provider

package
v0.1.4643 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 102 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package provider holds the model vendors magpie can reach: where each one lives, which protocols it speaks, the API key the user typed in, and which of its models should show up in the agents' pickers.

Provider keys are never read from environment variables. A provider is exactly what the user entered, kept in ~/.config/magpie/providers.json (mode 0600).

Index

Constants

View Source
const (
	MinCap = 1
	MaxCap = 99
)

MinCap and MaxCap bound an account's cap, in percent: none is no cap.

View Source
const (
	AuthBoth    = ""                  // x-api-key and Authorization: Bearer, the default
	AuthXAPIKey = catalog.AuthXAPIKey // x-api-key alone
	AuthBearer  = catalog.AuthBearer  // Authorization: Bearer alone
)

The headers a third-party Anthropic API's key goes in (Provider.AuthHeader).

View Source
const (
	SplitGranted = "Granted"
	SplitTopUp   = "Topped up"
)

Split labels: what a balance is made of, each a key the GUI words in the user's language (the TUI and CLI say it in English).

View Source
const (
	BillingPlan  = "plan"
	BillingPAYG  = "payg"
	BillingMixed = "mixed" // its keys are on a plan and on pay as you go
)

How a provider bills (EV_John_Liu on X: mark pay as you go apart from a token plan on Providers and Routing): on a plan, a subscription or token package paid ahead, or pay as you go, each call billed as used. The Providers list and a routing group's card say it. The user's word (Provider.Billing) stands; else it is read from what magpie knows of the provider: a signed-in account is a plan, a preset's plan or pay as you go endpoints (its Regions) say theirs, a key of a vendor or relay is pay as you go. A provider added by its address, a local server or another magpie says nothing until the user sets it.

View Source
const (
	ResetCaseWeek     = "week"
	ResetCaseExpiring = "expiring"
)

The two times an account the user lets spend its resets by itself spends one, each of which can be on alone (#2078): its week used up and no other account left (AutoUseCodexReset), and the one about to run out unused (SpendExpiringCodexResets).

View Source
const (
	CreditsOn    = "on"    // in its place, the default
	CreditsFirst = "first" // before moving to another account
	CreditsLast  = "last"  // after everything else
	CreditsOff   = "off"   // never: held when a window is used up
)

Ways a Codex account spends its credits, for SetCodexCreditsMode.

View Source
const (
	ResetUsedWeek     = "week"
	ResetUsedExpiring = "expiring"
	ResetUsedByHand   = "hand"
)

Why a reset was used: by itself as the account's week was used up and no other account could answer (AutoUseCodexReset), by itself as it was about to run out unused (SpendExpiringCodexResets), or by hand from the Usage page, the panel or the CLI (UseCodexReset).

View Source
const (
	MaxLimit      = 1000
	MaxQueueLimit = 10000
	MaxQueueWait  = 3600
)

MaxLimit bounds a limit on requests at once; MaxQueueLimit how many may wait, MaxQueueWait how long one waits, in seconds.

View Source
const (
	CloudflareJev       = "typesafe/jev"
	CloudflareClefModel = "@cf/cloudflare/clef"
	CloudflareClefFlash = "@cf/cloudflare/clef-flash"
)
View Source
const (
	ViaSystemOne  = "systemone"
	ViaVercel     = "vercel"
	ViaVercelEval = "vercel-eval"
	ViaCloudflare = "cloudflare"
	ViaGoogle     = "google"
)

The ways a decision API is asked, by where it is (DecideVia): TypeSafe's own System One; Vercel's AI Gateway, at its TypeSafe API (System One's questions and answers, with its own name for Jev) or, where an older setup points, at the AI SDK's evaluation models (a boolean for a noul and probabilities for a confidence); or Workers AI (System One's questions and answers, in Cloudflare's envelope and at an account's address); or Google's Decisions API (System One's questions over an input, at the Gemini API's /decisions, its key as x-goog-api-key).

View Source
const (
	DetectMax  = 30
	DetectWide = 8
)

A detection of many models asks at most DetectMax of them, DetectWide requests at a time, each waiting detectWait for its answer.

View Source
const (
	AffinitySession = "session"
	AffinityTurn    = "turn"
	AffinityOff     = "off"
	// AffinityStrict keeps a conversation on the key or account that
	// answered it whatever happens: resting, all but used up or past the
	// usage cap set on it, it is still the one asked, and its error goes
	// to the agent rather than the conversation to another. A usage cap
	// still keeps new conversations off it.
	AffinityStrict = "strict"
)
View Source
const (
	PatienceOff     = -1
	PatienceDefault = 60
	PatienceLongest = 240
)

PatienceOff, PatienceDefault and PatienceLongest are a group's Patience: none, the seconds a group waits that hasn't set it, and the most it may.

View Source
const (
	RedactOn     = "on"     // masked as Settings say, whatever its provider says
	RedactOff    = "off"    // sent as written
	RedactFollow = "follow" // saved: clears it, the providers' own say
)

A Group's Redact: what a request through it is masked by.

View Source
const (
	ShareMark    = "routing-group"
	ShareVersion = 1
)

A routing group shared as text (laincatx on X): one group's routing, rules and members, copied from one magpie and pasted into another. It says what it is (ShareMark) and in which format (ShareVersion), so a magpie can tell it from any other text and one made by a newer magpie from one it can read.

View Source
const (
	WhyGroupOff       = "switched off on the Routing page"
	WhyGroupUnticked  = "its models are unticked in their providers' model lists"
	WhyGroupTurnedOff = "its models are turned off for every request"
	WhyGroupNoServer  = "no provider serves its models now"
	WhyGroupAgentCant = "this agent can't use its models"
	// the three below the gateway serves: only the agent's lists leave
	// it out, and picking it puts it back in them (ShowFor)
	WhyGroupNarrowed  = "this agent is shown other providers and groups only"
	WhyGroupNotPicked = "not picked for this agent, which is shown only the models picked for it"
	WhyGroupTakenOut  = "taken out of this agent's model list"
)

Why a routing group of the user's is not offered to an agent (UnservedGroup.Why). The GUI says each in the page's language.

View Source
const (
	// TemplateSmart sends a turn the classifier judges hard to the
	// strongest model and one it judges easy to a cheap one; a compaction
	// goes to the cheap one too.
	TemplateSmart = "smart"
	// TemplateThrifty sends everything to a cheap model first, and to the
	// strongest when the agent asks for high reasoning or every cheap one
	// fails.
	TemplateThrifty = "thrifty"
	// TemplateSteady is the strongest model of each of up to three
	// providers, in order, so one vendor down or out of quota doesn't stop
	// the agent.
	TemplateSteady = "steady"
	// TemplatePlan is the strongest model of each of up to three
	// providers, those billed by a plan (a subscription or token plan)
	// before the pay-as-you-go ones, so the allowance already paid for is
	// spent first and a key is the last resort.
	TemplatePlan = "plan"
	// TemplateFast is the same strongest models as TemplateSteady, the
	// provider that has answered fastest lately first (Fastest).
	TemplateFast = "fast"
	// TemplateEven is the strongest model alone, from every provider that
	// serves it (up to four), taken in turn over all their keys and
	// accounts (Rotate).
	TemplateEven = "even"
)
View Source
const (
	IntentHard = "a hard task: designing, debugging, a change across several files, or planning"
	IntentEasy = "an easy task: a quick question, a small edit, a lookup, or running a command"
)

The intents TemplateSmart's classifier chooses between. Hard comes first, so a turn the classifier can't place stays on the strong model, the group's first.

View Source
const (
	NeedProvider  = "provider"
	NeedProviders = "providers"
	NeedCheap     = "cheap"
	// NeedPlan: no provider is billed by a plan, so "plan first" has
	// nothing to put first
	NeedPlan = "plan"
)
View Source
const (
	RefillMonth = "month"
	RefillWeek  = "week"
	RefillDay   = "day"
)

How often a balance typed refills.

View Source
const (
	SpendDay   = "day"
	SpendMonth = "month"
	SpendTotal = "total"
)

The periods a spend cap counts over: a calendar day or month in local time, or in all since it was set.

View Source
const (
	ExportSub2API  = "sub2api"
	ExportCLIProxy = "cliproxyapi"
)

Export formats.

View Source
const (
	MoveMoving = "moving" // under way, or cut short (put back at the next try)
	MovePlugin = "plugin" // the plugin has the id
	MovedBack  = "back"   // moved back to the built-in by an older magpie: moved again by itself
	MoveFailed = "failed" // the last try failed: the built-in carries on
	// MoveRemoved is a moved one whose plugin the user removed: its
	// accounts stay with the plugin's sign-ins, and the plugin installed
	// again has it at once (HandOver). Nothing installs it by itself.
	MoveRemoved = "removed"
)

A migration's states.

View Source
const (
	MiniMaxCodeID       = "minimax-code"
	MiniMaxCodeGlobalID = "minimax-code-global"
)

MiniMaxCodeID is the MiniMax Code plugin's provider (the China site), MiniMaxCodeGlobalID its international site's.

View Source
const (
	KindImage = "image"
	KindVideo = "video"
)

What a model makes, as the user says it (shen-joe, #1399): a provider set up with a base URL tells magpie its image and video models by its own model list ("kind": "image" or "video") or, for images, by a model's name. A relay whose list says neither — most don't — leaves a video model making nothing, and an image model with an odd name drawing nothing. The user can say so of one model instead, kept in settings' ModelKinds by "<provider id>/<model id>" as a model's name is: an image model is drawn with at the images API under the provider's base, a video model asked at its videos API, as one its list marks is (gateway's Drawers and customVideomakers).

View Source
const (
	SuffixOn  = "on"
	SuffixOwn = "own"
	SuffixOff = "off"
)

The ways the agents' lists name models (SuffixMode): every name with its provider's after it, as by default; all but the names the user gave models (#92); or none (#335).

View Source
const (
	OpenCodeGoChat      = "https://opencode.ai/inference/go/openai/v1"
	OpenCodeGoAnthropic = "https://opencode.ai/inference/go/anthropic"
	OpenCodeGoGemini    = "https://opencode.ai/inference/go/google/v1beta"
)

OpenCodeGo are the URLs Go's docs give each API (opencode.ai/docs/console/go, Endpoints).

View Source
const (
	PartnerShown  = "shown"  // the add sheet (the Plugins page) listed it
	PartnerOpened = "opened" // its row was opened
	PartnerKeys   = "keys"   // its key page was opened
	PartnerAdded  = "added"  // a provider was added from it (its plugin installed)
)

What is counted for a partner.

View Source
const (
	WorkDirHeader = "X-Magpie-Work-Dir"
	WorkGitHeader = "X-Magpie-Work-Git"
)

WorkDirHeader and WorkGitHeader tell a plugin's fetch where the agent that asked works, as the agent says it in its request: the folder, percent-encoded (decodeURIComponent reads it), and "yes" or "no" for whether it is in a git repository. Each is left off when it isn't known. The plugin host takes them off whatever the plugin sends on (host.js), so they reach no vendor as headers.

View Source
const (
	SessionToPluginHeader  = "X-Magpie-Session"
	SubagentToPluginHeader = "X-Magpie-Subagent"
)

SessionToPluginHeader and SubagentToPluginHeader tell a plugin's fetch the session the agent named (sessionOf: Claude Code's x-claude-code-session-id and the rest; for an OpenCode 1 subagent that names no separate root session, its x-opencode-parent-session-id unless the caller set X-Magpie-Session) and the subagent the request is of: Claude Code's x-claude-code-agent-id, Codex's spawn thread id (collab_spawn / thread_spawn / agent_job), or OpenCode's x-opencode-session-id when x-opencode-parent-session-id is set. The agent's own headers never reach a plugin, so a plugin that keeps state per conversation (Devin's cache keepalive) had only the request's text to go by, and Claude Code Auto's permission check, whose history grows in its one merged user message, looked like a new conversation each time (magpie-community/plugins#620). Each is left off when the agent named none. The plugin host takes them off whatever the plugin sends on, as it does the ones above.

View Source
const (
	CallerAgentHeader = "X-Magpie-Caller-Agent"
	CallerNameHeader  = "X-Magpie-Caller-Name"
	CallerViaHeader   = "X-Magpie-Caller-Via"
)

CallerAgentHeader, CallerNameHeader and CallerViaHeader tell a plugin's fetch the agent the request came from, as the gateway records it: its id (claude), the name people know it by (Claude Code), and, for a request another magpie passed on (a Remote magpie provider there), the computers it came through, the agent's first, comma-separated. Each value, and each computer, is percent-encoded UTF-8 (decodeURIComponent reads it). A request from this computer has no via. A plugin on the receiving magpie had only the request's text to go by, as the original agent stayed in the gateway (@febsincos on X). The plugin host gives them to chat.headers as input.caller too, and takes them off whatever the plugin sends on, as it does the ones above.

View Source
const (
	Ordered   = "order"
	Rotate    = "rotate"
	LeastUsed = "usage"
	Pace      = "pace"
	// Weighted spreads a provider's requests over its keys by each key's
	// weight (KeyAccount.Weight, #841), or a subscription's over its
	// accounts by each account's (AccountWeights), smoothly: 3 and 1 go
	// a, a, b, a…
	Weighted = "weight"
	// FreeFirst spends what costs nothing first: the models its vendor
	// serves at no cost to the subscription's allowance or credits, before
	// the ones that spend it (routes.FreeFirst).
	FreeFirst = "free"
	// Fastest goes by speed: the one that has answered the model fastest
	// lately — first token, then how fast it wrote — first; one not
	// measured lately gets a turn now and then to be (routes.Fastest).
	Fastest = "fast"
	// Cheapest goes by price: the member whose model costs least at the
	// request's time first — its vendor's peak hours and the provider's
	// rate windows read then — those alike in their listed order
	// (routes.Cheapest). A group's only: a provider's keys and accounts
	// all bill its one price.
	Cheapest = "cheap"
	// Drain stays on one key or account until it is used up, then goes
	// on to the next in the listed order, and stays on that one: one
	// before it that renews meanwhile doesn't take its requests back
	// (dzxx0496 on Discord; routes.Drain).
	Drain = "drain"
	// FreeExpiring spends free quota before paid, the free quota that is
	// lost soonest first: a free account (FreePlan, or a model that costs
	// nothing there, FreeModel) at its next reset or its credits' expiry,
	// then the paid ones as Smart orders them, and the used up last
	// (routes.FreeExpiring; wowbbs on Discord: five check-in accounts of
	// WorkBuddy, MiniMax, Trae and Qoder in one group). A group's only.
	FreeExpiring = "expiring"
	// SmallFirst sends a request to the member with the smallest context
	// window that holds it, so the big ones are kept for long requests
	// (routes.SmallFirst; yg6888 on X: Composer's 200K and Grok 4.7's
	// 256K never answered in a group of 1M models under Smart). Members
	// too small are left out as under every routing (roomy). A group's
	// only: a provider's keys and accounts serve one window.
	SmallFirst = "fit"
)

The routings besides the default, smart, in order.

View Source
const (
	SearchPickTurns = ""      // in turn, each search the next key
	SearchPickOrder = "order" // the first until it is refused
)

How a search picks among a search API's keys (SearchAPI.Pick).

View Source
const (
	SocketAuto = "auto"
	SocketOn   = "on"
	SocketOff  = "off"
)

The ways a provider's Socket is set: SocketAuto tries the Responses WebSocket and leaves a host that refuses its handshake to HTTP for a while; SocketOn tries it every turn; SocketOff is HTTP alone, where the default would be the socket. "" is the default (SocketMode).

View Source
const (
	ClientCodex      = "codex"
	ClientClaudeCode = "claude-code"
)

The clients a test can be asked as.

View Source
const (
	MaxTokensField     = "max_tokens"
	CompletionTokField = "max_completion_tokens"
)

Chat Completions has two names for a reply's length. OpenAI's own API reads max_completion_tokens and turns max_tokens away on its newer models ("Unsupported parameter: 'max_tokens' is not supported with this model. Use 'max_completion_tokens' instead.", GoxxKintBlade on X), while DeepSeek, Zhipu and most OpenAI-compatible relays read max_tokens alone.

View Source
const (
	HoldsLow        = "low"     // under HoldsFloor used
	HoldsNoClock    = "clock"   // no reset clock, so no known start
	HoldsBeforeLog  = "log"     // began before magpie's log does
	HoldsNoneRouted = "none"    // magpie routed nothing it counts in it
	HoldsCredits    = "credits" // a call in it may have been paid from credits
)

Why a window's whole isn't told (QuotaWindow.HoldsWhy), for the GUI to say "not enough data" and why rather than leave it out (#2045).

View Source
const (
	CheckinClaimed    = "claimed"    // claimed by magpie
	CheckinDone       = "done"       // in already, pressed in WorkBuddy or before
	CheckinIneligible = "ineligible" // the account can't take part
	CheckinInactive   = "inactive"   // no event running, or it has ended
	CheckinFailed     = "failed"     // no answer; tried again later, at its until if given
	// CheckinCaptcha is a plugin's check-in the vendor asked a captcha
	// of: the user checks in in its own app, magpie never solves one
	CheckinCaptcha = "captcha"
	// CheckinOwnApp is a check-in the user is to do in the vendor's own
	// app: an answer for the day. WorkBuddy's check-in answered 401 while
	// the sign-in works; Trae CN refused the claim with 9074, which says
	// so in its own words (#1920), not that only its app is paid
	CheckinOwnApp = "own-app"
)

What came of a day's check-in, WorkBuddyCheckin.Outcome.

View Source
const AIStudioChat = "https://generativelanguage.googleapis.com/v1beta/openai"

AIStudioChat is Google AI Studio's OpenAI-compatible base, the Google Gemini preset's Chat URL.

View Source
const AIStudioGemini = "https://generativelanguage.googleapis.com/v1beta"

AIStudioGemini is Google AI Studio's own Gemini API (generateContent), beside its OpenAI-compatible one.

View Source
const AccountMark = "#"

AccountMark puts a member's account after its model: "a/m:high#<id>".

View Source
const AntigravityRisk = "Google may suspend an Antigravity account it sees used outside Antigravity. Use one you can afford to lose."

AntigravityRisk is what magpie says before an Antigravity account is added.

View Source
const ArkDecision = "doubao-seed-2-1-lite-260915"

ArkDecision is the model Volcengine Ark answers System One with, in its beta (axelburks on Discord): doubao-seed-2-1-lite-260915. Asked on 11-01, Ark's other Seed models it serves the account (doubao-seed-2-1-pro-260628, doubao-seed-2-0-lite-260428) and deepseek-v4-1-flash were each refused 400 "does not support the SystemOne API".

View Source
const ArkSystemOneHeader = "ark-beta-systemone-api"

ArkSystemOneHeader is the header Ark's System One API is turned on by while it is in beta: without it, POST …/systemone is a bare 404.

View Source
const Auto = "auto"

Auto is the word that takes one part of a spec back to the vendor's list and models.dev.

View Source
const AutoFallback = "fallback"

AutoFallback is an Auto pick that is the model the account may pick by hand, Copilot having no Auto session to give it (copilotAutoFallback).

View Source
const AutoPrefix = "auto/"

AutoPrefix starts the id agents are given for a group magpie found: "auto/<model>".

View Source
const AzurePreset = "azure"

AzurePreset is the preset's id.

View Source
const BailianDecision = "decision-model-preview"

BailianDecision is Alibaba Cloud Bailian's decision model, asked on the same System One API as Jev (#647).

View Source
const BlockedHint = "the provider's network firewall blocked requests from this IP; wait a while, or switch to another network or proxy"

BlockedHint is what a vendor's edge firewall blocking magpie's address means, in plain words: Alibaba Cloud's (ESA, in front of zcode.z.ai) answers a 405 HTML page, "Sorry, your request has been blocked due to unusual activity", linking errors.aliyun.com. Nothing in the request is at fault and magpie changes nothing about it: the address is.

View Source
const ChatGPTAPIID = "chatgpt-api"

ChatGPTAPIID is the subscription's id, as a provider and in logins.json.

View Source
const ClaudeNoLimitsLine = "Usage report: no meters on this plan"

ClaudeNoLimitsLine is the line the gateway adds under /usage's text when Claude Code's usage_report has the server reporting no meters (limits: []): the plan has no 5-hour or weekly limits. Read as /usage's text alone (the subscription line, no window), it said "temporarily unavailable" (@andy_chen1997 on X, a Claude Enterprise seat). Its words say no "usage limit", which claudeUsageDenied reads as an account error.

View Source
const ClaudeRisk = "" /* 228-byte string literal not displayed */

ClaudeRisk is what magpie says before a Claude account is added, as the window does.

View Source
const ClineVersion = "3.5.54"

ClineVersion is the Cline desktop release magpie says it is to the Cline API.

View Source
const CodexAutoReview = "codex-auto-review"

CodexAutoReview is the reviewer model of OpenAI's that Codex asks its auto-review of an approval (the guardian) on.

View Source
const CodexDaemonRestart = "codex app-server daemon restart"

CodexDaemonRestart is the command that restarts Codex's app-server, for the user to run themselves.

View Source
const CodexDeviceSite = "device"

CodexDeviceSite is the "site" of a ChatGPT sign-in by device code (StartSignInWith): the window asks for it when it is opened from another computer.

View Source
const CodexSubagentLead = settings.CodexSubagentLead

CodexSubagentLead is the value of settings.CodexSubagentModel that puts Codex's subagents on their lead's model, whatever the lead names.

View Source
const CommandCodeGoHint = "" /* 204-byte string literal not displayed */

CommandCodeGoHint says where a Go plan's key works.

View Source
const CommandCodeMaxOutput = 200_000

CommandCodeMaxOutput is the most max_tokens Command Code takes at /alpha/generate, for any model: more is refused ("Too big: expected number to be <=200000 at params.max_tokens"). models.dev gives some of its models more (DeepSeek V4's 384000, MiniMax M3's 512000).

View Source
const CommandCodePlanID = "commandcode-plan"

CommandCodePlanID is the subscription's id, and its sign-in's.

View Source
const ContextSmallest = -1

ContextSmallest is a group's Context when agents are told the window of its smallest member.

View Source
const ConversationHeader = "X-Magpie-Conversation"

ConversationHeader carries the conversation a request belongs to, to a plugin's chat.headers hook as its session; it goes no further.

View Source
const CopilotAuto = "auto"

CopilotAuto is the model id that has Copilot pick the model.

View Source
const DecidersHeader = "X-Magpie-Deciders"

DecidersHeader asks a magpie's model list for its decision models too.

View Source
const DeepSeekHost = "api.deepseek.com"

DeepSeekHost is DeepSeek's own API. A relay or another base serving DeepSeek's models is not it.

View Source
const DrawersHeader = "X-Magpie-Drawers"

DrawersHeader asks a magpie's model list for its image models as well.

View Source
const EffortAuto = "auto"

EffortAuto is a group whose classifier picks each turn's reasoning effort (Group.Effort).

View Source
const EffortHeader = "X-Magpie-Effort"

EffortHeader is the header a plugin's fetch is told the request's effort in: one of the efforts its model's variants named, or another the client asked for (minimal, xhigh), for the plugin to pick its variant by.

View Source
const ExportRisk = "" /* 248-byte string literal not displayed */

ExportRisk is said wherever an export is offered.

View Source
const FallbackHeader = "X-Magpie-Fallback"

FallbackHeader, "1", tells a plugin's fetch that magpie needn't have the answer waited for: a request its vendor queues (Qoder's free models) comes back at once with the queue's 503 and Retry-After instead of being waited out for minutes. Without it the plugin waits. A model's test sends it, so a queued model's test says it is queued instead of running out of time. The plugin host takes it off whatever the plugin sends on (host.js), as it does the two above.

View Source
const FastWord = "fast"

FastWord is the last part of a member typed to be sent fast.

View Source
const FirstTokenWait = -1

FirstTokenWait is a group's FirstToken when the user picked Wait for it itself: every member waited for, whatever the default for every group. 0 is a group that sets nothing, which follows that default.

View Source
const FlatSep = "~"

FlatSep stands for each slash of a catalog id in its flat spelling.

MiniMax Code takes a SubAgent's model only as "<provider>/<model>" with one slash in the whole (/^[^/\s]+\/[^/\s]+$/, #1387), and its provider for magpie is "custom_provider:magpie", so a model under it can't hold a slash: "bb-codex/gpt-6.1-sol" is written there as "bb-codex~gpt-6.1-sol", and the gateway takes that back to the catalog id (Unflat). A tilde is in no id a provider was seen to serve but OpenRouter's "~anthropic/…" latest-aliases, which flatten to "openrouter~~anthropic~…", still one entry's.

View Source
const FreePrefix = "free:"

FreePrefix starts a group's member rule that takes, of the models the rest of it matches, only those their catalog marks free (Entry.Free, catalog.Model's: the vendor's or its plugin's own word, as the catalog was last read): "free:workbuddy/*" is WorkBuddy's free models, today's and those its next list marks so (#5903). The flag alone decides: a model listed at $0, at a rate of 0, on an account named Free or with "free" in its id is not taken for one, and the rule is no promise that a request costs nothing — the flag is the catalog's, not the bill's. The rest is a glob, a "re:" pattern or an id, matched as on its own.

View Source
const FreshPace = 100 / (7 * 24.0)

FreshPace is the pace of an account with a whole week ahead of it: what one not known counts as.

View Source
const GPUStackPreset = "gpustack"

GPUStackPreset is GPUStack's preset id.

View Source
const GoogleDecision = "gemini-decision-1"

GoogleDecision is Google's decision model, gemini-decision-1, which the Gemini Developer API answers at its Decisions API (POST /v1beta/decisions) on an AI Studio key: typed noul, choice and score questions, as System One asks them, over an input (Google's docs, aistudio.google.com/docs/decisions-api, 2026-11-11).

View Source
const GrokFastTimes = 2

GrokFastTimes is how many times its model's price xAI sells a Grok model's fast variant at (grokFastPrice).

View Source
const GroupPrefix = "group/"

GroupPrefix starts a group's id in the catalog: "group/<id>".

View Source
const HarnessOnlyHint = "" /* 201-byte string literal not displayed */

HarnessOnlyHint says what the refusal means and what to do.

View Source
const HoldsFloor = 5.0

HoldsFloor is the least share used a window's whole is reckoned from: below it a percent the vendor rounds is too coarse to scale up.

View Source
const ImageLane = "images"

ImageLane is the name of a ChatGPT account's image window (QuotaWindow.Lane). Drawing with gpt-image-2 counts against an allowance of its own, apart from Codex's 5-hour and weekly windows (#6160). /wham/usage has no image window (additional_rate_limits is null), but each reply of the images API tells it, a 200's too: x-codex-active-limit names the image limit and its window's headers say when it renews (#6412), which the gateway keeps (ImageHeard). A refusal, usage_limit_reached, rests the image model until the time it names, or that window's renewal (ImageRest). So the row says that time, or "unknown": never a share, as the share the headers tell stayed 0 on an account that had drawn.

View Source
const JevLatest = "jev-latest"

JevLatest is the Jev a decision provider is asked with when the user picked none: TypeSafe's latest stable one.

View Source
const KeyHeldCode = "gateway_key_held"

KeyHeldCode is the error code a gateway answers a key held to a budget, models or accounts with, where its own accounts would be told (#1981): the key is someone else's to use, and is told its own limit alone.

View Source
const KeyReadOnlyCode = "gateway_key_read_only"

KeyReadOnlyCode is the error code a gateway answers a read-only key with on a route that uses or changes anything.

View Source
const KiloVersion = "7.8.3"

KiloVersion is the Kilo CLI release magpie says it is to the Kilo Gateway.

View Source
const ListWaitHeader = "X-Magpie-List-Wait"

ListWaitHeader asks a magpie's model list to be answered once it is other than the one If-None-Match names, waiting up to the seconds it says; at the end of the wait, 304 says it is the same.

View Source
const MLXServePreset = "mlx-serve"

MLXServePreset is the MLX-Serve preset's id.

View Source
const Manual = "manual"

Manual is a group's routing when the user picks which member it uses, as CC Switch has one provider on at a time (#317): every request goes to the member picked (Group.Pick), over its own keys or accounts; the others, and the rules, wait until another is picked or the group is routed otherwise. The pick is changed on the group's card, in a click.

View Source
const MaxAccountName = 64

MaxAccountName bounds an account's name, in characters.

View Source
const MaxCondText = 500

MaxCondText is how long a message condition's text may be, in characters.

View Source
const MaxExpiring = 20

MaxExpiring bounds the grants of credit that expires on one key.

View Source
const MaxIcon = 1 << 20

MaxIcon is the largest picture magpie keeps for a provider.

View Source
const MaxImagesLimit = 1000

MaxImagesLimit bounds a limit on the images one request may carry. No vendor lists more than a few hundred, and a number past this is a typo rather than a cap.

View Source
const MaxIntent = 200

MaxIntent is how long an intent may be, in characters.

View Source
const MaxKeyWeight = 1000

MaxKeyWeight is the most a key's weight can be.

View Source
const MaxOwnBalance = 1_000_000

MaxOwnBalance bounds a balance typed by hand, in USD or in yuan.

View Source
const MaxPartners = 12

MaxPartners is the most partners listed, of the add sheet's and of the Plugins page's each; the rest of a longer list are left out.

View Source
const MaxQuotaRest = 8 * 24 * 60

MaxQuotaRest bounds QuotaRest, in minutes: eight days, a week's window and a day over, the longest the gateway rests anyone out of quota.

View Source
const MaxRPMLimit = 10000

MaxRPMLimit bounds a limit on requests a minute.

View Source
const MaxSpendCap = 1_000_000

MaxSpendCap bounds a spend cap, in USD.

View Source
const MiMoID = "mimo-app"

MiMoID is the MiMo subscription's id, as a provider and in logins.json.

View Source
const MinRefreshEvery = 10 * time.Minute

MinRefreshEvery is the shortest RefreshEvery: a vendor's list changes over days, and asking it each minute only spends its rate limit.

View Source
const NewAPIUserHeader = "New-Api-User"

NewAPIUserHeader is where a new-api relay's /api/user/self wants the user's id, beside the access token.

View Source
const NoDetails = "refused with no details (an empty reply, often from a firewall or proxy in front of the API rather than the API itself)"

NoDetails is what an error with an empty body is said as: the upstream refused and gave no reason, which an API seldom does and a firewall or proxy in front of it often does.

View Source
const NoteLongest = 200

NoteLongest is how many characters a group's note keeps.

View Source
const OMLXPreset = "omlx"

OMLXPreset is the oMLX preset's id.

View Source
const OpenCodeAnonymousKey = "public"

OpenCodeAnonymousKey is the key OpenCode asks Zen with when no one is signed in to it, which Zen's free models answer.

View Source
const OpenCodeConsole = "https://opencode.ai/console"

OpenCodeConsole is where OpenCode shows a workspace's credits: the Credits card on the console's Overview, to its owners and admins.

View Source
const OpenCodeStub = "Not available in this session. Never call this tool."

OpenCodeStub describes a tool offered only for Zen's free tier to see, which the client doesn't have.

View Source
const OpenCodeVersion = "2.2.5"

OpenCodeVersion is the oldest OpenCode release magpie says it is to OpenCode's gateway: 2.2.5, npm's latest @opencode/cli on 2026-11-01. Since 2026-10-26 Zen's free tier answers 429 FreeUsageLimitError ("Free models work in OpenCode") to OpenCode 1.19.0's User-Agent whatever the request says (#3491). A fixed version goes stale as OpenCode updates itself, so the one sent is what OpenCode's own updater says is latest (openCodeLatest), never older than this.

View Source
const OpenRouterJev = "~typesafe/jev-latest"

Cloudflare's own decision models on Workers AI (ARNO on Discord): Clef and Clef Flash answer System One's questions as Jev does, but each is run at its own address (…/ai/run/@cf/cloudflare/clef) and takes the request as it is, its model named "clef" or "clef-flash", where Jev is a run of typesafe/jev with the questions as its input. OpenRouterJev is Jev as OpenRouter names it, the latest one.

View Source
const PartnersURL = "https://usemagpie.ai/api/partners"

PartnersURL is where the list is kept; MAGPIE_PARTNERS moves it, and MAGPIE_PARTNERS=off keeps to none.

View Source
const PricesHeader = "X-Magpie-Prices"

PricesHeader asks a magpie's model list for what each model costs there ("magpie_price"): a magpie that doesn't send it is told nothing more than before.

View Source
const QianfanSignInURL = "https://console.bce.baidu.com/qianfan/resource/token-plan"

QianfanSignInURL is the console page the plan is on, where the user signs in and runs the bookmarklet.

View Source
const QoderCNID = qoder.CNProviderKey

QoderCNID is the Qoder CN subscription's id, the same as Qoder CN's agent.

View Source
const RateWindowsMax = 8

RateWindowsMax is how many windows one provider can have (#2463).

View Source
const RegexpPrefix = "re:"

RegexpPrefix starts a member that is a regular expression over the whole "provider/model" id, in any case as a glob is: "re:openrouter/.*:(free|beta)". "(?-i)" in it makes case matter from there on: "re:(?-i)openrouter/.*:FREE".

View Source
const RemoteAgentModelsPath = "/v1/magpie/agent-models"

RemoteAgentModelsPath is where a remote magpie tells the models its agents are on (KoiLx0 on X: several computers on one remote magpie, each setting every agent's models again by hand, and again after each change there). It is answered as the Library is: to the computer itself and to a full-access key of a magpie shared on the local network.

View Source
const RemoteAgentModelsWait = 8 * time.Second

RemoteAgentModelsWait is how long a remote magpie has to tell its picks.

View Source
const RemoteCardsPath = "/v1/magpie/quotas/cards"

RemoteCardsPath is the gateway's answer of its kept cards.

View Source
const RemoteCodexResetPath = "/v1/magpie/quotas/codex-reset"

RemoteCodexResetPath has the gateway spend one of its Codex account's rate-limit resets (?user=, the account always named; &credit=, one of its resets.each, else the one that runs out first), as its Usage page's "Use a reset" does (#3850, prgrmrwy): a reset shown on another magpie's card, or in an app reading the cards, can be used from there too. It can't be undone, so the gateway takes it only with a gateway key of full access, never from a page or app it lets in without one.

View Source
const RemoteKeyLimitPath = "/v1/magpie/limit"

RemoteKeyLimitPath is the gateway's answer of the calling key's limit.

View Source
const RemoteLibraryPath = "/v1/magpie/library"

RemoteLibraryPath is where a remote magpie tells its Library's prompts and skills (KoiLx0 on X: managed on one computer, not on every client). It is answered to the computer itself and to a full-access gateway key of a magpie shared on the local network, as the quotas are.

View Source
const RemoteLibraryWait = 90 * time.Second

RemoteLibraryWait is how long a remote magpie has to send its skills.

View Source
const RemoteMagpieEvery = "10m"

RemoteMagpieEvery is how often, as RefreshEvery writes it, the gateway fetches a Remote magpie's list when its user set no RefreshEvery. Its list is the other magpie's models as they are now: a model that comes there later (a ZCode gift plan's GLM-5.3-Trial, listed once its plugin read the gift; a provider, plugin or routing group added there) reached this magpie only when Fetch models was pressed in its editor, and a trial a day long could pass unseen (6igsteven on Discord, 10-24). It is a list on the other computer's magpie, read from its memory, so asking it often costs nothing a vendor sees. "off" (magpie provider refresh-every <id> off) asks it only when told, as before.

View Source
const RemoteMagpiePreset = "remote-magpie"

RemoteMagpiePreset is the preset's id.

View Source
const RemoteProvePath = "/v1/magpie/prove"

RemoteProvePath is where a magpie proves, with no key sent to it, that it holds a gateway key: POST {"nonce": hex, "key_id": RemoteKeyID(key)} is answered {"proof": hex of RemoteProof(key, nonce, the address it was reached at)}, or 404 when no enabled gateway key there has that id (the gateway's remote_prove.go).

View Source
const RemoteRefreshPath = "/v1/magpie/quotas/refresh"

RemoteRefreshPath has the gateway read a card (?provider=, &user=) again, or every card when no provider is named, then answer as RemoteCardsPath.

View Source
const RemoteResetWait = 35 * time.Second

RemoteResetWait is how long a remote magpie is waited for to spend a reset: its use (20s at most) and its wait for routing to know (10s).

View Source
const RemoteUpdatePath = "/v1/magpie/update"

RemoteUpdatePath has the gateway update this magpie to its channel's latest release, once it is newer than ?version= says the asker runs.

View Source
const RestCapOff = -1

RestCapOff is RestCap set to off (`magpie provider rest-cap <id> off`): a key or account of the provider that fails without saying why — a relay's or an account pool's 5xx, a dropped connection — doesn't rest at all, and is asked again by the next request as if it hadn't failed (Kismet Alan on Discord: an aggregator's unknown errors fail now and then, and the next request often goes through). What the vendor said plainly still rests it as ever: out of quota or credit, rate limited, its key refused (401, 403), its model not served, its window full.

View Source
const (

	// SIWCUsageURL is where a ChatGPT account's usage is shown
	SIWCUsageURL = "https://chatgpt.com/settings/usage"
)
View Source
const Scheme = "magpie"

Scheme is the URL scheme magpie registers with the system.

View Source
const SentModelHeader = "X-Magpie-Sent-Model"

SentModelHeader is how a plugin says the model id it sent the vendor, when it picks one magpie can't: Antigravity's plugin sends a family as the variant of it the effort picks from the account's own list (gemini-3.1-pro at high goes as gemini-3.1-pro-high). The gateway keeps it as the try's and the ledger row's Wire, read from a plugin's answer only; like every X-Magpie- header it never reaches the agent.

View Source
const SessionPlaceholder = "${sessionId}"

SessionPlaceholder is what a string value of extraBody writes for the conversation's id.

View Source
const SignInHeader = "X-Magpie-Sign-In"

SignInHeader is how a plugin says what its answer means for the account's sign-in, whatever its status, so it can answer with the status its built-in did: "expired" marks the account lapsed, as a built-in whose vendor refused the sign-in marked it, though the status be a 502; "kept" leaves the account as it is, as a built-in answering a 401 of the vendor's without its sign-in refused did; "renewed" clears the mark, as a built-in whose sign-in renewed took it off whatever the request then met. Without it a 401 marks the account and a success clears the mark.

View Source
const SpentShare = 98

SpentShare is the share of an allowance past which an account is all but used up: Smart routing keeps it for when no other can take a request, and the agent signed in to it is signed in to another.

View Source
const SubagentPlaceholder = "${subagentId}"

SubagentPlaceholder is what a header or an extraBody string writes for the Claude Code subagent a request is of (yetone/magpie#2937).

View Source
const ThreadPlaceholder = "${threadId}"

ThreadPlaceholder is what a header or an extraBody string writes for the thread's id.

View Source
const TraeCNID = "trae-cn"

TraeCNID is the Trae CN plugin's provider.

View Source
const TraeRefusedWords = "Trae CN refused this check-in (9074: too many taking part); check in in the Trae CN app"

TraeRefusedWords is what an account Trae CN refused a claim 9074 is told, in the TUI and CLI (the GUI says it in each language): what Trae did, and where the check-in can still be done.

View Source
const UnknownRuleWord = "unknown "

UnknownRuleWord starts the error for a word ParseRule doesn't know.

View Source
const VertexPreset = "google-vertex"

VertexPreset is the preset's id.

View Source
const VideomakersHeader = "X-Magpie-Videomakers"

VideomakersHeader asks a magpie's model list for its video models as well: a magpie that doesn't send it would take grok-imagine-video, whose id says "imagine", for an image model.

View Source
const WBRestrictedHint = "" /* 152-byte string literal not displayed */

WBRestrictedHint is what magpie adds to WorkBuddy's 403 code 11140 "request illegal" (#1849), whose displayMsg says "Your account has been restricted due to unusual activity": the account, not the request, is out until WorkBuddy lifts the restriction, which its appeal asks for. The gateway reads it as the account restricted (failRestricted), the plugin adds the same words, and the Routing page says it apart.

View Source
const WaitHeader = "X-Magpie-Wait"

WaitHeader tells a magpie's gateway how many seconds its client waits for the answer: a model test asking a remote magpie sends its own wait, and the gateway takes no retry pause or patience round that would end past it, so the test is told the error rather than running out of time (plugins#827). Like every X-Magpie- header it goes no further.

View Source
const WorkBuddyAIID = "workbuddy-ai"

WorkBuddyAIID is WorkBuddy AI's subscription, the international build's.

View Source
const WorkBuddyRisk = "" /* 291-byte string literal not displayed */

WorkBuddyRisk is what magpie says before a WorkBuddy or WorkBuddy AI account is added, as the window does (WORKBUDDY_RISK in app.js).

View Source
const WorkspaceID = "{WorkspaceId}"

WorkspaceID stands in a decision API's address for the user's Bailian workspace id (#647), which the editor and `workspace=` fill in.

View Source
const YouFreeSearch = "https://api.you.com/v1/agents/search"

YouFreeSearch is You.com's search that takes no key (#1626): 100 searches a day for each address, then 429. With a key, You.com is asked at its Base, ydc-index.io, instead.

View Source
const ZCodeRestrictedHint = "" /* 209-byte string literal not displayed */

ZCodeRestrictedHint is what the ZCode plugin (0.1.27 on) adds to the Start Plan's 405 code 3012, "request has been blocked due to unusual activity": ZCode's risk control blocked the account, ZCode's own app included (plugins#348), until ZCode support lifts it. The gateway reads it as the account restricted (failRestricted), and the Routing page says it apart.

View Source
const ZhipuSearchPath = "/api/mcp/web_search_prime/mcp"

ZhipuSearchPath is where a GLM Coding Plan's web search MCP server is, on the plan's own host: Zhipu's Web Search MCP at open.bigmodel.cn/api/mcp/web_search_prime/mcp and Z.ai's at api.z.ai/api/mcp/web_search_prime/mcp, a Streamable HTTP server asked with the plan's key as a Bearer (docs.bigmodel.cn/cn/coding-plan/mcp/search-mcp-server, docs.z.ai/devpack/mcp/search-mcp-server).

Variables

View Source
var (
	CodexAppCrashed  func(since time.Time) (at time.Time, crashed, known bool)
	CodexAppRelaunch func(ctx context.Context) error
)

CodexAppCrashed and CodexAppRelaunch are set by the agent package. CodexAppCrashed says whether the Codex app logged the page it shows when it can't go on (fatal_error_broadcasted) at or after since, and when; known false when its logs can't be read. CodexAppRelaunch quits the app and opens it again, erring where it can't.

View Source
var (
	CodexAppOpen   func(ctx context.Context) (open, known bool)
	CodexAppReopen func(ctx context.Context) error
)

An app-server ended is not yet one started in its place. The app starts another only once it has read the end of the old one's stdout and seen it exit (its StdioConnection closes on both, ChatGPT.exe 26.1021's app.asar). On Windows every process the app-server started inherits that stdout (Rust's Command creates children with bInheritHandles), so an MCP server or tool command left running after it holds the pipe open: the app never sees it close, starts no other, and every send says "Codex app-server process is not available" until Codex is quit and opened again (蛋仔 on Discord, 10-30; reproduced on the Windows box with codex 0.164's app-server and an MCP server that outlived it: its stdout ended only when the MCP server did). So once the ones ended are gone, magpie waits codexAppBackWait for a new one; when none comes while the app still runs, it has the agent package reopen the app (CodexAppReopen), and says it is stuck when that can't be done.

CodexAppOpen, set by the agent package, says whether the Codex desktop app runs here; known false when that can't be told. CodexAppReopen quits it and opens it again, erring where magpie doesn't (macOS, where a reopen opens a new window: the user does it).

View Source
var (
	ErrCodexAppGone    = errors.New("the Codex app isn't running")
	ErrCodexAppNoEnd   = errors.New("the Codex app's app-server couldn't be ended")
	ErrCodexAppNotBack = errors.New("the Codex app didn't start another app-server")
)

What RestartSwitchedCodexApp found when it couldn't restart the app's app-server; the agent package says each in the reader's language.

View Source
var (
	RemoteHubAsk   func(id string) bool
	RemoteHubFound func(id string)
)

RemoteHubAsk, set by the library, is whether it would give the router of the Remote magpie id a server; RemoteHubFound is called once that magpie says it serves one. Nil, nothing is asked.

View Source
var (
	ZCodeZaiBase      = "https://api.z.ai/api/anthropic"
	ZCodeBigModelBase = "https://open.bigmodel.cn/api/anthropic"
)

Where ZCode's coding plan and its sign-in are; vars so tests can point them elsewhere.

Affinities are how long a conversation stays with the key or account that answered it: "" auto, as long as what the vendor cached of it is worth keeping; for the whole session; within a turn only, free to move when the user speaks again; never; or strictly: for the whole session, never moved to another key or account however it answers (#1797).

View Source
var AllBuilt atomic.Int64

AllBuilt counts the times All built the list anew, for tests.

View Source
var AllBuiltAt atomic.Int64

AllBuiltAt is when the build All last counted was asked for (allProviders entered, the hold's rule read at once after), for a test to judge a build by when it was asked, not by when the request that asked began (#2965).

AuthChoices are the values Provider.AuthHeader takes.

View Source
var ClaudeHandedOver func(user string)

forgetClaudeDir removes a saved account's config directory altogether. ClaudeHandedOver is told of a saved Claude account switched in to Claude Code itself, whose directory forgetClaudeDir has just removed: a Claude Code still running there (the gateway's, waiting for its conversation's next turn) holds the refresh token that is Claude Code's own now, and a refresh of it there would leave Claude Code's copy refused, the account signed out (0xAncientTwo on X). The gateway sets it.

View Source
var ClaudeThroughMagpie = func() bool { return false }

ClaudeThroughMagpie is set by the agent package: whether Claude Code's settings send its requests to magpie's gateway (ANTHROPIC_BASE_URL), whatever its model and however it signs in there. NextLogin then never moves its sign-in off a spent account. false until it is set, and in a process without the agent package.

View Source
var CodexAppDesk func() time.Time

CodexAppDesk is set by the agent package: when magpie named its model list for the Codex app in Codex's config (model_catalog_json beside the ChatGPT sign-in), zero while it names none or the time isn't known. The app-server reads model_catalog_json only as it starts and never again (codex-rs app-server model_catalog.rs reloads on an account change alone), and the app keeps one app-server for every window, so an app that started before the list was named shows Codex's own models alone until it is quit (not_4O4 on X, the Windows app: a new window and a new project on D: listed GPT alone). Unlike a new list, which changes with every pick and is left for the app's next launch (#4550), the list is named once, as Codex is connected or the list first becomes known: its app-servers from before are restarted for it once, as for a Connect.

View Source
var CodexAppRoute func() (route string, out, known bool)

CodexAppRoute is set by the agent package: what in Codex's config the app-server reads as it starts and magpie writes (its provider and base URL: route, compared, never parsed), and whether magpie is Codex's provider for its used-up ChatGPT account (out, AppOut); known false when Codex's config can't be read. Nothing the Codex app writes itself (its model or effort pick) and not the model list is in route, or a pick would restart it.

View Source
var CodexBase = "https://chatgpt.com/backend-api/codex"

CodexBase is where a ChatGPT account's Codex requests go; a var so tests can point it elsewhere.

View Source
var CodexBeforeAppEnd func(home string)

CodexBeforeAppEnd is set by the agent package: it is called with Codex's home just before the app's app-server is ended for a change of where Codex goes, to put the chats the app has open onto the provider Codex is on now. The app-server that starts in its place resumes them on their row's provider, and Codex refuses a chat of another one.

View Source
var CodexHoldMatters func() bool

CodexHoldMatters is set by the agent package: whether Codex is wired to magpie beside its ChatGPT sign-in, so that magpie becomes its provider while the Codex app holds the account (codex.out), or is its provider for that already. Nil or false: what the app holds changes nothing.

View Source
var CodexNoAccount func() bool

CodexNoAccount is set by the agent package: whether the provider Codex's config names takes no ChatGPT account at all (a [model_providers] table without requires_openai_auth = true, such as magpie's with the user's own requires_openai_auth = false; danzi002 on Discord). Such a provider sends its own key, and the app-server answers account/read with no account for it (codex-rs ModelProviderInfo::account_state and resolve_provider_auth), so which ChatGPT account auth.json holds is nothing the app-server, the Codex app or the daemon goes by: an account switch restarts none of them. false when it can't be told.

View Source
var CodexTakeoverOff func() bool

CodexTakeoverOff is set by the agent package: whether the user has turned off magpie's takeover of Codex's used-up account (AppOutOff): its sign-in set to Always ChatGPT, as the takeover note's Keep on ChatGPT does, or Codex not connected. The takeover ending while it says so is the user's change, and the Codex app's app-server is restarted for it as for a Connect, Restart the Codex app to follow off too: the one the takeover started answers account/read with no account, so the app shows none of its ChatGPT projects or chats till it restarts, which the user who turned the takeover off to have them back can't tell (Herzz____ on X, the Windows app's project list empty). Asked only as the takeover ends; false while it isn't set.

View Source
var CondFields = []string{"tokens", "effort", "agent", "subagent", "message", "system", "last"}

CondFields are the fields a condition can look at. system and last are the request's texts as the agent sent them (SucroseMoE on X: a harness's title or compaction call told apart by its prompt, with no model asked): system, each of its system prompt's blocks; last, each text of its last user message.

View Source
var CondOps = map[string][]string{
	"tokens":   {"gte", "gt", "lt", "lte"},
	"effort":   {"is", "not", "gte", "lte"},
	"agent":    {"is", "not"},
	"subagent": {"is", "not"},
	"message":  {"contains", "excludes", "starts", "matches"},
	"system":   {"contains", "excludes", "starts", "matches"},
	"last":     {"contains", "excludes", "starts", "matches"},
}

CondOps are each field's ways to compare.

View Source
var CopilotTokenURL = "https://api.github.com/copilot_internal/v2/token"

CopilotTokenURL trades the GitHub OAuth token for a short-lived Copilot session token; a var so tests can point it elsewhere.

View Source
var CopilotUserURL = "https://api.github.com/copilot_internal/user"

CopilotUserURL says where an account's Copilot API is; a var so tests can point it elsewhere.

View Source
var CopilotWSLDirs func() []string

CopilotWSLDirs, set by internal/agent, are the Copilot CLI's folders (~/.copilot), as magpie opens them, in the WSL distros that run now: magpie on Windows finds a Copilot CLI signed in inside one (#723, jia2). Where ~/.copilot is a link the folder is where it leads (#4502). nil, or none, off Windows. A stopped distro isn't in it: reading its files would start it.

View Source
var CursorExecutable = func() string {
	for _, name := range []string{"cursor-agent", "agent"} {
		if p, err := proc.LookPath(name); err == nil && (name == "cursor-agent" || isCursorAgent(p)) {
			return p
		}
	}
	home, _ := os.UserHomeDir()
	for _, p := range append([]string{filepath.Join(home, ".local", "bin", "cursor-agent")}, proc.SystemDirs("/usr/local/bin/cursor-agent", "/opt/homebrew/bin/cursor-agent")...) {
		if st, err := os.Stat(p); err == nil && !st.IsDir() {
			return p
		}
	}
	return ""
}

CursorExecutable finds the cursor-agent CLI; a var so tests can fake it.

View Source
var DefaultReplyHeaders = []string{"Request-Id", "X-Request-Id", "X-Oneapi-Request-Id"}

DefaultReplyHeaders are passed on from every provider's reply, without a word from the user: request ids, opaque to everyone but the vendor, which magpie sets no header of its own under. OpenAI's and Anthropic's names, and one-api's (new-api and the relays built on it).

View Source
var Described func() bool

Described is set by the gateway: whether an image sent to a model that can't see is described to it by one that can (Settings › Vision). Agents are then told every model takes images; told a model is text-only, they turn the user's image away before magpie is asked (Codex: "does not support image input").

View Source
var DevinExecutable = func() string {
	if p, err := proc.LookPath("devin"); err == nil {
		return p
	}
	home, _ := os.UserHomeDir()
	for _, p := range append([]string{filepath.Join(home, ".local", "bin", "devin")}, proc.SystemDirs("/usr/local/bin/devin", "/opt/homebrew/bin/devin")...) {
		if st, err := os.Stat(p); err == nil && !st.IsDir() {
			return p
		}
	}
	return ""
}

DevinExecutable finds the devin CLI; a var so tests can fake it.

View Source
var Efforts = []string{"low", "medium", "high", "xhigh", "max"}

Efforts are the reasoning levels a rule can ask for, lowest first.

View Source
var ErrListOff = errors.New("its model list is off: add each model by its id")

ErrListOff is what a Fetch of a provider whose list is off answers, with no request made.

View Source
var ErrNoURL = errors.New("type the base URL first")

ErrNoURL is a detection with no URL to ask at.

View Source
var ErrSIWCSignIn = errors.New("the ChatGPT sign-in has expired — sign in again")

ErrSIWCSignIn is an account OpenAI no longer refreshes: it must be signed in again.

View Source
var ErrUnreadable = errors.New("providers.json can't be read")

ErrUnreadable is a providers.json that is there but can't be read or decoded: never an empty catalog, to list as none, back up or write over.

View Source
var ExtraBodyReserved = []string{"model", "stream", "messages", "input", "contents", "system", "systemInstruction", "system_instruction", "instructions", "tools"}

ExtraBodyReserved are the fields extraBody can't set: the model and whether to stream, which magpie decides for routing and reads the reply by, and the conversation itself — its messages, input or contents, its system prompt and instructions, its tools.

View Source
var GitHubUserURL = "https://api.github.com/user"

GitHubUserURL says whose a GitHub token is; a var so tests can point it elsewhere.

View Source
var GrokBase = "https://cli-chat-proxy.grok.com/v1"

GrokBase is the CLI's backend; a var so tests can point it elsewhere.

View Source
var GrokExecutable = func() string {
	home, _ := os.UserHomeDir()
	path := append(filepath.SplitList(os.Getenv("PATH")), registryPath()...)
	for _, c := range grokCandidates(runtime.GOOS, home, GrokHome(), appdir.Getenv("GROK_BIN_DIR"), path) {
		if isFile(c.path) && (c.own || isGrokBuild(c.path)) {
			return c.path
		}
	}
	return ""
}

GrokExecutable finds the Grok Build CLI; a var so tests can fake it.

View Source
var ImageHeard func(agent, user string, now time.Time) (CodexLimit, bool)

ImageHeard is, set by the gateway, the image window the ChatGPT account user's last reply of the images API told, while it has not renewed; false when none told one.

View Source
var ImageRest func(agent, user string, now time.Time) (time.Time, bool)

ImageRest is, set by the gateway, when the image model of the ChatGPT account user (as its usage is read, Account.UsageAgent) is back, while the vendor's refusal keeps it resting; false when it is not.

View Source
var KeySpent func(keyID string, start time.Time) float64

KeySpent is usage.KeySpent, which package usage sets: what the calls magpie sent on the key keyID from start on cost, in USD. nil (a test of this package alone) counts nothing.

View Source
var KiroExecutable = func() string {
	if p, err := proc.LookPath("kiro-cli"); err == nil {
		return p
	}
	home, _ := os.UserHomeDir()
	for _, p := range append([]string{filepath.Join(home, ".local", "bin", "kiro-cli")}, proc.SystemDirs(
		"/Applications/Kiro CLI.app/Contents/MacOS/kiro-cli", "/usr/local/bin/kiro-cli", "/opt/homebrew/bin/kiro-cli")...) {
		if st, err := os.Stat(p); err == nil && !st.IsDir() {
			return p
		}
	}
	return ""
}

KiroExecutable finds kiro-cli, which refreshes its own sign-in; a var so tests can fake it. The installer puts it in ~/.local/bin, and on macOS inside Kiro CLI.app as well.

View Source
var LeaveOutSelf = true

LeaveOutSelf is whether a Remote magpie found to be this magpie is left out. The gateway's tests serve their Remote magpie from their own process, and turn it off.

View Source
var Levels = []string{"none", "minimal", "low", "medium", "high", "xhigh", "max"}

Levels are the reasoning levels a model whose own aren't known can be given.

View Source
var MemberEfforts = []string{"none", "minimal", "low", "medium", "high", "xhigh", "max"}

MemberEfforts are the levels a group's member may be fixed at, lowest first: the words agents and vendors use for reasoning effort.

View Source
var ModelMoved func(from, to string) error

ModelMoved, when set, gives what another package keeps of a provider's model ("<provider>/<model>") the id it is listed by now (SetModelID): the gateway keys' models (access), which this package can't reach.

View Source
var ModelUnserved = lazyre.New(`(?i)model.{0,80}(not (supported|accessible|available|found|enabled|allowed)|unsupported|does ?n[o']t exist|may not exist or you may not have access|unknown|invalid)|not_found_error.{0,40}"model: |(no such|unknown|invalid|unsupported) model|model_not_found|has no provider supported|deployment[ _]?not[ _]?found|deployment.{0,60}does ?n[o']t exist|模型.{0,12}(不存在|不支持|无权|未开通)`)

ModelUnserved are how a vendor says the model isn't one it serves this key, or this way — words another provider, or key, may not answer with (the gateway's unservedWords, read decoded: catalog.Words): ModelScope's 400 for a model id none of its instances serves, "Model id : … , has no provider supported" (#2887), and Azure OpenAI's DeploymentNotFound, whose message "The API deployment for this resource does not exist" a relay passes on as a 400 (its 404 fails over by its status already). And Anthropic's 404 for a model the account may not call: through Claude Code "There's an issue with the selected model (claude-mythos-5-2). It may not exist or you may not have access to it.", from the API {"type":"not_found_error","message":"model: claude-mythos-5-2"} — that model rests on that account, not the account for all its models (ZacharyZhang on X).

View Source
var OpenCodeToolSchemas = map[string]string{
	"edit":  `{"type":"object","properties":{"path":{"type":"string","description":"File to edit"},"oldString":{"type":"string","description":"Exact text to find and replace"},"newString":{"type":"string","description":"Text to replace oldString with (must differ from oldString)"},"replaceAll":{"type":"boolean","description":"Whether to replace every occurrence of oldString. When false, oldString must match exactly once. Defaults to false."}},"required":["path","oldString","newString"],"additionalProperties":false}`,
	"glob":  `{"type":"object","properties":{"pattern":{"type":"string","description":"Glob pattern to match files against"},"path":{"type":"string","description":"Directory to search. Defaults to the current working directory."},"hidden":{"type":"boolean","description":"Include hidden files and directories (default: false)."},"limit":{"type":"integer","exclusiveMinimum":0,"description":"Maximum number of matching files to return (default: 100)"}},"required":["pattern"],"additionalProperties":false}`,
	"grep":  `{"type":"object","properties":{"pattern":{"type":"string","minLength":1,"description":"Regular expression or literal text to match in file contents."},"path":{"type":"string","description":"File or directory to search. Defaults to the current working directory."},"include":{"type":"string","description":"Glob pattern to filter files (for example, \"*.js\" or \"*.{ts,tsx}\")"},"literal":{"type":"boolean","description":"Treat ` + "`pattern`" + ` as exact text instead of a regular expression (default: false)."},"caseSensitive":{"type":"boolean","description":"Use case-sensitive matching (default: true)."},"limit":{"type":"integer","exclusiveMinimum":0,"description":"Maximum number of matching lines to return (default: 100)"}},"required":["pattern"],"additionalProperties":false}`,
	"read":  `{"type":"object","properties":{"path":{"type":"string","description":"File or directory to read"},"offset":{"type":"integer","minimum":0,"description":"The line or directory entry to start reading from (1-based)"},"limit":{"type":"integer","minimum":0,"description":"The maximum number of lines or directory entries to read (defaults to and capped at 2000)"}},"required":["path"],"additionalProperties":false}`,
	"shell": `{"type":"object","properties":{"command":{"type":"string","description":"Shell command string to execute"},"workdir":{"type":"string","description":"Working directory to execute the command in. Defaults to the current working directory. When possible, avoid changing directories in the command and set the working directory here instead."},"timeout":{"type":"integer","minimum":0,"description":"Timeout in milliseconds. Set to 0 to disable the timeout. Defaults to 120000 for foreground commands. Background commands have no timeout by default."},"background":{"type":"boolean","description":"Run the command in the background and return immediately (useful for dev servers and long-running builds). You do not need to use '&' at the end of the command when using this parameter. You will be notified when it completes. DO NOT poll for completion."}},"required":["command"],"additionalProperties":false}`,
}

OpenCodeToolSchemas are the parameters OpenCode 2.2.5 gives its core tools, as it sent them to Zen (testdata/opencode-2.2.5-chat.json). Zen's free tier answers 403 FreeTierError to one offered with no parameters.

View Source
var OpenCodeTools = []string{"edit", "glob", "grep", "read", "shell"}

OpenCodeTools are OpenCode 2's core tools, which Zen's free tier wants offered, by name: shell, not 1.x's bash (what 2.2.5 sent on 2026-11-01).

View Source
var PluginAgentGoing func(spec string) error

PluginAgentGoing, set by internal/agent, takes magpie out of the config of the agent the plugin spec adds and puts back what the user had, as `magpie <agent> default` does. It runs before the plugin is turned off or removed, while magpie still knows the agent: after, nothing could (#3810).

Protocols in the order magpie prefers them when it has to translate.

View Source
var ReckonHolds func(qs []SubscriptionQuota, now time.Time) []SubscriptionQuota

ReckonHolds is usage.WithWindowHolds, which package usage sets: it reads the usage log, which this package can't import. QuotaReport, KeptQuotaReport and RefreshReport tell each window's whole by it, as the Usage page does (#2333); nil, where usage isn't linked in, leaves it out.

View Source
var RemoteHubWait = 5 * time.Second

RemoteHubWait is how long a Remote magpie's info is waited for.

View Source
var SearchVendors = []SearchVendor{
	{ID: "tavily", Name: "Tavily", Base: "https://api.tavily.com", KeysURL: "https://app.tavily.com/home", Paths: []string{"/search"}},
	{ID: "brave", Name: "Brave Search", Base: "https://api.search.brave.com", KeysURL: "https://api-dashboard.search.brave.com/app/keys", Paths: []string{"/res/v1/web/search"}},
	{ID: "exa", Name: "Exa", Base: "https://api.exa.ai", KeysURL: "https://dashboard.exa.ai/api-keys", Paths: []string{"/search"}},
	{ID: "firecrawl", Name: "Firecrawl", Base: "https://api.firecrawl.dev", KeysURL: "https://www.firecrawl.dev/app/api-keys", Paths: []string{"/v2/search"}},
	{ID: "you", Name: "You.com", Base: "https://ydc-index.io", KeysURL: "https://you.com/platform", KeyOptional: true, Paths: []string{"/v1/search", "/v1/agents/search"}},
	{ID: "deepseek", Name: "DeepSeek", Base: "https://api.deepseek.com", KeysURL: "https://platform.deepseek.com/api_keys", Paths: []string{"/v1/tools/search"}},

	{ID: "volcengine", Name: "Doubao Search (Volcengine)", Base: "https://open.feedcoopapi.com", KeysURL: "https://console.volcengine.com/search-infinity/api-key", Paths: []string{"/search_api/web_search"}},

	{ID: "wsa", Name: "Yuanbao Search (Tencent Cloud)", Base: "https://api.wsa.cloud.tencent.com", KeysURL: "https://console.cloud.tencent.com/wsapi/index", Paths: []string{"/SearchPro"}},

	{ID: "tinyfish", Name: "TinyFish", Base: "https://api.search.tinyfish.ai", KeysURL: "https://agent.tinyfish.ai/api-keys", Paths: []string{"/"}},
	{ID: "searxng", Name: "SearXNG", KeyOptional: true, Paths: []string{"/search"}},
}

SearchVendors are the search APIs magpie can ask, in the order offered.

View Source
var SendsThroughPlugin func(id string, req *http.Request) func(*http.Response, error)

SendsThroughPlugin, set by the gateway, is told of each request handed to a plugin's account, which goes past the gateway's own transport, as it goes, and what came back for it: the call's headers both ways, for Recent calls (gateway's wire_headers.go).

View Source
var TemplateIDs = map[string]string{TemplateSmart: "smart-split", TemplateThrifty: "cheap-first", TemplateSteady: "never-stuck", TemplatePlan: "plan-first", TemplateFast: "fastest-first", TemplateEven: "spread-evenly"}

TemplateIDs are the ids agents pick a template's group as, before a number when one is in use.

TemplateKinds are the templates, in the order they are offered.

View Source
var TemplateNames = map[string]string{
	TemplateSmart:   "Hard to strong, easy to cheap",
	TemplateThrifty: "Cheap first",
	TemplateSteady:  "Never stuck",
	TemplatePlan:    "Plan first",
	TemplateFast:    "Fastest first",
	TemplateEven:    "Spread evenly",
}

TemplateNames are the templates' names in English, which the GUI says in the user's language.

View Source
var Weekdays = []string{"sun", "mon", "tue", "wed", "thu", "fri", "sat"}

Weekdays are the days a TimeWindow names, as time.Weekday counts them.

Functions

func APIError

func APIError(b []byte, fallback string) string

APIError pulls the human message out of an error body when there is one. A firewall's block page is put in plain words (BlockedHint); Google's "verify your account" refusal also says what to do about it, with the link it gave.

func AccessKeyVendor added in v0.1.1182

func AccessKeyVendor(p Provider) string

AccessKeyVendor is whose account access key p's plan is read with: "volcengine" (Ark's Coding and Agent Plans), "tencent" (Token Plan 企业版), "alibaba" (Token Plan on aliyuncs.com), or "" for none.

func AccountByName added in v0.1.2376

func AccountByName(id string, users []string, ref string) (string, error)

AccountByName is the one of users, accounts of the subscription id, that the user named ref (AccountNameOf, compared without case), "" when none is: an alias picks an account wherever its email does (#4532). It is an error when the name is two accounts', or another account's email or name as magpie lists it, which would then pick one of them by guess.

func AccountCapOf added in v0.1.809

func AccountCapOf(id, user string) int

AccountCapOf is AccountCap of the provider id, 0 when there is none.

func AccountLabelOf added in v0.1.2247

func AccountLabelOf(id, user string) string

AccountLabelOf is the name the account user of id goes by besides user itself: the user's own (AccountNameOf), else its plugin's (PluginUserOf); "" for none. id is a provider's or "plugin:<id>", as logins name a plugin's accounts.

func AccountModelsOf added in v0.1.610

func AccountModelsOf(id, ref string) (string, []string, error)

AccountModelsOf is the models the account or key ref of the provider id alone serves, and the account or key as AccountModels knows it; no models when it serves all the provider's.

func AccountNameOf added in v0.1.1172

func AccountNameOf(id, user string) string

AccountNameOf is the name the user gave the account user of the subscription id, "" when none.

func AccountNames added in v0.1.1076

func AccountNames() map[string]string

AccountNames maps every account and key a gateway key may name (#905), "<provider>/<id>", to how it is shown, "<provider>/<user>", an account by the name the user gave it (AccountShown); what no provider has now maps to itself.

func AccountShownOf added in v0.1.1326

func AccountShownOf(id, user string) string

AccountShownOf is AccountShown for the account user of the provider id.

func AccountWindow

func AccountWindow(account, name string, now time.Time) (start, reset time.Time, known bool)

AccountWindow is the window named name of account ("<provider>/<user>", as a key's accounts are written) as the account's last good reading tells it: when it began and when it resets. known is false when there is no such reading, it has no such window, the window has no reset clock or no length, or its reset has passed with no reading since.

When it isn't known, start is the latest time known to be no later than the window's start: the reset that passed (a window never begins before the last one ended), or zero when nothing is. A limit counting from it counts every call of the window it follows, and maybe more, never less.

It asks no vendor itself: it is on every keyed request's path. When the window isn't known, the accounts are read again in the background, at most once a minute, as the Usage page would (and only when allowances are read without being asked, settings.QuotaReads).

func AccountWindowVia

func AccountWindowVia(f func(account, name string, now time.Time) (start, reset time.Time, known bool)) (restore func())

AccountWindowVia has AccountWindow answer with f until restore is called: a test's accounts and windows, with no reading and no vendor.

func Add added in v0.1.50

func Add(p Provider) (string, error)

Add saves a provider the user just added, beside those already here: an id in use — the preset's, or the one its name slugs to — moves on to the next free one (anthropic-2), and a name in use gets the same number, so a second key of a vendor, or one key for another workspace, is a provider of its own rather than one replacing the first. It answers the id saved.

func AddClaudeSetupToken added in v0.1.2167

func AddClaudeSetupToken(token string) (string, error)

AddClaudeSetupToken adds a Claude account from a setup-token, served by Claude Code with the token in CLAUDE_CODE_OAUTH_TOKEN. Claude Code's own sign-in is left as it is. It answers the account's name; a token already saved answers the account that has it.

func AddCopy added in v0.1.455

func AddCopy(p Provider, from string) (string, error)

AddCopy adds p, a copy the user made of the provider from (#268), beside it: what the form doesn't carry — the keys, the balance token, how requests spread over the keys, where they fall back to — is from's where p leaves it out. The same key on the same host is taken, the copy being asked for (another model list, another endpoint). A signed-in account is never copied: its sign-in is the agent's.

func AddKey added in v0.1.14

func AddKey(id, name, key string, proto Protocol) error

AddKey saves one more key for a provider, on: it takes requests after the ones before it. It becomes the first when the provider has none.

func AddKeyExpiring added in v0.1.3310

func AddKeyExpiring(id, ref string, x Expiring) error

AddKeyExpiring gives the balance typed for the key ref of the provider id a grant x of credit that expires, in the balance's currency, counted from now, beside the grants it has. A key with no balance typed takes none: type the balance that stays first, 0 when all of it expires.

func AddKeys added in v0.1.930

func AddKeys(id string, keys []string, proto Protocol) (added, had int, err error)

AddKeys saves several keys at once, on, after the ones the provider has, with the protocol given: those it has already are passed over. added is how many were new, had how many it had.

func AddPlugin added in v0.1.1232

func AddPlugin(ctx context.Context, spec string) (plugin.Entry, error)

AddPlugin installs the plugin spec, as plugin.Add does, and puts back what was set aside of it when it was last removed.

func AddPlugins added in v0.1.1225

func AddPlugins(ctx context.Context, es []plugin.Entry) (added []string, failed map[string]error)

AddPlugins installs the plugins another computer has (Carried) that aren't here, the way the Plugins page adds one, and hands each a deprecated built-in it serves (HandOver). It never takes a plugin away or changes one already here; a removal is davsync's, which tracks the plugins both sides had at the last sync. It returns the specs added and why the others couldn't be.

func AddSearchKeys added in v0.1.3251

func AddSearchKeys(vendor, text string) (added, had int, err error)

AddSearchKeys puts the keys in text (one, or several separated by commas, spaces or lines) after the vendor's, on; one it has already is counted in had and left as it is.

func AddressOf added in v0.1.1224

func AddressOf(urls ...string) string

AddressOf is the address the URLs are at, the origin of the first one set, for an editor to start from; "" when none is.

func Adopt added in v0.1.642

func Adopt(ctx context.Context, id string) error

Adopt puts the built-in id onto its plugin before any account of it is signed in: the plugin installed, and the subscription signs in through it from now on, as a moved one does. One with accounts is moved instead, and one whose plugin the user removed is the plugin's again.

func AgentContextAgents

func AgentContextAgents() []string

AgentContextAgents are the agents that have a window of their own, sorted.

func AgentContexts

func AgentContexts(agent string) map[string]int

AgentContexts are the windows agent (its list id, Agent.ListsFor) was set.

func AgentEffort added in v0.1.1084

func AgentEffort(agent string) string

AgentEffort is the effort agent's requests are asked for, "" for none.

func AgentNamed

func AgentNamed(agent, name string) (string, bool)

AgentNamed is the catalog id of the one model the agent of that id's list names name (LabelsFor), for an agent that asks for a model by the name its list shows: WorkBuddy shows a model's id after its name ("GLM-5.3:workbuddy/glm-5.3", elis_pina on X), so with the provider left out of the names it is given the name as the id too. false when no model shown, or more than one, is named so.

func AgentPricer added in v0.1.2147

func AgentPricer(st settings.Settings, find func(string) (Group, []Member, bool)) func(Entry) (catalog.Price, bool)

AgentPricer is EntryPricer for the model list magpie writes into an agent's own config (Pi's, omp's, OpenCode's cost): a group whose members cost the same is priced as EntryPricer prices it, and one whose members differ at the member it sends to first — a manual group's pick, else its first member not switched off — since that is the member a request goes to while it answers, and an agent that prices calls by its config (omp's custom provider, taotao7 on Discord) otherwise counts every call to the group at 0. A first member in a fast mode, or with no known price, leaves the group unpriced, as before. The list is read afresh at each Sync, so the price follows the group's members.

A provider's rate window (#2463) is left out: the file holds whatever was written at the last Sync, which nothing rewrites when a window opens or closes, so a window's price taken then would stay on through the hours outside it. magpie's own count (Usage, a key's budget) takes each call's window.

func AgentSuffix

func AgentSuffix(agent string) string

AgentSuffix is the agent's own mode, "" when it follows every agent's.

func AgentUser added in v0.1.683

func AgentUser(agent string) string

AgentUser is who an agent is signed in to itself, as its own files say, for an agent whose vendor a plugin serves too; "" when not known.

func AgyHasEvery

func AgyHasEvery() bool

AgyHasEvery reports whether Antigravity (local agy CLI) is signed in and has every account of the withdrawn Antigravity plugin, by email: then nothing is left to move, and the old plugin only sends requests agy-cli could. An old account with no email can't be matched, so it counts as not there. Account discovery being off changes nothing here: these are the user's own sign-ins.

func AgyMoveUsers

func AgyMoveUsers() []string

AgyMoveUsers are the accounts MoveToAgy would bring in, by email ("" for one that doesn't say), for the Providers page's line.

func AgyPriced

func AgyPriced(model string, pr catalog.Price) catalog.Price

AgyPriced is pr, a price found for model, at what Antigravity counts it at: for a call known to be Antigravity's (the agy CLI's or the app's own session log).

func AgyScoped

func AgyScoped(model string, pr catalog.Price) catalog.Price

AgyScoped is agyScoped for the callers that price by a model's name alone.

func AllKeys

func AllKeys(id string) ([]string, error)

AllKeys is every key a provider holds, on or off, in the order its list shows them, each once: what Copy all keys and `magpie provider keys <id>` give, one a line, for another magpie's Paste several or `magpie provider keys <id> add` to take (@emilochen on X: one provider's keys from this computer to a magpie in the cloud). Only the keys go: their names, protocols and plans are this magpie's. A signed-in account has none to give.

func Allowances added in v0.1.29

func Allowances(agent string) map[string]Allowance

Allowances is each of an agent's accounts' allowance by user, as last known, asked for again in the background when that was over a minute ago. Only the very first ask waits, and not for long. An account missing is one not known yet. A ChatGPT API account is known by the same ChatGPT account's Codex reading (samePlanAllowances).

func AntigravityBase added in v0.1.299

func AntigravityBase(id string) (base, effort string, ok bool)

AntigravityBase is the model magpie offers for one of Antigravity's ids at a level ("gemini-3.7-flash-low" is gemini-3.7-flash at low), and that level; ok is false for an id that is itself a model magpie offers, or that no family has. Picks and agents' models saved before the families were one model still name these ids.

func AntigravityBuiltinForTest

func AntigravityBuiltinForTest() func()

AntigravityBuiltinForTest serves the built-in Antigravity again until the returned func runs. Its route has served nothing since it was retired on 11-15, and its code is still shared with Gemini CLI's: the tests of that route use this until the code is taken out (#6723).

func AntigravitySentID added in v0.1.560

func AntigravitySentID(model, effort string) string

AntigravitySentID is the id a request for model goes out under at that effort on an Antigravity account: the variant of the family the effort picks, at the level of that family nearest the effort asked for; with no effort asked for, the family's own default. One of the family's own variant ids — an id a pick or an agent's model list kept from before the families were one model — goes as it is when no effort is asked for, and at the level the effort picks otherwise, since the effort the client asks for wins, as it does for the family. Any other id goes as it is.

The gateway sends the envelope under this and the ledger judges what the vendor answered against it, so there is one of it rather than one each: a reply naming the id a call went out under is that model answering, and read against the family instead every level of it reads as another model having swapped in, in the routing view and in the ledger alike.

func AntigravityVariants added in v0.1.299

func AntigravityVariants(model string) (map[string]string, bool)

AntigravityVariants are Antigravity's ids a model magpie offers stands for, by level, "" the default; ok is false for a model that stands for none, which goes to Antigravity as it is.

func AnyPriceKey added in v0.1.581

func AnyPriceKey(model string) string

AnyPriceKey is the key a price for a model from any provider is stored at: its id lower-cased, the way a session's bare model is looked up.

func ApplyImage added in v0.1.413

func ApplyImage(pid, model string, images bool, known *bool) (bool, *bool)

ApplyImage is what magpie tells of model: the user's answer when they gave one, else images as the vendor's list has it (known is that list's explicit answer, nil when it didn't say).

func ArrangeSearchAPIs added in v0.1.1258

func ArrangeSearchAPIs(order []string) error

ArrangeSearchAPIs puts the search APIs in the order of the vendors named (#2286), the order they are tried in. One not named keeps its place after them; a name of none set up is refused, so an order sent from a page drawn before one was removed changes nothing.

func ArrangeSearchKeys added in v0.1.3251

func ArrangeSearchKeys(vendor string, refs []string) error

ArrangeSearchKeys puts the vendor's keys in the order of refs; one not named keeps its place after them, and a ref of no key is refused, so an order sent from a page drawn before a key was removed changes nothing.

func AskClaudeUsage added in v0.1.558

func AskClaudeUsage()

AskClaudeUsage is the user asking to see Claude's usage — opening the Usage page, refreshing it, `magpie quota` — so Claude Code's /usage is run at once rather than when the next unasked reading is due (claudeUsageWait); the next SubscriptionUsage waits for it.

func AskEveryClaudeUsage added in v0.1.3064

func AskEveryClaudeUsage()

AskEveryClaudeUsage is the user refreshing every allowance by hand: the tray panel's or the Usage page's Refresh, routing's read of the allowances, the TUI's r (#5380: the panel said "Allowances refreshed" while each saved Claude account kept its old reading, which only its own card's refresh read again). As AskClaudeUsage, and each saved Claude account's /usage is run too, as its card's refresh runs it, the 30-second floor and all. Opening the page, its timer and `magpie quota` ask with AskClaudeUsage, which starts no saved account's Claude Code (savedRefresh).

func AskRemoteHub added in v0.1.3135

func AskRemoteHub(ctx context.Context, id string)

AskRemoteHub asks the Remote magpie id at once whether it serves its router, as its next model list would: its switch just turned on.

func AskUsage added in v0.1.791

func AskUsage()

AskUsage has the next SubscriptionUsage wait for a new reading rather than hand back the last one, as AskClaudeUsage does, without having Claude Code's /usage run: magpie quota wait reads again each time it wakes, and only a wait for Claude needs Claude read.

func Asked added in v0.1.1169

func Asked(ctx context.Context) context.Context

Asked is ctx for a read the user asked for: the Usage page opened or refreshed, a card's refresh, `magpie quota`, `magpie accounts`.

func AsksAccessKey added in v0.1.2953

func AsksAccessKey(p Provider) string

AsksAccessKey is whose account access key p's editor and Usage page ask for: AccessKeyVendor's for a preset's provider, and for a custom one only once it has one saved. A custom provider is the user's own address and key, sent as typed, whatever host it is on: one at tokenhub.tencentmaas.com/plan was asked for a SecretId and SecretKey it never needs (ysm119 on Discord).

func AuthHeaders

func AuthHeaders(p Provider, proto Protocol) map[string]string

AuthHeaders is how a request to the vendor proves who it is. Anthropic's own API wants x-api-key alone, and so does Bedrock's, which turns away a request with both (#176); other compatible vendors take either, so both. Azure OpenAI takes a key in api-key alone: a Bearer there is an Entra ID token, and the key sent as one is turned away.

func AutoGroupID added in v0.1.603

func AutoGroupID(model string) string

AutoGroupID is the id of the group magpie finds for a model, however a vendor spells it: "auto-claude-opus-5-5" for claude-opus-5.5.

func AutoGroupOf added in v0.1.673

func AutoGroupOf(pid, model string) string

AutoGroupOf is the id of the group magpie finds for a provider's model: AutoGroupID of the model the user said it is the same as (settings' ModelSameAs), else of its own id.

func AutoGroupSkip added in v0.1.2246

func AutoGroupSkip() []string

AutoGroupSkip are the providers the user keeps out of the groups magpie finds (SetAutoGroupSkip).

func AutoGroupsOn added in v0.1.603

func AutoGroupsOn() bool

AutoGroupsOn reports whether magpie finds groups on its own: a model more than one provider serves is a group of them (autoGroups). It is on until the user turns it off.

func AutoRefsOn added in v0.1.1294

func AutoRefsOn() bool

AutoRefsOn is autoRefsOn, for the packages that spell a group's id.

func AutoResetWords added in v0.1.1234

func AutoResetWords(user string) string

AutoResetWords says in a few words when user spends one by itself, for the CLI and TUI: "" when it never does.

func AutoResets added in v0.1.514

func AutoResets(agent, user string) bool

AutoResets says whether agent's account user spends its resets by itself at either time; only a Codex account does.

func AutoResetsWeek added in v0.1.1234

func AutoResetsWeek(agent, user string) bool

AutoResetsWeek says whether agent's account user spends a reset by itself once its week is used up and no other account can answer.

func AutoStandIn added in v0.1.603

func AutoStandIn(id string) (string, bool)

AutoStandIn is the model a request for a group magpie found goes to when there is no such group now: while such groups are off (SetAutoGroups), once the providers the user keeps out of them (SetAutoGroupSkip) took it away, or once fewer than two providers serve its model (a provider removed, or its list without the model: canlee886 on X, a Codex thread saved on group/auto-gpt-6-1-sol failed every turn with 404). It is its model, from the first provider that serves it, one not kept out first, as "provider/model": the same model, never another. An agent set to the group, or a session begun on it, keeps working, on one provider. ok is false for any other id, a group there is, a group the user has of that id, one they removed, and a model no provider serves now (GoneGroupModel).

func AutoStandInFor added in v0.1.3374

func AutoStandInFor(agent, id string) (string, bool)

AutoStandInFor is AutoStandIn for a request of agent's: the agent's own subscription first when it serves the model (freefcw on X: off, Codex's gpt-6-astra went to Devin, the first provider in the order), then the first provider as AutoStandIn picks.

func AwaitAllowance added in v0.1.1164

func AwaitAllowance(ctx context.Context, agent, user string) bool

AwaitAllowance has agent's accounts read again unless a reading is out, and waits, till ctx ends, for one that knows user: after a reset is spent, routing then counts the account's windows started again, rather than not known and behind the rest till a later request reads them (#1491). A reading out already, begun before the reset, doesn't count it, so another is asked for; three at most. It says whether user is known now.

func AzureBase added in v0.1.419

func AzureBase(raw string) (string, bool)

AzureBase is the v1 API base of the resource an endpoint names, as it was pasted from the portal or another app — the bare resource (https://r.openai.azure.com), …/openai, …/openai/v1, a classic deployment's URL with its api-version, or only the resource's name — and ok false when it names no Azure resource.

func AzureHost added in v0.1.419

func AzureHost(host string) bool

AzureHost reports whether host is an Azure OpenAI resource's.

func BackAt added in v0.1.791

func BackAt(q SubscriptionQuota, now time.Time) time.Time

BackAt is when a used-up account has room again: when the last of the windows that stop it (usedUp's) starts again, a window's seconds to go counted from now. Zero when one of them doesn't say.

func Balance added in v0.1.37

func Balance(ctx context.Context, p Provider) (amount string, ok bool, err error)

Balance asks the vendor what is left on the provider's key in use. ok is false when there is no way to ask it. A key given limits and no quota of its own has what its fullest window has left: what it can spend now.

func BalanceFound added in v0.1.3030

func BalanceFound(p Provider) (u, field string, looked bool)

BalanceFound is the balance query magpie found for p by itself, with its field ("" when none was found yet), and whether p is one it looks for at all: a relay added by hand with no Balance URL. The editor shows it, so a wrong amount can be put right with a Balance URL of the user's.

func BalanceNumber added in v0.1.540

func BalanceNumber(s string) (float64, bool)

BalanceNumber is the amount a balance as a vendor tells it holds: "$12.34", "¥1,024.50", "CNY 8", "12.3k credits". A share ("45%"), or text with no number, is none.

func BalanceProbeState

func BalanceProbeState(p Provider) (eligible, undetected bool)

BalanceProbeState says whether magpie looks for p's balance query (the off switch aside, so the editor can offer to turn it on again), and whether it looked and found none.

func BalanceQuery added in v0.1.1235

func BalanceQuery(p Provider) (balanceURL, field string)

BalanceQuery is the Balance URL and field the provider's balance is asked at, which differ from the saved ones for an account query left without its token (keyQueryOf).

func BalanceText added in v0.1.1790

func BalanceText(b float64, unit string) string

BalanceText is a wallet's balance as told, the figure in its unit: "6,291 points left" (QuotaWindow.Balance).

func BareDisabled added in v0.1.1219

func BareDisabled(id string) (string, bool)

BareDisabled reports whether a bare id (no provider in it) is the id of a model of a provider that is on and the user disabled, and the pattern that did: the catalog leaves it out, so Resolve doesn't find it.

func BareModelIDs added in v0.1.1226

func BareModelIDs() bool

BareModelIDs says whether /v1/models lists models by their bare ids too.

func BareOnly

func BareOnly() bool

BareOnly says whether /v1/models lists a model by its bare id in place of the provider/model ids it stands for (settings.BareModelIDsOnly; qQianye on X), not beside them. See OnlyBare.

func BillingOK

func BillingOK(s string) bool

BillingOK reports whether s is a billing the user may set: plan, pay as you go, or "" for magpie to read it.

func BoundCallID added in v0.1.887

func BoundCallID(id string) string

BoundCallID is a call's id as the ChatGPT backend takes one: as it is when it fits its 64 characters, else the sha256 of it (trimmed, as calls and their outputs are paired), 64 hex characters. Foreign providers can join two ids into one longer than that (#732, congee949: 86 and 87); the same id gives the same hash on every request, so a call and its output stay paired, and two ids that differ are never cut down alike.

func BuiltinRetired added in v0.1.1282

func BuiltinRetired(id string) bool

BuiltinRetired is whether magpie's built-in id is retired: its plugin serves it, and the built-in serves nothing, moved or not. One whose accounts haven't moved yet (a failed install, an account the plugin turned away) is listed by MoveCandidates with why, until it moves. The built-ins are retired one by one, each with its code (the owner, 10-16: 陆续把内置 Provider下线掉), so this is the set retired so far.

func CCSwitchSkillOrigin added in v0.1.83

func CCSwitchSkillOrigin(dir string) (repo, branch string, ok bool)

CCSwitchSkillOrigin is the GitHub repository (owner/name) and branch CC Switch installed the skill in its folder dir from, as its database records it.

func CCSwitchSkillsDir added in v0.1.83

func CCSwitchSkillsDir() string

CCSwitchSkillsDir is the folder CC Switch keeps the skills it installs in.

func CanFast added in v0.1.577

func CanFast(p Provider, model string) bool

CanFast reports whether model, as p serves it, has a fast mode magpie can ask for: a ChatGPT account's GPT models (Codex's Fast), Cursor's models with a -fast one, an OpenAI key's GPT and o-series models on its Responses API (priority processing), an Anthropic key's Opus models with fast mode, and a plugin's models it says are served at priority. A Claude subscription runs Claude Code itself, and a cloud (Bedrock, Vertex) refuses the field, so neither is. A provider the user added by its address (AddedByAddress) is asked for priority on a GPT model it serves on an OpenAI API, when the user switches it fast themselves (#1615): it is sent service_tier "priority" there, as Codex's own Fast already is (#1234), and one that turns the field away is asked again without it and not sent it again (the gateway's optional fields).

func CanUltra added in v0.1.1270

func CanUltra(p Provider, model string) bool

CanUltra reports whether a fast pick of model on p can be sent as Ultrafast: a ChatGPT model that one of Codex's accounts lists the tier on (Account.Tiers), or a plugin's model, with fast mode, that the plugin says its vendor serves at ultrafast (serviceTiers, #2514), or another magpie's model its list offers ultrafast on (#1234), or a model OpenAI's API serves at ultrafast on that API (OpenAIUltra), or a GPT model on a provider the user added by its address (OwnFast) that OpenAI offers Ultrafast on: its API serves it so (OpenAIUltra), one of Codex's accounts lists the tier on the model, or Codex's own entry for it does, which Codex is offered on that provider as well (codexcat.OwnOffers; KoiLx0 on X, a relay that serves it). Like its Fast, that is asked for, and a provider that turns the field away is asked again without it. A list that doesn't say tiers offers none.

func CancelQianwenSignIn

func CancelQianwenSignIn(id string)

CancelQianwenSignIn stops waiting on the provider's sign-in.

func CancelSignIn added in v0.1.14

func CancelSignIn(id string)

CancelSignIn stops waiting for the browser.

func CanonicalRef added in v0.1.1294

func CanonicalRef(ref string) string

CanonicalRef is ref as magpie keeps it: a found group's auto/<model> as group/auto-<slug>, an effort after it (":high") and Claude Code's [1m] mark kept; any other ref as it is. The gateway takes a request's model back to it before key limits, routing and the usage log see it, so the two ids of one group are one.

func Carried added in v0.1.1225

func Carried(keys bool) []plugin.Entry

Carried is the plugins a backup or a sync carries: those added from npm or a git repository, on or off as the user left them, with their options: without keys, those whose names look like a key are left out, as a provider's secret headers are. A plugin added from a file or folder is this computer's alone, and a plugin's sign-ins (plugin-auth.json) stay here, as a subscription's do.

func CertPath

func CertPath(p string) (string, error)

CertPath is a client certificate's, key's or CA's file as ClientCert keeps it: ~ taken as home, and a whole path, since the gateway reads it from wherever it was started.

func ChangeModelEfforts

func ChangeModelEfforts(ref string, efforts []string) (bool, error)

ChangeModelEfforts is SetModelEfforts, saying whether anything changed: levels already kept, or every level a model offers already, change nothing, which the caller says rather than a tick over nothing saved (@czhhcz on X).

func ChangeModelSpec

func ChangeModelSpec(ref string, c SpecChange) (bool, error)

ChangeModelSpec is SetModelSpec, saying whether anything changed: a spec the model goes by already (every reasoning level it has, a window it was given) saves nothing, which the caller says rather than "saved" (@czhhcz on X).

func Changed added in v0.1.705

func Changed()

Changed drops what is held: a provider, an account, a plugin or a setting was written.

func ChatGPTReviewFree added in v0.1.2020

func ChatGPTReviewFree(model, plan string) bool

ChatGPTReviewFree says whether a call on model by a ChatGPT account on plan is free, counted in none of its usage windows and charged nothing: Codex's reviewer model, codex-auto-review, since OpenAI made Auto-review free for every user signed in through a ChatGPT account (2026-10-06, #1593, hywang1230; thsottiaux's "Day 2.1"), but not on a Free plan, where cybercaius on Discord measured it spending the allowance. A review run on another model (one that follows the session, or a stand-in magpie routes it to), or through an API key, is a call like any other.

func CheckQueue added in v0.1.1009

func CheckQueue(limit, wait int) error

CheckQueue says what is wrong with a queue's bound or wait, nil when nothing is.

func CheckRPM added in v0.1.1119

func CheckRPM(n int) error

CheckRPM says what is wrong with a limit on requests a minute, nil when nothing is.

func CheckRateWindows added in v0.1.2200

func CheckRateWindows(ws []RateWindow) string

CheckRateWindows says what is wrong with a set of a provider's rate windows, "" when nothing. A window's rate stands to the same rule as a price rate but is never 0: 0 would read as the price as listed, which is what being outside every window already means.

func CheckinDay added in v0.1.778

func CheckinDay(t time.Time) string

CheckinDay is the day (Beijing, "2006-01-02") WorkBuddy's check-in counts t in: a WorkBuddyCheckin of that Day is today's.

func ClaudeBare

func ClaudeBare(ref string) string

ClaudeBare is ref (a served "provider/model", with a [1m] mark or not) as Anthropic names it, without the provider, when ref is a Claude model on Claude Code's own subscription in magpie and the bare id goes to that same model (OwnRoute). Claude Desktop's Code tab on the user's own subscription reads the model variables of settings.json and sends them to Anthropic, which turns "anth/claude-haiku-5-5[1m]" away ("There's an issue with the selected model", iryan_sun on X); through magpie the bare id arrives at the same subscription. Haiku has no 1M window to mark, so its mark is taken off. Anything else is as it is: another vendor's model or a relay's has no id Anthropic knows, and one with an effort fixed on it names that effort only through its ref.

func ClaudeCodeModels added in v0.1.1681

func ClaudeCodeModels() []catalog.Model

ClaudeCodeModels is the list Claude Code, as it is signed in on this computer, offers: models.dev's anthropic list without what the account isn't entitled to, and the models Anthropic told it the account has beyond them (Claude Mythos 5.1).

func ClaudeCodeMovedOff added in v0.1.648

func ClaudeCodeMovedOff(user string) bool

ClaudeCodeMovedOff says Claude Code itself is signed in to another account than user now: what a Claude Code run in its own home says of the account it is on is no longer user's. false when it can't be told. Named from its profile, the account is told by its whole name: a Team seat and a personal plan of one email ("me@x.com · Acme", "me@x.com") are two accounts, and one's usage isn't the other's (netfishx on X).

func ClaudeDashed added in v0.1.1163

func ClaudeDashed(id string) string

ClaudeDashed is id with each dot of a Claude model's version a dash: relay/claude-opus-4.6-us[1m] is relay/claude-opus-4-6-us[1m]. Any other id is as it is.

func ClaudeDirToken added in v0.1.2167

func ClaudeDirToken(dir string) string

ClaudeDirToken is the setup-token of the saved Claude account whose config directory is dir (claudeAccountDir), "" when it has a sign-in of its own or is no saved account's. A run there is given it, and no other.

func ClaudeExtraLine

func ClaudeExtraLine(spent, limit float64, currency string) string

ClaudeExtraLine is the line for spent and limit, in cents of currency.

func ClaudeExtraUsage

func ClaudeExtraUsage() bool

ClaudeExtraUsage says whether magpie sends a Claude account requests once its plan is used up, for Anthropic to bill as extra usage: true unless the user turned it off.

func ClaudeFast added in v0.1.577

func ClaudeFast(model string) bool

ClaudeFast reports whether a Claude model has fast mode.

func ClaudeGroup added in v0.1.1219

func ClaudeGroup(id string) bool

ClaudeGroup says a model id (as CompactSet takes it) is a routing group whose every member is one of Anthropic's Claude models, by the name it is listed under or the one the vendor is asked for. Claude Code runs such a group as it runs a Claude model, to its own window, so it isn't handed magpie's default compaction window (#1741: a group of Claude [1m] models was told 272000, its id's last part not starting with "claude"). A group with any other member, or none, isn't.

func ClaudeInWSL added in v0.1.834

func ClaudeInWSL() string

ClaudeInWSL is the WSL distro the gateway runs Claude Code in, when there is none on Windows itself and one was found there; "" otherwise. It never waits on WSL: until a look has been made, one starts and "" comes back.

func ClaudeLoginVersion added in v0.1.788

func ClaudeLoginVersion(user string) string

ClaudeLoginVersion is the credential the saved Claude account user has now, which a run started on it goes by (NoteClaudeSignInFailure).

func ClaudeModel added in v0.1.1309

func ClaudeModel(model string) bool

ClaudeModel is claudeModel for another package: whether model, after any vendor prefix, is one of Anthropic's Claude models by its name.

func ClaudeOwnName added in v0.1.1552

func ClaudeOwnName() (string, bool)

ClaudeOwnName is the name Claude Code's own sign-in is served by now, and false while it has none (Unnamed) or Claude Code is signed out.

func ClaudeProxies

func ClaudeProxies() []string

ClaudeProxies are the distinct proxy choices the Claude subscription's accounts send their requests through (ProxyOfLogin): what internal/egress looks the way out up through. No account, none: a user without one is never looked up for.

func ClaudeRead added in v0.1.1163

func ClaudeRead(ref string) string

ClaudeRead is a model read back from Claude Code's settings as magpie serves it: a dashed spelling ClaudeSpelled wrote taken back to the served id, anything else as it is. A model of a provider switched off since is taken back too, so magpie still knows it for its own and moves the agent off it (Reseat).

func ClaudeSignInRequired added in v0.1.788

func ClaudeSignInRequired(message string) bool

ClaudeSignInRequired says message is Claude Code's, or magpie's, word that a Claude sign-in is gone and has to be made again: not a failure of the moment, as a network error or another Claude Code holding the refresh is ("Failed to refresh OAuth token: another Claude Code process is refreshing it").

func ClaudeSpelled added in v0.1.1163

func ClaudeSpelled(ref string) string

ClaudeSpelled is ref (a served id, with an effort and [1m] mark or not) as Claude Code is given it: dashed (ClaudeDashed) when that spelling comes back to this id (ClaudeUndashed), else as it is.

func ClaudeTokenUser

func ClaudeTokenUser() string

ClaudeTokenUser is the saved setup-token account Claude Code itself uses now (magpie's token in its settings.json), "" for none.

func ClaudeTrustFolder added in v0.1.2691

func ClaudeTrustFolder(dir string, keys ...string) error

ClaudeTrustFolder records, in saved account config directory dir, that Claude Code may work in a folder (magpie's own, or a caller's), which keys names as Claude Code keys its projects (2.1.316: the folder's path, on Windows with forward slashes, "C:/Users/<me>/AppData/Local/Temp/magpie-claude-work"), as Claude Code itself records it once the trust question is answered yes. On mydosu's Windows (#4830) a saved account's directory had no such entry, and every /usage read of that account waited out its time on the question. Only a directory of magpie's saved accounts is written, never the user's own ~/.claude.json; every other key is kept, and a file that can't be read or parsed, which Claude Code may be writing, is left as it is.

func ClaudeTrustedProjects added in v0.1.3072

func ClaudeTrustedProjects() (map[string]bool, error)

ClaudeTrustedProjects are the projects keys of the folders the user told Claude Code to trust (hasTrustDialogAccepted), in the state file of the account it is signed in to (claudeProfilePath, so CLAUDE_CONFIG_DIR's when set), read again only when the file changes. Only read, never written: the answers are the user's. A file that isn't there trusts nothing; one that can't be read or parsed, which Claude Code may be writing, or account discovery turned off, is an error: unknown. What it returns is shared and must not be changed.

func ClaudeUnbare

func ClaudeUnbare(v string) string

ClaudeUnbare is ClaudeBare taken back: a Claude model of Anthropic's by its bare id, which magpie sends to Claude Code's own subscription, is that subscription's ref. Any other value is as it is.

func ClaudeUndashed added in v0.1.1163

func ClaudeUndashed(ref string) (string, bool)

ClaudeUndashed is the served id (a provider's model or a routing group) whose dashed spelling (ClaudeDashed) ref is, its effort and [1m] mark kept, when ref is no served id as it is and exactly one served id is so spelled. An id served as it is spelled always wins.

func ClaudeWarmed added in v0.1.223

func ClaudeWarmed() map[string]time.Time

ClaudeWarmed is when magpie last started a window of each Claude account, by user as kept (lower-cased).

func CleanAutoInclude added in v0.1.1234

func CleanAutoInclude(in []string) ([]string, error)

CleanAutoInclude are AutoInclude's patterns as they are kept: trimmed, each once, every one one magpie can read. A pattern is a glob with * in it (any run of characters, in any case: "gpt-*", "*claude*") or a regular expression after "re:" that matches the whole id.

func CleanLevels added in v0.1.477

func CleanLevels(in []string) ([]string, error)

CleanLevels are the reasoning levels a group names for itself (Group.Levels) as they are kept: lowercase, each once, lowest first. Only the levels magpie knows are taken.

func CleanModelTier

func CleanModelTier(v string) (string, error)

CleanModelTier reads the words people use for a tier: "" (also off, usual, standard) for none, "priority" (fast), "ultrafast" (ultra, ultra-fast).

func CleanNote

func CleanNote(s string) string

CleanNote is a group's note as stored: one line, its spaces and line breaks run together, at most NoteLongest characters.

func CleanPatterns added in v0.1.826

func CleanPatterns(in []string) ([]string, error)

CleanPatterns are a group's patterns as they are kept: trimmed, each once, every one one magpie can read.

func ClearKeyExpiring added in v0.1.3310

func ClearKeyExpiring(id, ref string) error

ClearKeyExpiring takes every grant of credit that expires off the balance typed for the key ref of the provider id; the rest stays.

func ClineClient added in v0.1.630

func ClineClient(h http.Header)

ClineClient makes a request to the Cline API carry the desktop app's headers.

func Closest added in v0.1.1148

func Closest(asked string, n int) []string

Closest lists up to n catalog ids nearest to asked, nearest first: a model whose display name holds asked's words before one whose id does, and the provider's id or name counting only alongside. Nothing when no model's name or id shares a word with it.

func CloudflareClef added in v0.1.859

func CloudflareClef(model string) bool

CloudflareClef reports whether model is one of Cloudflare's Clef models.

func CodexAPIKeySignedIn added in v0.1.1083

func CodexAPIKeySignedIn() bool

CodexAPIKeySignedIn says Codex itself is signed in with an OpenAI API key rather than a ChatGPT account (auth.json's auth_mode): its sign-in is a key's, and spends no account a gateway key's list governs.

func CodexAccountModel added in v0.1.1195

func CodexAccountModel(id string) bool

CodexAccountModel says id names a model of a ChatGPT account's, served now or not: codex/<model>, or one of a provider that is a ChatGPT account.

func CodexAppBack added in v0.1.2993

func CodexAppBack() bool

CodexAppBack is whether the Codex app still runs on the app-server it started while magpie was Codex's provider for its used-up account, now that magpie gave Codex back its ChatGPT account and left the app running (Restart the Codex app to follow off, #4550). That app-server read account/read as it started, when Codex's provider took no ChatGPT account, so the app shows no account, no usage meter and none of its ChatGPT side until it restarts: the Agents row says so and offers the restart (練習^1.0beta by mail, 11-04: the panels loaded only after `magpie codex default` and a restart).

func CodexAppClosed

func CodexAppClosed()

CodexAppClosed gives all of Codex's accounts one list of projects in the Codex app (shareCodexProjects); the caller knows the app is closed: the agent package between its quit and its open.

func CodexAppProjectsShort

func CodexAppProjectsShort() bool

CodexAppProjectsShort says the open Codex app shows fewer projects than its accounts have, until it is quit and opened again.

func CodexAppSnagged added in v0.1.3045

func CodexAppSnagged() bool

CodexAppSnagged is whether the Codex app showed the page it shows when it can't go on after magpie restarted its app-server, and magpie couldn't reopen it: the user quits it and opens it again.

func CodexAppStale added in v0.1.1155

func CodexAppStale() string

CodexAppStale answers the account the Codex desktop app is still signed in to when Codex has been switched to another since the app opened, "" when it isn't open or is on the account Codex is. The app shows that account's limits, and once they are spent won't send in any thread, until it is quit and opened again.

func CodexAppStuck added in v0.1.1704

func CodexAppStuck() bool

CodexAppStuck is whether a Codex app is left on the provider it started with, which magpie couldn't restart: the user quits and opens it.

func CodexAutoReset added in v0.1.507

func CodexAutoReset(user string) bool

CodexAutoReset says whether the Codex account user spends a reset by itself at either time.

func CodexAutoResetWhen added in v0.1.1234

func CodexAutoResetWhen(user string) (week, expiring bool)

CodexAutoResetWhen says at which of those times the Codex account user spends a reset by itself: both unless the user kept it to one.

func CodexCatalog added in v0.1.1118

func CodexCatalog(shown []Entry) []catalog.Model

CodexCatalog is shown as a Codex that names magpie its model_provider is handed it from GET /v1/codex/models (#1281): every model, a ChatGPT account's own among them, since that Codex reaches them through magpie's /v1 by magpie's id, not through the ChatGPT backend's list.

func CodexClient

func CodexClient() string

CodexClient is the Codex client magpie presents to the ChatGPT backend (settings.CodexClient): "" for Codex CLI, "desktop" for the Codex app. A value this magpie doesn't know (a newer one's, a file edited by hand) is read as "" and changes nothing.

func CodexClientVersion

func CodexClientVersion() string

CodexClientVersion is the Codex client version the backend's model list is asked for now (codexVersion): a list asked for an older one may lack a model the backend lists only to a newer client.

func CodexCompactModel

func CodexCompactModel() string

CodexCompactModel is the model Codex's compactions made by magpie are put on, "" for the session's own. A provider renamed since it was set is named by its new id (RenamedRef).

func CodexCompressed added in v0.1.1206

func CodexCompressed(req *http.Request, body []byte) int

CodexCompressed sends req's body, body, zstd-compressed as Codex's own client sends it, when req is a turn to the ChatGPT backend (CodexBase/responses), and as it is otherwise. It is called once the body is final and signed, and returns the bytes that go on the wire. The body is still the plain body everywhere magpie keeps or shows it.

func CodexCredits added in v0.1.1080

func CodexCredits(user string) bool

CodexCredits says whether the Codex account user spends its credits once a usage window is used up: true unless the user turned it off.

func CodexCreditsFirst added in v0.1.2611

func CodexCreditsFirst(user string) bool

CodexCreditsFirst says whether the Codex account user, which spends its credits, spends them before routing moves on: a window used up sends neither requests nor Codex's sign-in to another account while it goes on on its credits (gateway's creditsFirst, NextLogin), where by default an account all but used up waits behind every one with room (Smart) and Codex is signed in to another (jojonas_xyz on X). Off unless the user set it.

func CodexCreditsLast added in v0.1.2511

func CodexCreditsLast(user string) bool

CodexCreditsLast says whether the Codex account user, which spends its credits, spends them only after everything else: once a usage window is used up, routing tries it after every account, key and fallback not on its credits (gateway's creditsLast) rather than in its place. Off unless the user set it, so a setting saved before it keeps its order.

func CodexCreditsMode added in v0.1.2511

func CodexCreditsMode(user string) string

CodexCreditsMode is how user spends its credits: CreditsOn, CreditsFirst, CreditsLast or CreditsOff.

func CodexDaemonStale added in v0.1.368

func CodexDaemonStale() string

CodexDaemonStale answers the account Codex's app-server is still signed in to when Codex has been switched to another since it started, "" when it isn't running or is on the account Codex is.

func CodexEfforts added in v0.1.2218

func CodexEfforts(e Entry) []string

CodexEfforts are the levels Codex's picker offers for e: its own, or, for a model nothing magpie reads says anything about — a custom provider's model-code, a relay's alias — low, medium and high. Codex sends such a model an effort whatever its entry lists (medium, or the one config.toml starts sessions at), and the gateway passes an effort on as asked where the model's levels aren't known (fitEffort), so with no levels in its entry the effort was sent and couldn't be changed (ccdcn on X: no effort choice for a custom provider's models). A model known to have no levels keeps none: one its vendor's catalog or models.dev lists without them, one the user said takes no reasoning ask, and a routing group, whose levels are its members'.

func CodexGoesOnCredits

func CodexGoesOnCredits(has, unlimited bool, balance string) bool

CodexGoesOnCredits is whether a ChatGPT account goes on past its allowance on credits, told as Codex reads them (/wham/usage's credits, the x-codex-credits-* headers, a codex.rate_limits event's credits): unlimited, or holding them (has_credits) — a balance said and spent (0 or less) is none left, whatever has_credits says. A balance not said, or not a number, is held.

func CodexHome added in v0.1.1151

func CodexHome() string

CodexHome is the Codex home magpie wires and signs Codex in through.

func CodexKeychainForTest added in v0.1.1258

func CodexKeychainForTest(find func(service, account string) ([]byte, error)) (restore func())

CodexKeychainForTest has Codex's keychain item read through find (no item: fs.ErrNotExist) on every system, until restore.

func CodexListRevoked added in v0.1.2096

func CodexListRevoked(err error) bool

CodexListRevoked says err, from CodexLiveList, is the backend calling Codex's sign-in revoked (SignInRevoked), not a refusal a refresh mends, a 5xx or a network error.

func CodexListTag added in v0.1.460

func CodexListTag() string

CodexListTag names the list Codex is handed, for its ETag: magpie's models, the account's own taken out of it, the order they are in, the windows set on them, the auto-review model, and whether its OpenAI models say multi-agent V1 (settings.CodexAgentsV1), so any of them changing has Codex ask for the list again.

func CodexListed added in v0.1.54

func CodexListed() []catalog.Model

CodexListed is the catalog as a Codex signed in to ChatGPT is handed it, after the backend's own models: all but a ChatGPT account's in magpie, which the backend lists already. A group answers for its first member but is not that provider's.

func CodexListedBeside added in v0.1.2958

func CodexListedBeside(backend map[string]bool) []catalog.Model

CodexListedBeside is CodexListed for a Codex whose sign-in's list, from the backend, has the slugs in backend: with a ChatGPT account's own models that list lacks among them, by magpie's id (codex/<slug>), which reaches them through magpie on the account that has them. Codex signed in to a Free account, a Team one on in magpie beside it, was handed the Free plan's list alone, and the Team plan's models were in every agent but Codex (bigfisheatsmall on X), though the codex provider lists them (codexPoolModels) and routing sends them to that account.

func CodexLiveList added in v0.1.1728

func CodexLiveList(ctx context.Context) ([]byte, error)

CodexLiveList is the ChatGPT backend's model list for the account Codex is signed in to now, as the backend sends it: its entries, their base_instructions among them, untouched. magpie writes it for the Codex app beside the sign-in (agent.CodexDesktopList), whose picker shows only the models a flag of OpenAI's names unless Codex reads its list from a file. An error when Codex is not signed in to ChatGPT, the backend doesn't answer 200, or its answer lists no model: never an empty list. CodexListRevoked tells one that is the backend calling the sign-in revoked.

func CodexMayBeUsedUp added in v0.1.1381

func CodexMayBeUsedUp(user string)

CodexMayBeUsedUp is a reply's word that user's ChatGPT account may be out (usage_limit_reached, or a window heard at 100%): for the account Codex is signed in to, its allowance is read again at once, at most every codexRecheckEvery, and a change told as the five-minute look tells it (noteCodexUsedUp).

func CodexNativeHidden added in v0.1.460

func CodexNativeHidden() map[string]bool

CodexNativeHidden is the ChatGPT account's own model slugs the user took out of Codex's list (HiddenModels), or didn't pick for it when it is shown only the models picked (PickedModels): the backend lists them, and the gateway drops them from its /models answer as it does the ones not picked.

func CodexNativePicked added in v0.1.292

func CodexNativePicked() (map[string]bool, bool)

CodexNativePicked is the set of the ChatGPT account's own model slugs the user kept, and whether they narrowed that list at all. The backend lists every model the account can reach; when the user has picked among them on the codex provider, the gateway keeps its /models answer to those (see codexModels). Not narrowed — the account's list is left whole. The picks are Picks: a model the vendor listed since they were saved is kept, as magpie's catalog serves it, or the account's own list froze at what was listed when the user picked (#5062).

A provider switched off picks nothing, as it serves no agent anything (Provider.Off): its picks are kept for when it is switched on again and are not a narrowing now. Usage only narrows the visible native list to none, as it does the general catalog; codexModels keeps hidden jobs. Best in family narrows it to the newest of each family the account lists.

func CodexNativeWindow added in v0.1.757

func CodexNativeWindow(restore bool) func(slug string) (n, most int, ok bool)

CodexNativeWindow is the context window Codex is handed for one of the ChatGPT account's own models, by the backend's slug, and the most it may be raised to (0: as the entry says): the window the user set on the codex provider (Provider.ContextOf), as /v1/models says it (#674). ok is false for a model the user set none for, whose entry keeps the backend's window — unless restore, for an entry not fresh from the backend: Codex's models_cache.json keeps what magpie last handed it, a window since taken away among it, so such an entry takes the account's own list's again.

func CodexOrder added in v0.1.952

func CodexOrder() (map[string]int, bool)

CodexOrder is where each model of Codex's list goes when the user put them in an order of their own on the Agents page (#855), by the slug Codex knows it by — a ChatGPT account's own by its bare one, as the backend lists it, and by magpie's id, as magpie lists one the backend's list lacks — and whether they did. A model it doesn't name keeps its place after them.

func CodexOutUntil added in v0.1.1704

func CodexOutUntil() time.Time

CodexOutUntil is when the ChatGPT account Codex is signed in to has room again, as last read: the latest reset of the windows used up. Zero when it isn't out or the reading doesn't say.

func CodexOwn added in v0.1.952

func CodexOwn(e Entry) bool

CodexOwn reports whether e is one of a ChatGPT account's own models, which the ChatGPT backend lists to Codex by its bare slug (e.Model).

func CodexOwnLeftOut

func CodexOwnLeftOut(keep string) func(slug string) bool

CodexOwnLeftOut is the rule for Show Codex's own models turned off (OwnModelsHidden, iiiiiimone on X): it says of a slug in the sign-in's list whether Codex's list leaves it out, so the picker offers magpie's models alone. A model magpie serves on a ChatGPT account of the user's stays, as the Agents page's picker keeps it (Served), and so does keep, the one Codex is set to, which Codex would otherwise run on fallback metadata. nil while the switch is on. Hidden jobs (codex-auto-review) are the caller's to leave.

func CodexOwnListTag added in v0.1.1138

func CodexOwnListTag() string

CodexOwnListTag names the list a Codex that reaches magpie for account failover alone is handed, its own models without magpie's (#1385). Neither it nor CodexListTag's is a part of the other, so Codex asks again when it moves from one list to the other; a V1 list's mark stays in front.

func CodexPIDs added in v0.1.2030

func CodexPIDs(ctx context.Context) []int

CodexPIDs lists the Codex processes running now that may hold a thread sending to magpie's gateway: the Codex app's app-server, the managed daemon, the CLI's sessions, an editor's codex. A relay magpie leaves at quit for them ends once they all have (codexrelay).

func CodexRestartsApp

func CodexRestartsApp() bool

CodexRestartsApp is codexRestartsApp, for the agent package: a change of Codex's route magpie makes by itself restarts the Codex app's app-server (moving the chats it has open first, CodexBeforeAppEnd) only when it says so.

func CodexSeals

func CodexSeals(m *catalog.Model, e Entry, members func(id string) []Member)

CodexSeals sets m.Seals: e's provider, or a member of its group, is one of no sign-in on the Responses API, which may seal a V2 lead's subagent tasks as the ChatGPT backend does (#1109). A ChatGPT account's model says so already (codex/, a group's Fast); another account's (Copilot) seals none.

func CodexServesWhileOut added in v0.1.2820

func CodexServesWhileOut(model string) bool

CodexServesWhileOut says magpie has something to serve Codex's own model on while the ChatGPT account Codex is signed in to is out: the Codex subscription's fallbacks, set in magpie, or another of its ChatGPT accounts not known out or lapsed. With neither, every turn magpie took over would be refused on that same account, so taking over would only hide the account and its reset from the app and restart the app's app-server twice (xiaoq6285 on Discord, one Plus account).

func CodexServiceTier

func CodexServiceTier() string

CodexServiceTier is the service tier set for every request Codex sends (settings.CodexServiceTier): "" as Codex asks it, settings.CodexTierStandard for none, "priority" or "ultrafast". A value this magpie doesn't know (a newer one's, a file edited by hand) is read as "" and changes nothing.

func CodexSignIn added in v0.1.1258

func CodexSignIn(dir string) (b []byte, ok bool)

CodexSignIn is the sign-in Codex goes by under its home dir, from wherever its config.toml has it kept (readCodexLogin); ok is false for none, or one magpie couldn't read. Agents' wiring reads it here.

func CodexSignInAsKept added in v0.1.2082

func CodexSignInAsKept() (tok, accountID string, err error)

CodexSignInAsKept is the access token and account id of the ChatGPT sign-in Codex keeps, as it is (codexTokenAsKept): an expired one is an error, left to Codex to renew.

func CodexSignInGone added in v0.1.2096

func CodexSignInGone(dir string, auth []byte) (gone, known bool)

CodexSignInGone says whether auth, the sign-in read from the Codex home dir, is one OpenAI refused to refresh for good (noteCodexSignInGone). known false: the record couldn't be read, which says nothing either way.

func CodexSignInKept

func CodexSignInKept() bool

CodexSignInKept reports whether the account Codex is signed in to is the one the user keeps it on (keepsLogin): the account KeepLoginAs names, or, kept on the first with none named, the one it is on, which magpie then never moves it off. The Codex app shows that account as the user's own, so on one of Codex's own models magpie doesn't become Codex's provider while it is held (the agent package's outOn): its takeover answers account/read with no account, and the app showed "magpie" for the account the user picked (davezfr on X, account 1 out of its allowance and its credits). On a model of magpie's it does, kept or not, or the app greys Send for it till the reset. false while it can't be told.

func CodexSignInKnown added in v0.1.1434

func CodexSignInKnown(dir string) (b []byte, ok, known bool)

CodexSignInKnown is CodexSignIn with whether the read says anything at all. A sign-in that isn't there (no auth.json: codex logout; no keychain item) or is kept where magpie doesn't read is known, ok false. One that couldn't be read, or doesn't parse, is not: Codex rewrites auth.json in place when it refreshes its tokens (codex-rs FileAuthStorage::save opens it with truncate), so a read in that moment finds it empty or cut off, and a keychain read can fail for a moment too. known false says nothing of the sign-in either way.

func CodexSignInListed

func CodexSignInListed() (ids []string, fetched time.Time, ok bool)

CodexSignInListed is the models the account Codex is signed in to listed when magpie last asked for its list (KeepAccountsListed), and when that was; ok is false while none is kept. The Codex app's list beside the sign-in (gateway.CodexDesktopCatalog) is the same backend's list for the same account, asked apart: one older than this that lacks a model this has is asked for again, or the app's picker went without a model magpie's own lists had (ANAGABRIELRLki on X: GPT-6.2 Astra).

func CodexSignInPlan added in v0.1.1588

func CodexSignInPlan() string

CodexSignInPlan is the plan of the ChatGPT account this machine's Codex is signed in to, as its ID token's chatgpt_plan_type names it ("free", "plus", "pro" …), "" when Codex isn't signed in or it can't be read. Codex's auto-review follows the session on a Free plan by default (codexcat.AutoReviewModel).

func CodexSignInWho added in v0.1.2712

func CodexSignInWho() string

CodexSignInWho names the ChatGPT account this machine's Codex is signed in to now and its plan, "" when it isn't: what the backend's model list (CodexLiveList) is the list of. A Pro account lists models a Plus one doesn't (chzbz on X: GPT-6.1 Sol).

func CodexSignedIn added in v0.1.507

func CodexSignedIn() (string, bool)

CodexSignedIn is the ChatGPT account Codex is signed in to now.

func CodexSignedInAccount added in v0.1.1258

func CodexSignedInAccount() string

CodexSignedInAccount is the ChatGPT account id (chatgpt-account-id) Codex's auth.json is signed in to now; "" when it is signed in to none, on an API key, or can't be read.

func CodexStatuslineCard

func CodexStatuslineCard(q Quota, now time.Time) string

CodexStatuslineCard is one account as Codex's footer shows it: its windows as StatuslineCard has them, or a key's balance.

func CodexSubagentModel added in v0.1.1142

func CodexSubagentModel() string

CodexSubagentModel is the model Codex's subagents are put on, "" for the one the lead asks for, CodexSubagentLead for the lead's own.

func CodexSubagentUnserved added in v0.1.1142

func CodexSubagentUnserved(id string) string

CodexSubagentUnserved says why Codex's subagents can't be put on id now, "" when magpie serves it.

func CodexSuggestionsModel

func CodexSuggestionsModel() string

CodexSuggestionsModel is the model the Codex app's prompt suggestions (its background ambient_suggestions turn and their safety check) are put on, "" for the model Codex sends them on. A provider renamed since it was set is named by its new id (RenamedRef).

func CodexTiers added in v0.1.1172

func CodexTiers(m *catalog.Model, e Entry, members func(id string) []Member)

CodexTiers sets on m what Codex is offered on e's service tiers (codexcat.Entries turns them into the entry's service_tiers): one source for every list Codex is handed, the gateway's and the models.json file magpie writes for a Codex CLI that names magpie its provider (#1530), and the /v1/models another magpie that has this one as its provider reads them from (RemoteTiers, #1234).

func CodexTiersWith

func CodexTiersWith(m *catalog.Model, e Entry, members func(id string) []Member, ultra func() map[string]bool)

CodexTiersWith is CodexTiers with UltraModels read through ultra, once for a whole list.

func CodexTokenURLForTest added in v0.1.1152

func CodexTokenURLForTest(u string) func()

CodexTokenURLForTest points ChatGPT's token endpoint at a test server, for the CLI's tests; the func it returns puts it back.

func CodexToolName added in v0.1.2694

func CodexToolName(name string) string

CodexToolName is name as the ChatGPT backend takes it: as it is when it is valid, else each character the backend refuses as "_", cut to 55, and a hash of the whole after it (as FlatName cuts a long name), so a name is made the same on every request and two names that differ never come out alike. An agent's declared tool so renamed is called back by its own name (CodexToolNamesBack).

func CodexToolNames added in v0.1.2694

func CodexToolNames(body []byte) []byte

CodexToolNames is body, a Responses request for the ChatGPT backend, with every tool name in it as CodexToolName makes it, or body byte for byte when each one is valid already.

func CodexToolNamesBack added in v0.1.2694

func CodexToolNamesBack(declared []string) map[string]string

CodexToolNamesBack maps each name of declared that CodexToolName changes back to the name the agent declared; nil when none changes.

func CodexTurnURL added in v0.1.1349

func CodexTurnURL(u *url.URL) bool

CodexTurnURL says whether u is CodexBase's /responses, where Codex sends a turn.

func CodexUsedUp added in v0.1.44

func CodexUsedUp(ctx context.Context) bool

CodexUsedUp reports whether the ChatGPT account Codex is signed in to is out for the Codex app, which then sends nothing for it (codexHeld): out of its allowance with no credits to go on with. A window at 100% with credits left isn't (the Codex app keeps sending, and the backend answers). False when that isn't known.

func CodexUsedUpKnown added in v0.1.1225

func CodexUsedUpKnown() bool

CodexUsedUpKnown is CodexUsedUp over what was read already, asking no one and waiting for no one. False when nothing was read yet, which is CodexUsedUp's own answer for an account it can't tell about.

For a caller on a path that must not do I/O: agent.SyncCatalog runs inside a write's own request (a routing group's Save), and the reading there is one the vendor is asked for over the network — a save waited 1.1s of the miss of its minute's cache. Nothing is lost by not asking: KeepOnAnAccountWithRoom reads it every loginSwitchEvery and noteCodexUsedUp tells the catalog when the answer changes, which is what the sync is reacting to, and the Usage page and routing read it as the user looks at them.

func CodexVersionBehind

func CodexVersionBehind(asked, now string) bool

CodexVersionBehind says a list asked for Codex version asked is behind now, the version magpie asks as (CodexClientVersion), or its version isn't known (codexListBehind).

func CodexWarmAtOf added in v0.1.1080

func CodexWarmAtOf(user string) (string, bool)

CodexWarmAtOf is user's own time of day to start its 5-hour window at, "off" for none; false when it follows settings' CodexWarmAts.

func CodexWarmed added in v0.1.182

func CodexWarmed() map[string]time.Time

CodexWarmed is when magpie last started a window of each ChatGPT account, by user as kept (lower-cased).

func CodexWindow added in v0.1.1280

func CodexWindow(user, slug string) int

CodexWindow is the context window Codex works in for one of its own models, by the backend's slug, for a request to the ChatGPT backend or OpenAI's API that Codex sent through magpie: the window the user set on the codex provider, else the one the account's own list gives (user, "" for any), else magpie's Codex subscription's, else Codex CLI's models_cache.json's; 0 when none says. models.dev's input limit for the same id is OpenAI's API's (gpt-5.5's 922K), not the window Codex holds a conversation to (272K): netube on Discord saw Routing say 922K for a Codex Plus account.

func CodexZstdForTests added in v0.1.1206

func CodexZstdForTests(on bool) (restore func())

CodexZstdForTests sets whether turns to the ChatGPT backend go compressed, for a test, and returns what puts it back.

func CompactFor added in v0.1.1214

func CompactFor(s settings.Settings, e Entry, find func(string) (Group, []Member, bool)) int

CompactFor is where Codex compacts a conversation on e (catalog.Model's Compact): the threshold the user set on it or its provider (CompactSet), else, when its window is one the user typed (Entry.WindowSet) and no size of theirs is typed in Settings, that whole window (#1809: a group set to 500K was told Codex as magpie's default 272K, which Codex runs to 95% of). magpie's default gives way to a window the user typed as it does to one they set in Claude Code (#876); a threshold they typed still comes first. 0 leaves it to settings.Compact. It takes the settings and the group finder from its caller: an agent's list is built for hundreds of models at magpie's start, and reading both again for each is what EffectivePriceIn saves the same loop.

func CompactSet added in v0.1.979

func CompactSet(id string) int

CompactSet is the threshold the user set on a model, by its catalog id ("provider/model", magpie/ and a [1m] mark taken off), or on its provider; for a group, the smallest its models have, so none of them outgrows its own. 0 when none is set: settings.Compact then answers.

func CompactSetIn added in v0.1.1048

func CompactSetIn(s settings.Settings, id string, find func(string) (Group, []Member, bool)) int

CompactSetIn is CompactSet with the settings and group finder its caller has already read (CompactFor's).

func CompactsOf added in v0.1.979

func CompactsOf(providerID string) map[string]int

CompactsOf is the thresholds the user set on a provider's models, by model id, "*" for all of them: what its editor's Compact at shows.

func Confidence added in v0.1.862

func Confidence(ps map[string]any) float64

Confidence is how sure a set of probabilities is of its likeliest, as System One gives it: 0 with every option as likely, 1 with one certain (its 0.87 of three options is 0.8).

func CopilotAccountName added in v0.1.1108

func CopilotAccountName(login, host string) string

CopilotAccountName is how a Copilot account is known in magpie: its GitHub login on github.com (host ""), "<login>@<name>.ghe.com" on an enterprise's (#1220). One login on two hosts is two accounts, each with its own token, plan and usage, so the name every list, switch, card and routing setting goes by carries the host. A GitHub login never has an @.

func CopilotHost added in v0.1.795

func CopilotHost(s string) (string, error)

CopilotHost is where a Copilot account signs in, from what a user typed ("acme.ghe.com", "https://acme.ghe.com/", "github.com"): "" for github.com, "<name>.ghe.com" for an enterprise on GHE.com. Nothing else is taken, so a GitHub token is never sent to a host of the user's choosing.

func CopilotRefusal added in v0.1.914

func CopilotRefusal(body []byte) bool

CopilotRefusal is Copilot saying the account may not call the model it was asked for, which Auto, having picked it, picks another for.

func CopilotSocketModel

func CopilotSocketModel(model string) bool

CopilotSocketModel says Copilot's list named model served over its Responses WebSocket ("ws:/responses" in its supported_endpoints).

func CopilotSocketTurn

func CopilotSocketTurn(req *http.Request) bool

CopilotSocketTurn says req is a Copilot account's Responses turn that may go over Copilot's WebSocket (SocketTurn), its model aside (CopilotSocketModel).

func CountPartner added in v0.1.1126

func CountPartner(what string, ids ...string)

CountPartner counts what for each of the partners ids, today.

func CursorBase added in v0.1.297

func CursorBase(id string) (base, effort string, ok bool)

CursorBase is the model magpie offers for one of Cursor's ids at an effort ("grok-4.7-low" is grok-4.7 at low, "grok-4.7-low-fast" grok-4.7-fast at low), and that effort; ok is false for an id that is itself a model magpie offers, or that no family has. Picks and agents' models saved before the families were one model still name these ids.

func CursorVariants added in v0.1.268

func CursorVariants(model string) (map[string]string, bool)

CursorVariants are Cursor's ids a model magpie offers stands for, by effort, "" the default; ok is false for a model that stands for none, which goes to Cursor as it is.

func DecideAnswer added in v0.1.862

func DecideAnswer(via string, b []byte) []byte

DecideAnswer is a gateway's answer as System One gives it: out of Cloudflare's envelope, or, from Vercel's evaluation models (its TypeSafe API answers as System One does), a boolean's probability as a noul, a confidence from the probabilities where there is none, and its usage named as System One names it.

func DecideAsk added in v0.1.862

func DecideAsk(via, model string, body []byte) []byte

DecideAsk is a System One request (body) as via takes it: Vercel's TypeSafe API takes it as it is; its evaluation models name the model in a header and ask a noul as a boolean; Workers AI takes the state and questions as the input of a run of the model, and a Clef there takes the request as it is, its model named as Clef names itself; Google's Decisions API takes it as googleAsk makes it.

func DecideResult

func DecideResult(via string, status int, b []byte) (int, []byte)

DecideResult is a decision API's answer, status and body, as System One gives it: DecideAnswer's translation of one that answered, and, from Google, an input its filters blocked (prompt_feedback.block_reason, "no decisions were evaluated, and answers is empty") as the 400 Google answers a blocked input with otherwise, its reason in the message.

func DecideRouteStatus added in v0.1.411

func DecideRouteStatus(err error) int

DecideRouteStatus is the HTTP status a System One request gets for err from RouteDecider: 400 when the model is named badly, 404 when magpie has no such Jev provider.

func DecisionGroup added in v0.1.1170

func DecisionGroup(ms []Member) bool

DecisionGroup reports whether ms, a group's models as they resolve now, are decision models, every one: the group answers System One, not a conversation.

func DeclareSearch added in v0.1.1142

func DeclareSearch(body []byte, lite bool) []byte

DeclareSearch is body with the web_search tool declared when its input replays a web search and nothing declares the tool, or body as it was. lite says the request goes as Codex's Responses Lite, whose tools are an additional_tools input item: the backend refuses a web_search among a Lite request's tools (400 "only supports function tools, custom tools, and client-executed tool search").

func Delete

func Delete(id string) error

Delete removes a provider. An account, a built-in's or a plugin's, is only hidden from magpie (its accounts and model picks kept, shown again from Hidden or by signing in); signing out is each account's Remove.

func DeleteGroup added in v0.1.38

func DeleteGroup(id string) error

DeleteGroup removes a group of the user's; one magpie found is hidden, to come back with ShowGroup. A group another has in it, or classifies with, stays until it is taken out of that one.

func DeleteGroups added in v0.1.912

func DeleteGroups(ids []string) error

DeleteGroups removes several groups at once, as DeleteGroup does each (lc on Discord: they could only be removed one at a time). It is all or none: refused, before any is removed, when one isn't there or a group left holds one as a member or classifier; one held only by another of them goes after it.

func DesktopSubagentEffort added in v0.1.1243

func DesktopSubagentEffort() string

DesktopSubagentEffort is the effort set for Desktop's subagent turns, independent of their model. Empty leaves each request's effort alone.

func DesktopSubagentModel added in v0.1.1234

func DesktopSubagentModel() string

DesktopSubagentModel is the model Desktop's subagents are put on, "" for the one the lead asks for. A provider renamed since it was set is named by its new id (RenamedRef), as a profile's model is.

func DesktopSubagentUnserved added in v0.1.1234

func DesktopSubagentUnserved(id string) string

DesktopSubagentUnserved says why Desktop's subagents can't be put on id now, "" when magpie serves that exact model or routing group. Resolve isn't enough: it takes any model name under a provider that is on, and the subagent would go to the vendor for a model it lacks.

func DetectBase added in v0.1.663

func DetectBase(base string, proto Protocol) string

DetectBase is base as proto takes it: an endpoint pasted whole (…/v1/chat/ completions, …/models/gemini-2.5-pro:generateContent) cut to its base, then the root for Anthropic, which adds /v1/messages itself, …/v1 for OpenAI's two when base is a bare host, and for Gemini's the …/v1beta beside a …/v1 or on a bare host (GeminiBase) — the editor's respellURL, in Go.

func DeveloperMessage

func DeveloperMessage(text string) map[string]any

DeveloperMessage is text as a Responses developer message, as Codex sends its base instructions in the input.

func DevinAuth added in v0.1.175

func DevinAuth() (key, server string, err error)

DevinAuth is the key the CLI signed in with and the server its API is on, read from credentials.toml; WINDSURF_API_SERVER_URL moves the server, as it does the CLI's.

func DevinAuthAt added in v0.1.386

func DevinAuthAt(home string) (key, server string, err error)

DevinAuthAt is DevinAuth for the account signed in in home, "" for the CLI's own.

func DevinCredentialsPath added in v0.1.45

func DevinCredentialsPath() string

DevinCredentialsPath is where the CLI keeps its sign-in.

func DevinModelEffort

func DevinModelEffort(id string) (model, effort string)

DevinModelEffort splits a Devin variant id into the model it runs and the effort it runs at, the way its own logs name a call (generation_model): swe-2-high is ("swe-2", "high"), claude-opus-5-5-high-fast ("claude-opus-5-5-fast", "high"), and an id that names no effort (glm-5-2-1m, swe-1-6-fast) is itself with none. No family list is needed: the effort and tier words are Devin's own (devinLevels, devinTiers).

func DevinNoWait added in v0.1.424

func DevinNoWait(ctx context.Context) context.Context

DevinNoWait marks a context whose caller must not wait on the devin CLI: the window's state, drawn after every click. DevinFamilies then answers with what it knows (or an error while nothing is known) and asks the CLI in the background, so the next state has it.

func DevinOffered added in v0.1.380

func DevinOffered(families []DevinFamily) []catalog.Model

DevinOffered is Devin's list as an agent's picker offers it: each family one model with the efforts its variants are at, as the provider lists it (devinModels), and Adaptive and Fusion — which Devin's own agent runs, though the API doesn't serve them — as the one model each.

func DevinPick added in v0.1.380

func DevinPick(families []DevinFamily, model, effort string) string

DevinPick is the id to give Devin's config for a model and effort picked as magpie offers them (DevinSplit the other way round): a family's variant at the effort, or the nearest it has; the family's own id with no effort, so that it keeps following the family's default; a fast run's variant at the effort, or at the family's default one. Any other id goes as it is.

func DevinSplit added in v0.1.380

func DevinSplit(families []DevinFamily, id string) (model, effort string)

DevinSplit is an id Devin's config holds taken apart as magpie offers it: the model (a family, or a family's fast run) and the effort the id is at. A family's own id is at none — it follows the family's default — and an id no family has at an effort (glm-5-2-1m, one Devin no longer lists) is itself, at none.

func DevinVariant added in v0.1.175

func DevinVariant(ctx context.Context, model, effort string) string

DevinVariant is the model to ask Devin's API for: a family's name follows its newest model, which the API takes only as one of its variants — the one at the effort asked for, or at the nearest effort the family has; with none asked, the family's default. A family's fast run (claude-opus-5-5-fast) is likewise its fast variant at that effort (claude-opus-5-5-high-fast). A variant's own id (swe-2-medium, one an agent was set to) goes as it is, whatever effort is asked: its id is the effort it runs at.

func DisableModels added in v0.1.1219

func DisableModels(pats ...string) error

DisableModels adds patterns to the disabled list.

func DisabledBy added in v0.1.1219

func DisabledBy(pat, pid, model string) bool

DisabledBy reports whether the one pattern pat disables pid's model.

func DisabledHits added in v0.1.1219

func DisabledHits(pat string) []string

DisabledHits are the providers' models, on and listed, that pat turns off now, as "<provider>/<model>".

func DisabledModels added in v0.1.1219

func DisabledModels() []string

DisabledModels are the patterns the user disabled, as saved.

func DisabledPattern

func DisabledPattern() func(pid, model string) string

DisabledPattern is ModelDisabled's pattern with the list read once, for a loop over many models: "" for a model that isn't disabled.

func DisabledUnknown added in v0.1.1219

func DisabledUnknown() bool

DisabledUnknown reports that settings.json can't be read and no list was read before it: the gateway then refuses every model, since any of them may be one the user disabled.

func DismissCodexApp added in v0.1.1155

func DismissCodexApp()

DismissCodexApp stops saying the Codex app is on another account.

func DismissCodexAppProjects

func DismissCodexAppProjects()

DismissCodexAppProjects stops saying so.

func DismissCodexDaemon added in v0.1.368

func DismissCodexDaemon()

DismissCodexDaemon stops saying the app-server is on another account.

func DropContext added in v0.1.532

func DropContext(p Provider, model string) (bool, error)

DropContext takes a window off one of a provider's models and reports whether there was one there to take away, as DropModelPrice and DropModelOutput do: a removal over a window that is not there leaves the provider in the state it was already in, but only the caller can tell the user so, and a ✓ over a window that was never set says there was one. Nothing is saved in that case, and so the agents are not told either — a provider saved over a window that did not change rewrites every agent's model lists for nothing, which is the one round the removal itself earns.

Save is what tells the agents here (store), so it is the save, and not a Touched of its own, that has to happen exactly once.

func DropModelOutput added in v0.1.532

func DropModelOutput(id string) (string, bool, error)

DropModelOutput takes a user's reply limit away under the key it is stored at, and hands that key back, so a caller left without a provider to name it by can still say which entry it cleared. It does not ask whether the provider is still there: a reply limit outlives the provider it was set for, and that provider can be deleted — the entry then sits in the settings answering for a model nothing serves, and a removal that resolved the provider first would leave the user no way to take it away, the file being the only other place it is in. Which key that is comes from the spelling as given before anything is looked up (outputKeyOf), so that a provider which has since taken the name of one that is gone is not the one the entry is cleared under. A key holding no limit is no error: there is nothing there to take away, which is the state the entry is left in either way, and writing it out again would rewrite the settings and every agent's model lists over a limit that did not change.

It reports whether there was a limit there to take away, as DropModelPrice does, and by neither saving nor telling the agents when there was none: only the caller can put that to the user, and a ✓ over a limit that was never set says the model had one.

func DropModelPrice added in v0.1.504

func DropModelPrice(key string) (bool, error)

DropModelPrice takes a user's price away under the key it is stored at, without asking whether the provider is still there, and reports whether there was one there to take away. A price outlives the provider it was set for: that provider can be deleted, and `magpie model prices` still lists the price and usage is still counted at it, so a removal that resolved the provider first would leave the user no way to take it away. Which of the keys a price is ever kept under this one is, is PriceKey's to say.

A key holding no price is still no error — there is nothing there to take away, which is the state it is left in either way — but saying so is what tells a mistyped id from a price that was cleared: `magpie model price -- reset` over a price still in the file would have the user believe it gone.

func DropUpstreamName added in v0.1.560

func DropUpstreamName(key string) (bool, error)

DropUpstreamName takes a name off under the key it is stored at, and says whether there was one to take. A name outlives the provider it was given for: that provider can be deleted, and the name is then in force for whichever provider takes that id next — its requests would go out renamed to a vendor that never heard of it, and nothing would say so — so a removal that resolved the provider first would leave the user no way to take away the one name doing that. A key holding no name is not an error: there is nothing there to take away, which is the state it is left in either way, and false says so to a caller that has something else to say.

Which key a ref is taken at is wireKey's: the name comes off from where it is really kept, rather than from under whichever provider the ref names now.

func DshCompactModel

func DshCompactModel() string

DshCompactModel is the model DSH's compactions are put on, "" for the one each asks for. A provider renamed since it was set is named by its new id (RenamedRef).

func EdgeBlocked added in v0.1.570

func EdgeBlocked(b []byte) bool

EdgeBlocked says whether an error body is a firewall's block page rather than the vendor's API answering, or one already put in plain words.

func Edited

func Edited() <-chan struct{}

Edited is closed when this magpie next writes the providers.

func EffectivePrice added in v0.1.504

func EffectivePrice(providerID, model string) (catalog.Price, bool)

EffectivePrice is what a call to a provider's model costs the user: the price they set for that model, or for every model of that provider, or for that model from any provider (settings' ModelPrices), else the provider's own list price, else its maker's, else the maker's of the model the user said it is the same as (SamePriceIn), each at the provider's price rate (PriceRate), and again at the rate of the time-of-day window the call falls in (RateWindows, #2463) — the window's rate on a price the user set as well, the price rate alone leaving it as set. The second return is false only when no price is known at all, which is not the same as a price of zero: that one is set, deliberately.

A price here is the provider's tariff, not the model's: the same model through two relays is two prices, and neither is what models.dev lists.

func EffectivePriceAt added in v0.1.2200

func EffectivePriceAt(s settings.Settings, providerID, model string, at time.Time) (catalog.Price, bool)

EffectivePriceAt is EffectivePriceIn at the time given: a record's own time when one is priced, now for a price shown before a call. A caller pricing many records takes BasePriceIn once per model and multiplies each record's window rate on itself, so one read of the prices serves every time of day.

func EffectivePriceIn added in v0.1.504

func EffectivePriceIn(s settings.Settings, providerID, model string) (catalog.Price, bool)

EffectivePriceIn is EffectivePrice at the settings given, for a caller pricing a whole list of models at one read of the file rather than one read per model: every model of that list is priced at the same copy, so the list is one snapshot of the prices rather than a reading per row, and a price changed while it is read takes effect in the next call.

func EffortFamily added in v0.1.603

func EffortFamily(id string) string

EffortFamily is the model an id with an effort word after it is a level of ("gemini-3.8-flash-medium" is gemini-3.8-flash), and the id itself when it has none.

func EffortsOf added in v0.1.137

func EffortsOf(m catalog.Model) []string

EffortsOf is the reasoning levels one of a provider's listed models has, before any the user left out.

func EnableModels added in v0.1.1219

func EnableModels(pats ...string) (missing []string, err error)

EnableModels takes patterns off the disabled list (ignoring case); it says which of them weren't on it.

func EntriesBuilt

func EntriesBuilt() int64

EntriesBuilt is how many times the catalog was built from every provider's files, for another package's test that counts them.

func EntryPriceIn added in v0.1.1131

func EntryPriceIn(st settings.Settings, find func(string) (Group, []Member, bool), e Entry) (catalog.Price, bool)

EntryPriceIn is what a call to an entry of the catalog costs the user, as the usage pages count it: its model's EffectivePriceIn, or a group's when every member costs the same, none in a fast mode, since which of them answers isn't known beforehand. find is GroupFinder's.

func EntryPricer added in v0.1.1437

func EntryPricer(st settings.Settings, find func(string) (Group, []Member, bool)) func(Entry) (catalog.Price, bool)

EntryPricer is EntryPriceIn for a whole list of entries, at the one read of the providers it makes: what a /v1/models or an agent's model file prices row by row.

func ErrorType added in v0.1.579

func ErrorType(b []byte) string

ErrorType is the kind of error a vendor's body names — the error's type (rate_limit_error, usage_limit_reached), else its code — or "" when it names none: what to set beside the status when a request failed.

func ExtraBodyOK added in v0.1.1191

func ExtraBodyOK(e ExtraBody) string

ExtraBodyOK says what is wrong with an extraBody, "" when nothing is.

func FactoryBaseForTest added in v0.1.685

func FactoryBaseForTest(api, eu string) func()

FactoryBaseForTest points Factory's API at api, and its EU region at eu, until the returned function runs. A provider built after the call uses them. Tests outside this package use it.

func FallbackGroup added in v0.1.1962

func FallbackGroup(id string) (Group, []Member, bool)

FallbackGroup is the routing group a provider's fallback entry names ("group/<id>", 01huadalang on Discord), as the gateway routes it (Live), with its members ready now. ok is false for an entry naming a model, and for a group removed or switched off: such an entry is passed over.

func Families added in v0.1.111

func Families() []string

Families are the families providers and groups are tagged with, sorted.

func FastPicks added in v0.1.1077

func FastPicks(agent string) []string

FastPicks are the entries agent's requests for are sent fast, read once for a list of them all.

func FaviconFor added in v0.1.186

func FaviconFor(ctx context.Context, base, name string) (string, error)

FaviconFor finds the site behind a provider's base URL and keeps its icon like a picture picked by hand (#12). The API's own host is asked first, then the domains it sits under (api.deepseek.com, then deepseek.com), since an API host seldom has a page of its own. On each, the home page's <link rel="icon"> pictures come before /favicon.ico. Only public https hosts are reached, as for an import link's icon.

A new-api or one-api site names its logo only in /api/status, which its page's script reads to set the tab's icon; the page itself names none, or the panel's own /logo.png, and its /favicon.ico is the panel's too, the same on every such site (wiixdede on X: every relay got new-api's icon). Its logo is taken from there, or one its page was given by hand, and one with neither gets name's first letters on a tile.

func FetchIcon added in v0.1.21

func FetchIcon(ctx context.Context, rawURL string) (string, error)

FetchIcon downloads the picture an import link named and keeps it like any other, returning the Icon value that points at it. It runs when the user confirms the import, never at parse time; the URL is re-checked here so a crafted request can't point magpie at anything but a public https picture, and the read stops one byte past MaxIcon so a huge body is refused rather than buffered. The picture is asked for through usemagpie.ai's icon proxy, so its host never sees the user's IP.

func FetchNew added in v0.1.402

func FetchNew(timeout time.Duration) (missing bool)

FetchNew asks each signed-in account whose vendor list magpie hasn't fetched yet for it, each for at most timeout. Start-up does this for the accounts there then; an account signed in while magpie runs (in magpie or in the agent's own app) otherwise showed magpie's built-in list, fewer models than the vendor serves, until Refresh was clicked (#204). One that fails is asked again after newFetchRetry, not each time. It reports whether an account is left without its list (one that failed, or that failed less than newFetchRetry ago), for a caller with no page to ask again from (the terminal, magpie serve) to try once more later.

func FetchNewBehind added in v0.1.651

func FetchNewBehind(timeout time.Duration)

FetchNewBehind is FetchNew in the background, started at once unless one started so is still running: for the Providers page, which waited on it (#541: ten seconds and more of placeholders, an account at a time and behind start-up's own run). FetchingNew says when it is done.

func FetchNewSoon added in v0.1.591

func FetchNewSoon(timeout time.Duration)

FetchNewSoon is FetchNew in the background, for a page that shouldn't wait on vendors (the panel, whose model picker otherwise kept an account's fallback list until the Providers page was opened). It does nothing while one runs or within newSoonEvery of the last.

func FetchingNew added in v0.1.651

func FetchingNew() bool

FetchingNew reports whether a FetchNew is under way (start-up's, or one started behind a page): accounts' lists may be on their way still. One started behind a page counts from its start, while it still picks the accounts due: a page whose FetchNewBehind found it so returned at once, and was told none was on its way until the one picking counted itself.

func FileError added in v0.1.587

func FileError() error

FileError is why providers.json can't be read, nil when it can or isn't there: for what lists the providers to say so, not "none yet".

func FindDrawingGroup added in v0.1.2794

func FindDrawingGroup(id string, draws func(p Provider, model string) bool) (Group, []Member, bool)

FindDrawingGroup is FindGroup for a drawing (the gateway's images API): a member that is one of its provider's image models, as draws says, is the group's even where the provider's picks leave it out (unpicked). Picks are of chat models, and an image model is offered to a group beside them (jzw690 on X), so a group of image models draws on its members without any of them being a model agents are offered.

func FindGroup added in v0.1.38

func FindGroup(id string) (Group, []Member, bool)

FindGroup looks a group up by its catalog id ("group/<id>") and resolves its members; one not ready now is left out.

func FindGroupAlso added in v0.1.3033

func FindGroupAlso(id string, also func(p Provider, model string) bool) (Group, []Member, bool)

FindGroupAlso is FindGroup with a member also says is the group's kept where its provider's picks leave it out: picks are of chat models, so a group of models made for another API (images, embeddings, speech, video) keeps those of a provider with picks only so (FindDrawingGroup, the gateway's media groups).

func FirstLogin added in v0.1.1226

func FirstLogin(agent string) string

FirstLogin is the account of an agent's first in the gateway's order, as InUseLogin, by the order alone: the one the agent is signed in to unless it is paused, else the first other one on; kept signed in to one of the user's choosing, the first on in the order (#1957). An account spent is still named, so a list that names it isn't rewritten each time an allowance is read. "" when the agent has none, or is none whose own sign-in is paused for its others (Claude Code's and Codex's).

func FlatID added in v0.1.1137

func FlatID(id string) string

FlatID is a catalog id with no slash in it.

func FlatName added in v0.1.572

func FlatName(namespace, name string) string

FlatName is the name a namespaced tool is offered to a model under, which takes one flat name: namespace__name, as Codex names an MCP server's tools. A name longer than the 64 characters APIs allow is cut and made unique by a hash of the whole.

func Flattened added in v0.1.1137

func Flattened() map[string]string

Flattened maps each served id that can be spelled flat, and taken back by Unflat, to that spelling; an id two served ids flatten to alike is left out, as is one already without a slash.

func FlushServed added in v0.1.1291

func FlushServed()

FlushServed writes what NoteServed noted and hasn't written yet: the gateway calls it as it ends.

func FoldCopies added in v0.1.1614

func FoldCopies() (int, error)

FoldCopies folds the providers that are copies of one, a key each (see above), as providers.json has them now. Run at start-up, so a user who has them already (from an import before this) finds them folded. It answers how many providers were folded into others. A providers.json that can't be read is left alone.

func FolderUnder added in v0.1.1180

func FolderUnder(folder, root string) bool

FolderUnder reports whether folder is root or a folder inside it: at a path's boundary, so /a/b is not under /a/bc. An unknown folder ("") is under none.

func ForgetAccount added in v0.1.770

func ForgetAccount(id string) error

ForgetAccount signs a subscription's accounts out of magpie for good, the way past a removal (#694: a removed Qoder came back with its old account each time it was added back, and nothing took it away). A plugin's sign-ins leave plugin-auth.json (the plugin host's signOut when one runs, else under plugin-auth.json.lock) and logins.json, and a moved built-in's backup of them goes too, so moving back doesn't bring them either; a built-in's saved accounts go as each account's Remove takes them. An agent's own sign-in, which magpie only reads, is hidden as Remove hides it. Signing in again starts afresh.

func ForgetAccounts added in v0.1.362

func ForgetAccounts()

ForgetAccounts makes the next look at the accounts read them afresh, for a caller that changed a sign-in behind magpie's back (a test's home).

func ForgetBalanceProbe

func ForgetBalanceProbe(p Provider)

ForgetBalanceProbe drops what was found for p, so its balance is looked for again at the next read (the editor's Check balance).

func ForgetBalances added in v0.1.90

func ForgetBalances()

ForgetBalances has the next KeyBalances ask again, after a provider's key or balance token changed.

func ForgetCodexClientsForTest added in v0.1.2805

func ForgetCodexClientsForTest()

ForgetCodexClientsForTest forgets the Codex version the gateway saw a client say it was and the one it found installed, for a test that asks what the pool says it is: both are kept for the process's life (the installed one for ten minutes, read in whichever test's HOME asked first), so an earlier test's Codex 0.165.0 spoke for the next test's 0.161.0 (#4807).

func ForgetCopilotForTest added in v0.1.1077

func ForgetCopilotForTest()

ForgetCopilotForTest drops what magpie keeps of each Copilot account for the process's life — its session (and the API endpoint it named), Auto's session, the models it was refused, may pick or saw — so a test run again (-count) asks the fake GitHub it serves rather than the last run's.

func ForgetKeptCardsForTest added in v0.1.1120

func ForgetKeptCardsForTest()

ForgetKeptCardsForTest has the cards kept on disk (quotas.json) read again from the home a test has set: they are read once per process.

func ForgetLogin added in v0.1.11

func ForgetLogin(agent, user string) error

ForgetLogin drops a remembered account. The one an agent is signed in to now would only be remembered again, so Codex and Claude Code are signed in to another of their accounts first (nextOnForget), as its Use would (StringKe, #4532: Claude's was refused while Codex's switched). Codex's last one is signed out instead, as `codex logout` does (mamba on Discord: a single Codex account couldn't be removed at all). Claude Code's last one that it can be signed in to is kept, and the removal refused (SignedInError, Only): magpie never signs Claude Code out.

func ForgetPlanQuotas added in v0.1.1142

func ForgetPlanQuotas()

ForgetPlanQuotas has the next PlanQuotas ask again, after what a plan's windows are read with changed (a Volcengine or Tencent Cloud access key).

func ForgetRemoteCardsForTest added in v0.1.1078

func ForgetRemoteCardsForTest()

ForgetRemoteCardsForTest drops the remote magpies' cards kept here, for a test run again (-count) to ask its own fake remote afresh.

func ForgetRemoteUpdatesForTest added in v0.1.3285

func ForgetRemoteUpdatesForTest()

ForgetRemoteUpdatesForTest drops what remotes answered.

func ForgetReorders

func ForgetReorders()

ForgetReorders forgets every NoteReordered, for a test that reordered accounts: a later test's conversation, backdated past the real time of that reorder, would otherwise be routed anew (#6249).

func FoundOnce added in v0.1.3117

func FoundOnce(find func(string) (Group, []Member, bool)) func(string) (Group, []Member, bool)

FoundOnce is find answering each group once: an agent's list asked a group's members for its compaction, its price twice and its protocols and tiers twice, each walking the group's members and resolving each (~8 MB in 2 minutes of an idle magpie's list rebuilds). What it gives is shared between the calls: only for reading.

func FreeID added in v0.1.399

func FreeID(id string) string

FreeID is id, or id-2, id-3… whichever no provider or subscription has.

func FreePlan added in v0.1.2921

func FreePlan(plan string) bool

FreePlan says whether an account's plan, as its vendor or plugin names it, is a free one: "Free", "Free plan", a trial. FreeExpiring spends such an account's quota before a paid one's.

func GateGroups added in v0.1.1248

func GateGroups(refresh func()) (stop func())

GateGroups makes the user's own groups wait on ServeGroups until stop: the gateway calls it as it starts serving. refresh, when not nil, is asked to bring the plugins up to date when a lookup gated finds a group of the user's own (served).

func GeminiAsked

func GeminiAsked(u string) string

GeminiAsked is the base a Gemini API is asked at: the saved base, and a bare host given /v1beta, as Google's SDKs add the version to a base_url with no path. GeminiBase keeps a relay's root as typed (JNDliuliuM on X), so the version is added here, where a request goes: WandAPI's https://api.wandapi.ai was asked at /models/… and refused (equinox0253 on X). A base with a path of its own (/v1beta, a relay's /gemini) is asked as typed.

func GeminiBase added in v0.1.1125

func GeminiBase(u string) string

GeminiBase is the base a Gemini URL is kept as: trimmed, an endpoint or the model list pasted whole cut back to the base. Only Google's own bare host is given its version (/v1beta); any other URL stays as typed, so a relay's root is not rewritten on the next open (JNDliuliuM on X).

func GeminiModelPath

func GeminiModelPath(model string) string

GeminiModelPath is model as every Gemini and Vertex AI path names it after models/: each slash-separated segment escaped and the slashes kept, so a relay's namespaced id (example/model-demo) is asked at /models/example/model-demo, the path the relay routes by, not /models/example%2Fmodel-demo (#6695, LuoRuiyao on X). An id with an empty, . or .. segment, which a server or proxy could clean into a path outside models/, goes as one escaped segment instead. An id with the models/ Google's own lists name a model by (AI Studio's OpenAI-compatible /models lists "models/gemini-…") is asked without it, since the path already has one: drawn at models/models/… the Gemini API answered 404 (Dani Ariyanto on Discord, Nano Banana 2.1).

func GeminiPath added in v0.1.1125

func GeminiPath(model string, stream bool) string

GeminiPath is the path under a Gemini base model is asked at: streamed as server-sent events (alt=sse) when stream, else one JSON reply.

func GitAt added in v0.1.2181

func GitAt(path string) (git, common string, err error)

GitAt is what the .git at path is to git's own search for a repository (repo_discovery_find_dir in git 2.56's setup.c): "yes" for a folder git takes for a repository (gitDir), or a file naming one ("gitdir: …", as a linked worktree's or a submodule's is), with the folder that holds the repository's config, objects and refs; "no" for any other file, where git stops with "not a git repository"; "" for nothing to go by, no .git or a folder git passes over. An error is a .git it couldn't read.

func GitOnDisk added in v0.1.1191

func GitOnDisk(dir string) string

GitOnDisk says whether dir, a folder on this computer, is in a git repository as git finds one from there: the nearest .git in it or in a folder above it that git takes (GitAt). A .git folder git doesn't take, an empty one say, is passed over as git passes it over, so an empty /tmp/.git doesn't make every folder under /tmp a repository (#3675). "" when dir isn't a folder here (an agent on another computer, through a shared magpie) or a .git on the way can't be read (another user's, through a shared magpie): unknown, never "no".

func GitSaid added in v0.1.1191

func GitSaid(text string) string

GitSaid is the last "yes" or "no" an agent's text says of its folder being in a git repository, "" when it says neither.

func GoneAutoGroup

func GoneAutoGroup(ref string) bool

GoneAutoGroup reports whether ref names a group magpie found that is gone with its model: no group of that id now, none the user has or removed, and no provider serving its model (AutoStandIn has none). An agent's conversation saved on it (canlee886 on X: a Codex thread on group/auto-gpt-6-1-sol) is told the model is gone and to pick another, rather than every id magpie has.

func GrokBuildFast added in v0.1.1258

func GrokBuildFast(id string) (string, bool)

GrokBuildFast is the Grok model id is Grok Build's fast variant of (grok-4.7-build-fast is grok-4.7's), and whether it is one: for a Grok CLI session, which names it bare, priced as grokFastPrice prices it.

func GrokFlatBody

func GrokFlatBody(body []byte) []byte

GrokFlatBody is a Responses body with Codex's namespaced functions flat (namespace__name) and every function's parameters an object at the root, the two things Grok's backend turns a request away over wherever it is served (Copilot's grok-4.7, #4374), and nothing else: tool types, reasoning and the rest go as they came. The model's call to a flat name is given its namespace back by the gateway (namespacedIn).

func GrokHome added in v0.1.22

func GrokHome() string

GrokHome is where the CLI keeps its sign-in and settings.

func GrokUser added in v0.1.22

func GrokUser(home string) (string, bool)

GrokUser is who the grok with this home is signed in to.

func GroupEndpoints added in v0.1.3157

func GroupEndpoints(ms []Member) []string

GroupEndpoints are the paths a request for a routing group is relayed on as it is to whichever of its members ms answers it: the APIs every member takes it on. None when a member translates every request anyway, or the members share no API.

func GroupFinder added in v0.1.133

func GroupFinder() func(id string) (Group, []Member, bool)

GroupFinder is FindGroup for looking up many: every provider's models are read once, when the first group is looked up, not again for each.

func GroupFor added in v0.1.136

func GroupFor(id string) (string, bool)

GroupFor is the group a model's id without a provider in it names, as "group/<id>": the group of that id, else the group of that model however a vendor spells it ("grok-4.7" is the group grok-4-7 or auto-grok-4-7). A request for the model is the group's then, as it would be for the group's own id; failing those, the group whose name it is (groupNamed); ok is false when no group has it. An id with a provider in it ("a/m") names that provider's model, never a group.

func GroupHasNative

func GroupHasNative(id string, api Protocol) bool

GroupHasNative says whether the group id has a member found now that speaks api natively, kept across requests while the files stay the same (keptOf, a minute at most). Pi's Drift asks it of the model an agent is set to on every /api/drift poll, and finding the members was ~3.4 MB a poll with real accounts, four of five bytes the window allocated a minute.

func GroupIDOf added in v0.1.1083

func GroupIDOf(ref string) (string, bool)

GroupIDOf is the group id a ref names ("group/<id>", or a found group's "auto/<model>": CanonicalRef), with spaces and the [1m] mark Claude Code puts on a 1M window taken off, as an agent's own settings carry it. ok is false for a ref that isn't a group's.

func GroupKept added in v0.1.2400

func GroupKept() map[string][]string

GroupKept is the models, by "provider/model", that a group listing alone (Group.Unlists) keeps out of agents' lists, with those groups' names: a provider's editor names them, as a model its own switch put back for agents is still left out by them. Held as MemberGroups is: shared, only for reading.

func GroupMember added in v0.1.136

func GroupMember(g Group, in string) (string, error)

GroupMember is the group's member a typed model names: its id, its model id without the provider, or the model's last name — each with the effort fixed on the member ("m:high") or, when only one member is of that model, without it.

func GroupRefs

func GroupRefs(id string) []string

GroupRefs are the refs an agent's list names the group id by now: group/<id>, and a found group's auto/<model> besides. None for no such group.

func GroupRoutedAt

func GroupRoutedAt(id string) time.Time

groupOf is the group of an id among all, unless it was removed. GroupRoutedAt is when the user last changed group id's routing (Group.RoutedAt); the zero time when never, or no such group. It reads the groups held for the catalog, no copy made: the gateway asks it once a request to a group.

func GroupRouting

func GroupRouting(routing string) bool

GroupRouting says whether routing is one a routing group can be routed by besides Smart (""): a built-in one, Manual, or a plugin's.

func GroupSlug added in v0.1.1078

func GroupSlug(name string) string

GroupSlug derives a group's own id from a name as Slug does, the dots kept: "GPT 6.1 Sol" → "gpt-6.1-sol", so an agent sending group/<id> sends the model's name as harnesses that price or tune by it read it (#968). A run of dots is one, and none starts or ends it. The ids magpie finds (auto-…) stay Slug's, so no id saved before changes.

func GroupsAfter added in v0.1.3364

func GroupsAfter(id string) []string

GroupsAfter are the routing groups the user built that have id ("provider/model") in them as a member and another member to go on to, as "group/<id>", in the user's order; one magpie found (Auto), hidden or switched off is none. A request for the model that its own accounts can't take (every one held at its usage cap, or Codex's own sign-in out of its allowance) goes on to these when nothing set as its fallback takes it (adorable_piglet on Discord, v0.1.3354): the Codex app asks Codex's own model, never the group built around it. A request that named the provider itself ("claude/…") is not sent on to these (gateway's namedProvider, Anotiaww on X).

func GroupsBound

func GroupsBound() bool

GroupsBound says some routing group is bound to gateway keys (Group.Keys), read from the groups held for the catalog, no copy made: a model list for a key no group binds needs no other look.

func GroupsFound

func GroupsFound() int64

GroupsFound is how many times a group's members were found, for another package's test that counts them.

func GroupsServed added in v0.1.1248

func GroupsServed() bool

GroupsServed says whether the user's own groups are served here now.

func HandOver added in v0.1.661

func HandOver(ctx context.Context, accounts bool) map[string]error

HandOver gives each deprecated built-in whose plugin the user has installed, at the version its move needs, and which that plugin serves, its id, so one subscription is never listed twice: the built-in, and the plugin's under "<id>-plugin" (ARNO on Discord: Qoder CN twice once the Qoder plugin's 0.2.0 served it, as nothing gave it the id). One with no accounts is the plugin's at once, as Adopt makes it; with accounts too, one that has some is moved (Move: each tried through the plugin, all put back on any failure, the built-in carrying on). One the plugin has accounts of its own for already is left as it is, since its models are in use as <id>-plugin's and the id changing would leave agents asking for a provider gone; the add sheet lists it once regardless. One moved whose plugin the user removed is the plugin's again once they install it, its accounts still with the plugin, and a failed move waits retryWait. No plugin is installed for it: the user's own install is what says to.

func HarnessOnly

func HarnessOnly(b []byte) bool

HarnessOnly says whether an error body is OpenRouter's refusal of a request not from an agent app it lists.

func HasMiniMax added in v0.1.910

func HasMiniMax() bool

HasMiniMax says whether a MiniMax Code account is signed in, on either site.

func HasPickedMagpie

func HasPickedMagpie() bool

HasPickedMagpie reports whether a Remote magpie's picks could be asked: a caller with nothing to follow asks no one.

func HasPluginCheckin added in v0.1.1085

func HasPluginCheckin() bool

HasPluginCheckin says whether a plugin that checks in is signed in.

func HasQoder added in v0.1.1077

func HasQoder() bool

HasQoder says whether a Qoder account of the plugin is signed in, on either site.

func HasTrae added in v0.1.784

func HasTrae() bool

HasTrae says whether a Trae CN account is signed in.

func HasUpstreamName added in v0.1.560

func HasUpstreamName(key string) bool

HasUpstreamName reports whether a name is kept under exactly the key it is given, the provider's part spelled as it is. No other spelling of the provider is tried: a caller deciding whether to remove a name by this key has to know that this key is the one a name is kept under, which is the one question wireKey's order is about.

A key spelled as an agent spells one — with magpie/ in front of it, and the spaces a ref is typed with — is that same key, as it is for a removal (DropUpstreamName): a name kept under it is there whichever way it is spelled, and a check that answered for one spelling only would say a name was not kept where it is. The one caller has had that prefix taken off already (splitModelRef), so nothing depends on it yet.

func HasWorkBuddy added in v0.1.356

func HasWorkBuddy() bool

HasWorkBuddy says whether a WorkBuddy (China) account is signed in.

func Held added in v0.1.2457

func Held[T any](key string, build func() T) T

Held is what build gives, built once while a request holds it (Hold), for what each row of a page looks up: shared by them, so read only.

func HeldSettings added in v0.1.908

func HeldSettings() settings.Settings

HeldSettings is the settings as heldSettings reads them, for a look outside the package made many times in one request.

func HiddenModels added in v0.1.460

func HiddenModels(agent string) map[string]bool

HiddenModels are the ids of the entries taken out of agent's lists, a found group saved by its old id, group/auto-<slug>, by the one it is listed by now (PublicRef).

func Hold added in v0.1.705

func Hold() (release func())

Hold keeps the catalog built once until release is called, for a request that only reads; a write meanwhile (Changed) drops it.

func HostOf

func HostOf(u string) string

HostOf pulls the host out of a URL, for display.

func IDDisabled added in v0.1.1219

func IDDisabled(id string) (string, bool)

IDDisabled reports whether a model id as asked ("<provider>/<model>" or a bare id) is one the user disabled, and the pattern that did.

func IDs

func IDs() []string

IDs lists the catalog ids, for error messages.

func IconDir added in v0.1.10

func IconDir() string

IconDir is where pictures given to providers are kept.

func IconFile added in v0.1.10

func IconFile(name string) string

IconFile is the path of a stored picture, for a name as StoreIcon made it; "" for anything else, so a request can't reach outside the folder.

func IconForCatalog

func IconForCatalog(catalogID string) string

IconForCatalog names the logo of the vendor behind a models.dev provider id, or "" when no preset covers it. A preset names several catalogs ("stepfun-ai-step-plan, stepfun-ai"), so an id is also found in that list; a preset whose catalog is exactly the id comes first, so Azure's "azure, openai" never gives OpenAI's models Azure's logo.

func IconFromURL added in v0.1.2390

func IconFromURL(ctx context.Context, raw, name, base string) (icon, failed string, err error)

IconFromURL keeps the picture at an address the user typed for a custom provider, since many sites have no /favicon.ico (usrname1833). It is fetched as a site's icon is: a public https host only, through the guarded client, within fetchIcon's time and MaxIcon, and kept only when StoreIcon knows it as a picture. With no address, or one that fails, it keeps the letter tile of name (or of base's site) instead, and failed says why.

func IconServed added in v0.1.1587

func IconServed(name string) (path, ctype string)

IconServed is the file to send for a stored picture and its type, "" to go by its name; path is "" for a name IconFile refuses. A PNG, JPEG or WebP longer than iconSide on a side is sent as a PNG copy scaled down to it, made on its first ask and kept; one that can't be read or scaled is sent as it is.

func ImageOverride added in v0.1.413

func ImageOverride(pid, model string) (bool, bool)

ImageOverride is the user's answer for whether pid's model takes images.

func ImageOverrideIn added in v0.1.1093

func ImageOverrideIn(s settings.Settings, pid, model string) (bool, bool)

ImageOverrideIn is ImageOverride from settings s already read: a list of many models reads them once, not for each (lml on Discord, Windows).

func ImportFromApps added in v0.1.25

func ImportFromApps(picks []AppPick) (added []string, err error)

ImportFromApps adds what the user picked, reading the sources again so keys never pass through the window. It answers the names added. The providers it adds alike but for their keys — an app that keeps an entry a key, as CC Switch does, gives hundreds — are one provider with those keys (see foldAdded).

func InUseLogin added in v0.1.504

func InUseLogin(agent string) string

InUseLogin is the account of an agent's the gateway goes to first: the one the agent is signed in to, unless it is paused or has used its allowance up — then the next one on that still has room — else the first other one on; "" when the agent has none. Kept signed in to one of the user's choosing, it is the first in the order that is in use.

func InputsOf

func InputsOf(m catalog.Model) []string

InputsOf is what a model takes: what its source listed, else, when its source said nothing of its input, what models.dev says the model takes wherever it is served, as images are read (catalog.SeesImages). A Gemini model a list gave bare (Vertex AI's, a relay's) was said to take text and image alone, never its audio (Parlevent_ on X). The list may be shared: the caller only reads it.

func InstallPluginCLI added in v0.1.1241

func InstallPluginCLI(ctx context.Context, id string) error

InstallPluginCLI installs the CLI PluginCLIMissing names, with its vendor's installer or, where that can't run, as it installs it.

func InstructionsAfterInput

func InstructionsAfterInput(model string) bool

InstructionsAfterInput says model is one OpenAI reads a request's top-level instructions for after its input, not before it: GPT-6.2 and later ("Starting with GPT-6.2, models append top-level instructions after input and bill those tokens at the uncached input rate", developers.openai.com/api/docs/guides/prompt-caching). Sent so, they end the prompt the cache keeps, and from the second turn on what is cached ends where the last turn's input did: on a ChatGPT account gpt-6.2-sol had 1,920 of 8,271 input tokens cached on a third turn with Codex's instructions on top, 6,016 with them first in the input (gpt-6-sol cached 5,632 of 6,843 with them on top). Such a model is sent its instructions as a developer message first in the input, which is where Codex puts its own on every model.

func Intents added in v0.1.95

func Intents(rules []Rule, q RuleRequest) []string

Intents are the intents the classifier is to choose among for q: those of the rules that match it but for their intent, up to the first that matches outright (a rule after it could never be the first to match). None when no rule before that one has an intent — the classifier then isn't asked. Each is given once, as the first rule has it.

func IsDecider added in v0.1.142

func IsDecider(id string) bool

IsDecider reports whether a classifier ("provider/model") is a decision provider's model.

func IsFastPick added in v0.1.1077

func IsFastPick(agent, id string) bool

IsFastPick reports whether agent's requests for the entry id ("<provider>/<model>") are sent fast.

func IsGroupRef added in v0.1.1294

func IsGroupRef(ref string) bool

IsGroupRef reports whether ref names a routing group: group/<id>, or a found group's auto/<model>.

func IsOwn added in v0.1.3374

func IsOwn(pid, agent string) bool

IsOwn reports whether the provider pid is agent's own subscription.

func IsPattern added in v0.1.826

func IsPattern(s string) bool

IsPattern reports whether a member as typed is a pattern rather than a model's id: a regular expression ("re:…"), a free rule ("free:…") or a glob with "*" in it. No vendor's model id has a "*" in it or starts with either prefix, so none can be taken for one.

func IsRemoteCard added in v0.1.1078

func IsRemoteCard(id string) bool

IsRemoteCard is whether id is a card this magpie has from a remote magpie, or the card standing for the remote itself.

func IsUltraPick added in v0.1.1270

func IsUltraPick(agent, id string) bool

IsUltraPick reports whether agent's requests for the entry id are sent as Ultrafast where the account offers it.

func KeepAccountsListed added in v0.1.1669

func KeepAccountsListed(ctx context.Context)

KeepAccountsListed fetches each signed-in account's list again once it is accountListAge old, in the magpie serving the gateway.

func KeepClaudeWindowsWarm added in v0.1.223

func KeepClaudeWindowsWarm(ctx context.Context, send func(ctx context.Context, configDir string) error)

KeepClaudeWindowsWarm starts the Claude accounts' windows as they reset, while settings say to, each with one request send makes.

func KeepCodexAppOnItsProvider added in v0.1.1704

func KeepCodexAppOnItsProvider(ctx context.Context, busy func() (int, time.Time))

KeepCodexAppOnItsProvider runs codexAppStep every codexAppEvery till ctx ends. busy says how many of Codex's requests are in flight through magpie and when the last ended.

A Codex request this magpie didn't serve is one the magpie before it may still be serving: a magpie that hands the gateway over (an update) lets the requests in flight finish in the old one, and the new one saw none of them. Its start counts as a Codex request ended then, so a reply streaming from the old one isn't cut short by the new one's first look.

func KeepCodexWindowsWarm added in v0.1.182

func KeepCodexWindowsWarm(ctx context.Context)

KeepCodexWindowsWarm starts the ChatGPT accounts' windows as they reset, while settings say to, two minutes after it starts and every codexWarmEvery after that, until ctx ends.

func KeepKeyRatesRead

func KeepKeyRatesRead(ctx context.Context)

KeepKeyRatesRead reads the group rate of every key whose provider has a top-up rate, when the magpie serving the gateway starts and again as each is due (every six hours, half an hour after a failed read), until ctx ends.

func KeepListsFresh added in v0.1.1234

func KeepListsFresh(ctx context.Context)

KeepListsFresh fetches the list of each provider of the user's own that has a RefreshEvery once its list is that old, run by the magpie serving the gateway (`magpie serve`, the app).

func KeepLoginsAlive added in v0.1.75

func KeepLoginsAlive(ctx context.Context)

KeepLoginsAlive renews a saved sign-in that is due, one a look, a minute after it starts and every hour after that — a computer that slept through a day catches up within the hour of waking — until ctx ends.

func KeepMiniMaxCheckedIn added in v0.1.910

func KeepMiniMaxCheckedIn(ctx context.Context)

KeepMiniMaxCheckedIn checks the MiniMax Code accounts in each day while settings say to, as KeepTraeCheckedIn does Trae CN's.

func KeepOnAnAccountWithRoom added in v0.1.402

func KeepOnAnAccountWithRoom(ctx context.Context)

KeepOnAnAccountWithRoom runs SwitchWhenSpent for Codex and Claude Code a minute after it starts and every loginSwitchEvery after that (Codex's codexLookEvery), until ctx ends, and keeps Claude Code's proxy that of its account (SyncClaudeProxyEnv). Between those looks Claude's sign-in is looked at every claudeLookEvery when claudeLookDue: Claude Code asks Anthropic itself, and an account burnt fast was out minutes before the next look (#4443).

func KeepPartnersFresh added in v0.1.1343

func KeepPartnersFresh(ctx context.Context)

KeepPartnersFresh fetches the partner list when the magpie serving the gateway starts, and again whenever it is due (every hour, ten minutes after a failed fetch), whether or not a page asks for it, so a partner added reaches an app left running within the hour, and the list kept on disk is fresh for the next start.

func KeepPluginsCheckedIn added in v0.1.1085

func KeepPluginsCheckedIn(ctx context.Context)

KeepPluginsCheckedIn checks the plugins' accounts in each day, each provider's while settings say to, as KeepWorkBuddyCheckedIn does WorkBuddy's.

func KeepPluginsListed added in v0.1.1167

func KeepPluginsListed(ctx context.Context)

KeepPluginsListed lists the plugins' models again every relistEvery, in the magpie serving the gateway, and drops the picks of models gone from them.

func KeepPluginsSignedIn added in v0.1.2858

func KeepPluginsSignedIn(ctx context.Context)

KeepPluginsSignedIn renews the plugins' sign-ins as they come due, in the magpie serving the gateway, while nothing uses them (#5080).

func KeepQoderCheckedIn added in v0.1.1077

func KeepQoderCheckedIn(ctx context.Context)

KeepQoderCheckedIn checks the Qoder accounts in each day while settings say to, as KeepTraeCheckedIn does Trae CN's.

func KeepRemoteListsFollowed added in v0.1.3172

func KeepRemoteListsFollowed(ctx context.Context)

KeepRemoteListsFollowed follows the list of each Remote magpie the user has, while ctx lasts: run by the magpie serving the gateway, beside KeepListsFresh.

func KeepRemotesUpdated added in v0.1.3285

func KeepRemotesUpdated(ctx context.Context, version string)

KeepRemotesUpdated runs UpdateRemotes a little after start (this magpie may just have updated) and every hour after, until ctx ends.

func KeepResetsFromRunningOut added in v0.1.701

func KeepResetsFromRunningOut(ctx context.Context)

KeepResetsFromRunningOut spends the Codex resets about to run out unused (SpendExpiringCodexResets), three minutes after it starts and then as soon as a look is due (wake: a lead's start, a retry), every resetExpiryClose at most, until ctx ends.

func KeepRetiringMoved added in v0.1.506

func KeepRetiringMoved(ctx context.Context)

KeepRetiringMoved moves the built-ins being retired, and hands over those whose plugin the user installed (HandOver), run by the magpie serving the gateway (one magpie, never two at once): a little after it starts, then every hour, so a failed move is tried again once retryWait has gone; a retired built-in's failed move brings the next run forward to when it is due. It also keeps each moved built-in's plugin up to date.

func KeepTraeCheckedIn added in v0.1.784

func KeepTraeCheckedIn(ctx context.Context)

KeepTraeCheckedIn checks the Trae CN accounts in each day while settings say to, as KeepWorkBuddyCheckedIn does WorkBuddy's.

func KeepWorkBuddyCheckedIn added in v0.1.356

func KeepWorkBuddyCheckedIn(ctx context.Context)

KeepWorkBuddyCheckedIn checks the WorkBuddy accounts in each day while settings say to: two minutes after it starts, every wbCheckinEvery after that, and as the Beijing day turns, until ctx ends.

func KeepsCredentials added in v0.1.3166

func KeepsCredentials(next *http.Request, via []*http.Request) error

KeepsCredentials is the CheckRedirect of a client that sends a vendor's credential: same-origin redirects are followed, at most 10 as Go's default, and any other is given back as the answer (http.ErrUseLastResponse).

func KeyAllowanceID added in v0.1.1086

func KeyAllowanceID(p Provider) string

KeyAllowanceID is what OnRenewed's hooks are told, as the user of agent "", of a key whose own windows magpie reads; empty for any other.

func KeyID added in v0.1.14

func KeyID(key string) string

KeyID is the fingerprint a key is named by, in lists and in the gateway.

func KeyListed added in v0.1.2955

func KeyListed(id, ref string) []string

KeyListed is the models the provider id's last fetched list marks its key ref (KeyID) as seeing, by the ids the provider lists them by, for the editor's Select all available (young02036 on Discord); nil when no list marks that key (one key on, a fetch not asked per key), which is unknown, not none. A plugin's account is listed by the models its plugin says that account has (young02036: a ZCode account with only GLM-5.3-Flash got its other account's models ticked).

func KeyOf added in v0.1.1164

func KeyOf(id, keyRef string) (string, error)

KeyOf is one of a provider's keys, by its id (keyID), for the editor to show or copy: a provider of several keys has a row for each, and each row copies its own (#1480).

func KeyPriceRateOK

func KeyPriceRateOK(r float64) string

KeyPriceRateOK says what is wrong with a key's own price rate, "" when nothing: above 0 up to 1000, at most three decimals. None is no value: the key bills at the provider's rate.

func KeyRatesKey

func KeyRatesKey() string

KeyRatesKey names the group rates read so far by what they are, for a cache of costs to be built again when one changes: a read that found the same rates leaves it as it was.

func Keyed added in v0.1.3166

func Keyed(c *http.Client) *http.Client

Keyed is c with KeepsCredentials after c's own CheckRedirect, for a request that carries a vendor's credential. c is left as it is.

func KeysHeld added in v0.1.2674

func KeysHeld(ids ...string) map[string]map[string]bool

KeysHeld is the keys, on or off, each provider of ids (every provider when none is named) has now, by provider id and KeyID: what PrefillNewKeys tells the keys added since by.

func KeysListed added in v0.1.1265

func KeysListed() int64

KeysListed is how many times a provider's keys on have been listed in this process: a test counts them, not the time a page or request took, to say they are listed once and not once a key (@NetRozee on X).

func KiloClient added in v0.1.635

func KiloClient(h http.Header, key, session string)

KiloClient makes a request to the Kilo Gateway carry what the Kilo CLI sends it (Kilo-Org/kilocode packages/opencode/src/session/llm/request.ts and kilocode/const.ts, packages/kilo-gateway/src/headers.ts): Kilo Code's attribution and User-Agent, the editor it runs in, its mode, and the session as the task, which the gateway keys its prompt cache on. session names the conversation, made into one of the CLI's ids (ses_…) as for OpenCode; none leaves the session headers out. A provider with no key sends no Authorization at all: the gateway answers a free model to a caller with no credential as anonymous (by IP, 200 requests an hour), and refuses a bearer it can't verify with 401 (Kilo-Org/cloud web-shared/src/lib/tokens.ts, ai-gateway/handlers/llm-proxy.ts). Kilo's clients still send "Bearer anonymous", which the gateway reads as none only until no released client sends it, so it is not copied here.

func KimiCodeSearch added in v0.1.779

func KimiCodeSearch(p Provider) string

KimiCodeSearch is where a Kimi Code plan's key searches the web, as kimi-cli's SearchWeb does (auth/platforms.py: the plan's search_url is its base_url, /coding/v1, with /search), "" for a provider that isn't a Kimi Code plan with a key.

func KindGroup added in v0.1.3040

func KindGroup(kind, ref string, serves func(p Provider, model string) bool) (Group, []Member, bool)

KindGroup is the group of the API kind's model ref names, with its members ready now: each provider has serves say serves the model under exactly that id, in the order the providers were added, none switched off and none the user disabled the model on (#1867). ref is the group's id ("group/auto-embedding:embed-1") or the model's own ("embed-1", which the route asks for: GroupFor by route). ok is false when no provider serves it; a group of one member is the model of that one.

func KindGroupID added in v0.1.3040

func KindGroupID(kind, model string) string

KindGroupID is the id of the group of the API kind's model: its exact id, as the providers list it.

func KnownFace added in v0.1.1234

func KnownFace(id string) (name, icon string)

KnownFace is the name and icon magpie knows the provider id by while it isn't set up: a built-in subscription signed out of, or with account discovery off ("claude" is Claude Code), or a preset's removed since. The usage log keeps the id of every provider a call went to, and the Usage page names those by this rather than by the bare id (@ByronVon1 on X: "claude" in the Provider filter). "" for an id magpie doesn't know, such as a custom provider removed since.

func Labels added in v0.1.516

func Labels(es []Entry) []string

Labels are how an agent's list names each of es, in order: as Label, or, when the user wants names plain (settings' PlainNames, #335), by the name alone — but for two or more models the list would call the same, which keep their provider's after it to tell them apart, and a routing group named as anything else in the list (the group found for a model, with that model left in it), which keeps "· routing group" while the model it is named as stays plain. With their own names plain (PlainOwnNames, #92), a name the user gave — a model's, or a routing group's they made (#868: "· routing group" was what an agent's narrow menu cut off) — is that name just as they wrote it, but for two the list would call the same, and the rest keep Label's.

func LabelsFor

func LabelsFor(agent string, es []Entry) []string

LabelsFor is Labels as the agent of that id's lists name es: by its own Provider in model names (settings.AgentSuffix, KillTry27355 on X: one agent's narrow menu wants names plain while another's wants the provider), else by the one for every agent. "" is every agent's.

func LastServed added in v0.1.664

func LastServed() map[string]time.Time

LastServed is when each ServedID last answered: what this process noted and what the file holds, whichever gateway wrote it.

func LearnAuthHeader added in v0.1.1211

func LearnAuthHeader(id, only string)

LearnAuthHeader keeps only as the header provider id's key goes in, when it sends both still: one the user picked is theirs.

func LearnZhipuCoding added in v0.1.1224

func LearnZhipuCoding(p Provider, from string)

LearnZhipuCoding moves provider p, whose key the pay-as-you-go endpoint from refused and the GLM Coding Plan's served, to the plan's endpoints: its OpenAI URL, and the plan's Responses URL when it has none (the zhipu and zai presets' Coding Plan region). Only a provider with that one key still at from is moved: one with other keys may hold pay-as-you-go keys too, and one the user has moved since is theirs. Each of its requests is then asked again at the plan's endpoint as this one was.

func LetGo added in v0.1.1400

func LetGo(req *http.Request)

LetGo lets go of the bytes SetBody gave req once it was answered and nothing will ask it again; a body SetBody didn't give is left as it is.

func ListHeader added in v0.1.1030

func ListHeader(name string) bool

ListHeader is a header whose value is a comma-separated list the request has its own of, which a provider's header of the same name adds to: anthropic-beta, the betas an agent asks on each request.

func ListedWindow added in v0.1.816

func ListedWindow(m catalog.Model) int

ListedWindow is the window a provider's model takes before the user says one: its vendor's list's, else the one models.dev gives a model of its id. A vendor models.dev doesn't list (a custom provider, a proxy, a plugin whose list says none, as Cline's) serves models it knows from others, under the vendor's prefix too: cline-free/mimo-v2.6-flash is mimo-v2.6-flash. A window the vendor lists under catalog.LeastWindow (512, H20 on Discord) is no window: models.dev's answers, else the one the id's name says ("qwen-3.8-27b-128k", catalog.NameWindow), else none, and the agent's default.

func ListsRead added in v0.1.1265

func ListsRead() int64

ListsRead is how many times a provider's saved lists have been asked for whole in this process: a test counts them to say a request reads them once, not once a key (@NetRozee on X).

func LocalHost added in v0.1.2244

func LocalHost(host string) bool

LocalHost says host is on this machine or the local network: localhost, a .local name, a loopback, private or link-local IP, or a name every address of which is one (netproxy.LocalName, looked up now and kept a minute; one that doesn't resolve isn't). Only the editor's caution asks it (/api/local-hosts), never a request.

func LocalZone added in v0.1.1524

func LocalZone() string

LocalZone is the IANA name of this computer's time zone, as a window set here records it: $TZ when it names one, else what /etc/localtime links to (macOS, Linux). "" when neither says (Windows, a TZ of "UTC+8" that names no zone): the window is then on the clock of whichever computer runs the gateway, as before.

func LoginCheckins added in v0.1.2935

func LoginCheckins(agent string, m map[string]SubscriptionQuota) map[string]SubscriptionQuota

LoginCheckins is m, agent's accounts' readings by user (LoginUsage), with each account's daily check-in as its Usage card has it (WithCheckins), for the provider editor's account rows (xwoffice_91592).

func LoginID added in v0.1.1076

func LoginID(agent, user string) string

LoginID is the stable id of an agent's account known by its name (#905): the login's, kept through renames, or one made of the name for an account whose logins haven't been written since — and for an agent that keeps its accounts elsewhere, made of the name always.

func LoginUsage added in v0.1.14

func LoginUsage(ctx context.Context, agent string) map[string]SubscriptionQuota

LoginUsage is the allowance used by each of an agent's accounts, by user. What was read less than a minute ago, here or for the Usage page, comes from the cache; the rest is asked for at once, as long as ctx allows.

func LoginUsageShown

func LoginUsageShown(ctx context.Context, agent string) map[string]SubscriptionQuota

LoginUsageShown is LoginUsage for the account lists (the editor's cards, `magpie accounts`): a provider magpie leaves alone (switched off or removed) makes no request, and its accounts show what was last known of them, as leftAlone promises, not an empty card ("No allowance reported", Kunlin03 on X: a Claude Pro account with the Claude Code switch off). LoginUsage itself stays empty for it: warm-ups and switching read it and must not take a kept reading for a fresh one.

func LoginUsageVia added in v0.1.778

func LoginUsageVia(f func(ctx context.Context, agent string) map[string]SubscriptionQuota)

LoginUsageVia has tests stand in for LoginUsage's readings. It returns once no reading is still running through the one it replaces, and none starts through it after.

func MakerPrice added in v0.1.411

func MakerPrice(model string) (catalog.Price, bool)

MakerPrice is a model's list price as the first vendor among the presets that makes the models it serves lists it; for a call whose provider has gone since.

func MantleBase added in v0.1.1270

func MantleBase(base, model string, other bool) string

MantleBase is the base a request for model goes to on Mantle's chat completions or Responses API, given a Mantle provider's base for it (IsBedrockMantle): one ending /v1 or /openai/v1 goes at whichever of the two serves the model, or at the other when other is set (the model was refused at the first, so the gateway learned its prefix). A base ending otherwise, one the user typed, is given back as it is.

func MarketIcon added in v0.1.2179

func MarketIcon(said string) string

MarketIcon is an icon the plugin market (registry.json) gives, as the page can show it. A bundled icon's name is given as it is. A picture (an https URL or a data:image URI) is checked, fetched and kept as a plugin's own picture is, and is "" until it is in: the page never loads a remote URL itself, and an icon("https://…") would look for a bundled file of that name.

func MarketPicture added in v0.1.2179

func MarketPicture(said string) bool

MarketPicture is whether a market icon is a picture to fetch or decode (anything with a scheme or a path in it) rather than a bundled icon's name.

func MarkupText added in v0.1.1848

func MarkupText(b []byte) string

MarkupText is the words markup holds, as plain words: scripts, styles and comments out, then every tag, entities read, whitespace folded, cut to 300 runes. "" when it holds none.

func Mask

func Mask(s string) string

Mask hides all but the ends of a secret.

func MaskSearchKey added in v0.1.1231

func MaskSearchKey(k string) string

MaskSearchKey is one search API key as shown: as Mask, but a Tavily key keeps its whole "tvly-" tag (tvly-…abcd), which says what it is and nothing secret of it.

func MatchRule added in v0.1.94

func MatchRule(rules []Rule, q RuleRequest) int

MatchRule is the first of rules the request matches, -1 for none.

func MemberAccount

func MemberAccount(id string) (member, account string)

MemberAccount splits a group's member into the member without its account and the account it names ("" for none): "a/m:high#x" is a/m:high on x. A group in the group ("group/<id>") is split too, for SaveGroup to refuse: its members name their own.

func MemberEffort added in v0.1.379

func MemberEffort(id string) (model, effort string)

MemberEffort splits a group's member into the model it names and the effort fixed on it ("" for none): "a/m:high" is a/m at high, unless a has a model "m:high" of its own. A group in the group ("group/<id>") takes none; one typed with one comes back split, for SaveGroup to refuse.

func MemberFast added in v0.1.577

func MemberFast(id string) (member string, fast bool)

MemberFast splits a member typed with ":fast" after it into the member and true: "a/m:high:fast" is a/m:high, fast, unless a has a model "m:high:fast" of its own.

func MemberGroups added in v0.1.572

func MemberGroups() map[string][]string

MemberGroups are the routing groups each model is in, as "group/<id>", by the model's "provider/model" id; a member fixed at an effort counts as its model, and a group removed is none. A provider kept for routing groups (Provider.Unlisted) reaches agents through these alone: a model of it in none of them is used by nothing. Held while a request holds the catalog, so it is shared, only for reading: the providers' page asked for it once for each provider, 11.6 MB of what twenty polls allocated.

func MemberLevels added in v0.1.1883

func MemberLevels(effort string) (fixed string, levels []string)

MemberLevels splits the effort MemberEffort gives into the one a member is fixed at and the several the agent picks among (nil for one or none): "high" is fixed at high, "low+high" follows the agent among low and high.

func MergeDeleted added in v0.1.1807

func MergeDeleted(id, into string) error

MergeDeleted has the calls of the deleted provider the Usage page lists under id listed and counted as into's, a provider there is now, or, with into "", as its own again (CyberCaius on Discord, who had renamed a provider onto a deleted one's id to see their calls together). Nothing in the usage log is rewritten: the merge is kept on its Deleted record and read through Renames, its calls priced as they were. A provider added later under the deleted one's id is not merged.

func MergeList added in v0.1.1030

func MergeList(h http.Header, name, add string)

MergeList writes name in h as the items h has under it, in any case, followed by those of add: comma-separated, each once, empty ones left out, under name as written.

func MergeName added in v0.1.673

func MergeName(p Provider, model string) string

MergeName is the name the groups magpie finds merge p's model by, when the user said nothing of it: its id as vendors agree on it (sameModel), with the maker's name its vendor left off put back (unprefixed), without a context window it is offered at (mergeName).

func MergeQuotaHistory added in v0.1.722

func MergeQuotaHistory(data []byte, now time.Time) error

MergeQuotaHistory merges another computer's history (as QuotaHistoryData gave it there) into this one's.

func MergeSignIns added in v0.1.2835

func MergeSignIns(local, remote *SignIns, prev map[string]string) (*SignIns, SignInPlan, map[string]string)

MergeSignIns merges this computer's sign-ins with the server's. prev is the sign-ins (id → hash) the last sync left on the server and here, nil for none known. Of an account on both sides, the one renewed later goes on (when neither says, the side that changed since prev); one gone from a side since prev was removed there, and goes from the other, unless it changed there since. It gives what goes up, what to do here, and what goes up's hashes.

func Mirror added in v0.1.76

func Mirror(ps []Provider, gs []Group) error

Mirror makes the providers and groups exactly these, as sync brings them from another computer: one not among them goes, one that came without keys keeps the keys it has here, and an access key or balance token it came without is kept too (KeepSecrets). Which account an agent is kept signed in to (KeepLogin, KeepLoginAs, SwitchOnly), whether its app is restarted to follow (RestartApp), and whether a Remote magpie that is this magpie is used anyway (KeepSelf), is this computer's own: one person signs in to a personal account at home and a work account at the office, and sync set each computer to the other's every day. A provider kept on this computer (ThisDevice) is neither replaced nor removed by them.

func MirrorGroupOrder added in v0.1.843

func MirrorGroupOrder(order []string) error

MirrorGroupOrder makes the groups' order the one another computer has, as sync brings it, the way MirrorOrder does the providers': its ids first, then the ones named here alone. None leaves the order here as it is.

func MirrorOrder added in v0.1.638

func MirrorOrder(order []string) error

MirrorOrder makes the providers' order the one another computer has, as sync brings it: its ids first, as it has them, then the ones named here alone (a signed-in account only this computer has), in the order they have here. None, as from a magpie before the order was synced or one never arranged, leaves the order here as it is.

func MirrorSearchAPIs added in v0.1.587

func MirrorSearchAPIs(as []SearchAPI) error

MirrorSearchAPIs makes the search APIs exactly these, as sync brings them; one that came without a key keeps the key it has here.

func MixSearchAPIs added in v0.1.3199

func MixSearchAPIs(vendors []string) error

MixSearchAPIs marks the vendors' search APIs to be asked together (SearchAPI.Mix, #2845), and every other one not: two or more, each set up and named once. None puts every one back to being asked in order.

func ModelDisabled added in v0.1.1219

func ModelDisabled(pid, model string) (string, bool)

ModelDisabled reports whether the user disabled pid's model, and the pattern that did. A list nobody knows (DisabledUnknown) disables none here: the gateway asks DisabledUnknown itself.

func ModelHeaders added in v0.1.3300

func ModelHeaders(pid, model string) map[string]string

ModelHeaders are the headers the user gave provider pid's model.

func ModelListsHeld added in v0.1.1209

func ModelListsHeld(ls map[string]ModelList) bool

ModelListsHeld reports whether every list in ls is the one its agent has now: SetModelLists would change none of them.

func ModelLoads added in v0.1.2758

func ModelLoads(now time.Time) map[string]float64

ModelLoads is how busy each model is that a plugin reported a load for in the last plugin.LoadFresh, by the ref an agent's model picker gives it ("provider/model", lowercased), the figure the provider editor shows by the model (plugin.ModelLoad): a model the user lists by another id (SetModelID) under that id, one listed as its own under its own. A model@size the plugin reported only by its model is left for the reader to look up by the model (axelburks on Discord: the Agents page shows it too). Nothing reported, nothing more is read.

func ModelName added in v0.1.137

func ModelName(pid, model string) (string, bool)

ModelName is the name the user gave a provider's model, if any.

func ModelOff added in v0.1.1130

func ModelOff(agent string) func(id string) bool

ModelOff reports whether agent's lists leave an entry out by the picks made one model at a time: every one not picked, when it is shown only the models picked for it, else the ones taken out (HiddenModels).

func ModelOrder added in v0.1.952

func ModelOrder(agent string) []string

ModelOrder is the order the user put agent's models in (OrderedModels), by entry id, a found group by the id it is listed by now (PublicRef); none when they never did.

func ModelSystemPrompt

func ModelSystemPrompt(pid, model string) string

ModelSystemPrompt is the system prompt the user gave provider pid's model, "" for none. It reads the held settings, as it is asked on every try of a request.

func ModelTier

func ModelTier(pid, model string) string

ModelTier is the tier the user gave provider pid's model, "" for none. It reads the held settings, as it is asked on every request.

func Movable added in v0.1.506

func Movable(id string) bool

Movable is whether the built-in id has a plugin it can move to.

func MovableIDs added in v0.1.628

func MovableIDs() []string

MovableIDs are the built-ins that have a plugin to move to, by id: the page marks them deprecated, moved or not.

func Move added in v0.1.506

func Move(ctx context.Context, id string) error

Move puts the built-in id's accounts onto its plugin (see above). An error leaves the built-in as it was.

func MovePackage added in v0.1.506

func MovePackage(id string) string

MovePackage is the plugin the built-in id moves to.

func MoveRetiring added in v0.1.506

func MoveRetiring(ctx context.Context) map[string]error

MoveRetiring moves the built-ins being retired that have accounts, at start-up: once, or again retryWait after one failed. One an older magpie moved back is moved again: there is no way back, as the built-in is going. One whose plugin the user removed waits for them to install it.

func Moved added in v0.1.506

func Moved(id string) bool

Moved is whether the built-in id's accounts are its plugin's now.

func MovedOnto added in v0.1.538

func MovedOnto(name string) []string

MovedOnto are the built-ins moved onto the plugin named (its spec or package name).

func NameDeleted added in v0.1.1807

func NameDeleted(id, name string) error

NameDeleted names the deleted provider the Usage page lists under id as the user wants it shown there; "" shows it by its own name again.

func NamedGroups added in v0.1.1248

func NamedGroups() (int, error)

NamedGroups counts the user's own groups in providers.json, served or not; a file that can't be read is an error, not none.

func NativeEndpoints added in v0.1.1440

func NativeEndpoints(e Entry) []string

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. A routing group's are GroupEndpoints, which need its members; none here. None either for a model every request to is translated anyway (a subscription served through its agent's own API).

func NextInOrder added in v0.1.2376

func NextInOrder(ctx context.Context, agent string) (to string, over bool, err error)

NextInOrder is the account `magpie accounts switch <agent> next` signs agent in to: of its other accounts the agent can be signed in to, taken in their order from the one after the account it is on, the first whose allowance is known and has room; when none has, the one with the most room left (roomLeft), and over says so. A saved Claude account not read yet is read then, as NextLogin's spares are.

An account off in magpie is taken too, as switching to it by name or from the accounts list is: on/off is whether the gateway's requests go to it, not whether the agent may be signed in to it. An account the agent signed itself in to (Claude Code's /login, codex login) starts off, and next passed over it (StringKe, #4532). The automatic switch (NextLogin) still takes only accounts that are on.

func NextLogin added in v0.1.402

func NextLogin(ctx context.Context, agent string) (from, to string, back, ok bool)

NextLogin is the account agent should be signed in to instead of the one it is on: the account magpie moved it off, once that has room again (back); else, when the one it is on is spent, the first of its other accounts that are on in magpie, in the order they were saved, whose allowance is known and not spent, or, when every one is past its line too, the one with the most room left (roomLeft). A saved Claude account not read yet is read then (readSpare). ok is false when the agent should stay.

func NextResetAt added in v0.1.1230

func NextResetAt(s string, now time.Time) (time.Time, bool)

NextResetAt is the first time after now that the time of day s names comes round; ok is false when s names none.

func NotSignedIn added in v0.1.1225

func NotSignedIn(ps []Provider) []string

NotSignedIn is the subscriptions among ps (as a backup or a sync brings them: their model picks and settings alone) that no account here is signed in to: they are listed once one is, and are to be signed in to on this computer. A subscription the user removed from magpie is not one.

func NoteClaudeLimits added in v0.1.199

func NoteClaudeLimits(user string, ls []ClaudeLimit)

NoteClaudeLimits keeps what Claude Code said of user's allowance as it answered, in place of the windows of the same names last read, and has routing weigh the account by it. An answer tells only some windows (a rate_limit_event often names five_hour alone): the others stand as last read, after a restart as kept on disk (quotas.json), so the week isn't lost to an answer that didn't name it (ifccod7391564 on X).

func NoteClaudeSignInFailure added in v0.1.788

func NoteClaudeSignInFailure(user, version, message string)

NoteClaudeSignInFailure keeps a run's refusal on the saved Claude account user, when the run started on the credential the account still has (version): one started on an older credential says nothing of this one. The run's own error stays in the request's trace.

func NoteCodexCredits

func NoteCodexCredits(agent, user string, on bool)

NoteCodexCredits keeps what a reply said of the credits of agent's account user (agent as its usage is read): whether it goes on past its allowance on them (CodexGoesOnCredits). ChatGPT says it on every reply, the 429 that turns a turn away as out of its allowance too, and Codex reads it there (codex-api's parse_credits_snapshot) — /wham/usage alone, read once a minute or failing, left an account that had bought credits benched as used up until its window renewed, days on, where Codex by itself went on on them (@123xtv03k on X). Turned on, those OnCredits asked are told, once the account is let spend them (CodexCredits).

func NoteCodexLimits added in v0.1.1118

func NoteCodexLimits(agent, user string, heard []CodexLimit)

NoteCodexLimits keeps what a reply said of agent's account user (agent as its usage is read, Account.UsageAgent) in place of the windows of the same span last read, for routing (Allowances) and the Usage page alike. An account not read well yet is known from what the reply told, when it told the week, until a reading tells the whole of it: a reply names only the windows it counts.

func NoteCodexSignInGoneForTest added in v0.1.2096

func NoteCodexSignInGoneForTest(dir, refresh string) (record string)

NoteCodexSignInGoneForTest records refresh as refused for good in dir, as a refresh OpenAI refused would, and says where the record is.

func NoteExpiredSignIn added in v0.1.1335

func NoteExpiredSignIn(ctx context.Context, a *Account, req *http.Request)

NoteExpiredSignIn renews the ChatGPT sign-in of a, whose request req the backend answered 401 token expired while the token had time left by its exp, so the next request goes with a new one. The request itself isn't sent again here; the routing loop passes over it as an auth failure. A refresh refused marks a saved account lapsed (savedRefreshFailed).

func NoteReordered

func NoteReordered(id string)

NoteReordered records that the user just changed which of provider id's accounts goes first (a drag in the pool, Make first, the CLI), so a conversation it last answered before that is routed anew at its next turn (the gateway's affine) instead of staying with the account the user moved down.

func NoteRevokedSignIn added in v0.1.1213

func NoteRevokedSignIn(ctx context.Context, a *Account, req *http.Request)

NoteRevokedSignIn keeps that the vendor revoked the credential req went to account a with. A saved ChatGPT account is refreshed first, as Codex does on a 401: a refresh that goes through is a new sign-in, and the account isn't marked.

func NoteServed added in v0.1.664

func NoteServed(p Provider, at time.Time)

NoteServed records that p just answered a request, at at. The file follows within servedFlushAfter (FlushServed): this process's LastServed has it at once.

func NoticePartners added in v0.1.1126

func NoticePartners(ids ...string)

NoticePartners keeps that the user has been shown the partners ids, so they are no longer new. It is kept whether or not they are counted.

func ObjectRoot added in v0.1.718

func ObjectRoot(ps map[string]any) bool

ObjectRoot makes a tool's input schema a plain object at the root, with no anyOf, oneOf or allOf there: Grok's backend wants one, and so do Anthropic's models behind Factory ("input_schema does not support oneOf, allOf, or anyOf at the top level", #646). allOf's branches are all merged, properties and required alike. Of anyOf's and oneOf's object branches the properties are merged, a field each of them requires stays required, and the other branches go. A branch that is a union itself, as zod writes a discriminated union inside another (Codex desktop's automation_update, #1271), is folded the same way first, so its fields are kept; a field the branches give different schemas takes any of them. It reports whether it changed anything.

func OffSpread added in v0.1.3374

func OffSpread(agent, id string) []string

OffSpread is the providers' ids ("provider/model") serving a bare model id that a request of agent's goes to none of, while found groups are off: several providers serve it, none of them the agent's own subscription, and the agent has one in magpie. Off, magpie picks none of them for the agent (freefcw on X); the request names one. nil when found groups are on, the id isn't bare or names a group of the user's, one provider serves it, or the agent has no subscription of its own here.

func OffersUltra added in v0.1.733

func OffersUltra(model string) bool

OffersUltra reports whether Codex offers its Ultra on the model, by the id a vendor serves it under: openai/gpt-6.1-sol on a relay, a dated snapshot, and a relay's rename the catalog reads as one of them (codex-gpt-6.1-sol, "[A]gpt-6.1-sol", one the user said is gpt-6.1-sol), whose levels are that model's already (provider.borrowedEfforts) and stopped at max.

func OnAccountIDs added in v0.1.399

func OnAccountIDs() []string

OnAccountIDs are the user's own providers saved on a subscription's id, which hide that subscription once it is signed in (All lists the one saved): made before the id was a subscription's, as a WorkBuddy key was before WorkBuddy's plan was one. MoveOffAccountIDs moves them.

func OnCredits

func OnCredits(f func(agent, user string))

OnCredits asks f to be told of a ChatGPT account found to go on past its allowance on credits it was not known to hold (NoteCodexCredits, or a reading of its usage), and let spend them: what held it as out of its allowance holds it no more.

func OnPlugins added in v0.1.506

func OnPlugins() []string

OnPlugins are the built-ins moved onto their plugins.

func OnRenewed added in v0.1.289

func OnRenewed(f func(agent, user string))

OnRenewed has f told when an account's usage windows were started again (a Codex reset spent), or a reading of them (Allowances) finds one it was full in full no more, so what sat out waiting for them can come back; agent is the one its usage is read under (Account.UsageAgent). And, as agent "" and the key's KeyAllowanceID, when a reading of a key's own windows finds one it was full in full no more: its limit raised in its panel, or its usage reset.

func OnServedMoved added in v0.1.1169

func OnServedMoved(f func())

OnServedMoved sets what is told when a provider's requests are answered by another of its accounts or keys than the one that answered before, or when the user signs an agent in to another account (SwitchLogin): the menu bar following the account in use reads it again then, rather than minutes later (#1516). It is called after NoteServed lets go of its lock and must not block; nil tells nothing.

func OnStarted added in v0.1.2497

func OnStarted(f func(agent, user string))

OnStarted has f told as OnRenewed is, and by the same tellings, but only when a window stands started again in fact: a reading finding one it was full in full no more with its reset gone by, or standing a new, later cycle, or a reset spent on them. What a vendor itself gave the time of waits for that, not for a reading that merely finds its window less than full while the vendor's own word stands (#2718).

func OnSubscriptionUsage added in v0.1.247

func OnSubscriptionUsage(f func())

OnSubscriptionUsage sets what is told when a refresh has landed, for what shows a stale copy meanwhile (the menu bar's text) to read the new one; nil tells nothing. It is held atomically: a refresh runs in the background and may be under way while it is set (#1023).

func OnlyBare

func OnlyBare(shown []Entry, bares []Bare) (rows []int, ids []string)

OnlyBare is the list of shown with bare ids alone (BareOnly): each Bare of bares in the place of the first row it stands for, and the other rows it stands for left out. A Bare stands for the row a request for it reaches (a routing group found for the model, auto/glm-5.3, is that model's under another prefix), and for a provider's row of the same model when the request reaches that model: by that group, or by the provider first in the Providers order serving it by that id. A row it doesn't reach (a vendor/model id that names another provider of the user's, so a request for it goes there) and any other group's row stay, by their ids, so no model is lost from the list. Each row is its index in shown, and the bare id it is listed by, or "".

func OnlyPicks added in v0.1.1225

func OnlyPicks(p Provider) bool

OnlyPicks is whether p, as providers.json keeps it, is a subscription's model picks and settings alone, with no endpoint or key of its own: it is signed in to, never given a key.

func OpenAIHost added in v0.1.2155

func OpenAIHost(host string) bool

OpenAIHost is whether host is OpenAI's own API (api.openai.com), whose Chat Completions takes max_completion_tokens on every model; not Azure OpenAI (*.openai.azure.com) and not a relay.

func OpenAIUltra

func OpenAIUltra(model string) bool

OpenAIUltra reports whether OpenAI's API serves model, or a dated snapshot of it, at service_tier "ultrafast".

func OpenCodeClient added in v0.1.615

func OpenCodeClient(h http.Header, session, dir string)

OpenCodeClient makes a request to OpenCode's gateway (Zen or Go) carry what OpenCode 2.2.5 itself sends there, as captured on 2026-11-01 (testdata/opencode-2.2.5-chat.json): its User-Agent (OpenCodeUserAgent), trace headers b3 and traceparent (one trace a session, a new span each request), x-opencode-client cli, the project dir is in (OpenCodeProject), and the session in x-opencode-session, x-opencode-session-id, x-session-affinity and x-session-id, with Accept */*. 1.x's x-opencode-request and its project "global" (which 2.x sends only from a git repository with no remote and no commit) don't go: Zen's free tier answers 429 FreeUsageLimitError to 1.x's shape (#3491). Zen reads the session id as OpenCode lays one out (openCodeSession); session names the conversation, whose turns keep one session id, which Zen routes and caches by. dir is the folder the agent works in, the home folder when "". The order 2.2.5 sends them in isn't kept: Go's HTTP/1 writes headers sorted and HTTP/2 in no fixed order.

func OpenCodeEnvironment added in v0.1.2562

func OpenCodeEnvironment(dir string) string

OpenCodeEnvironment is OpenCode 2.2.5's environment block, word for word (packages/core/src/instructions/builtins.ts, as 2.2.5 sent it to Zen on 2026-11-01), said for dir, the home folder when "". Zen's free tier serves a request as OpenCode's own only when a system message carries one; without it a request gets a small allowance a day, then 429 FreeUsageLimitError ("Free models work in OpenCode"), and fixed text in it that only magpie would send (a directory "unknown") is a fingerprint.

func OpenCodeFreeURL added in v0.1.1243

func OpenCodeFreeURL(u string, proto Protocol) string

OpenCodeFreeURL is where a request on proto to Zen's free tier goes, given the URL it would go to at Zen (https://opencode.ai/zen/v1/…, or under /zen for Messages): where OpenCode 2 sends it, the base_url models.dev's v2 catalog (models.opencode.ai/experimental/v2.0/api.json, which 2.2.5 reads) gives every opencode model on 2026-11-01: /inference/openai/v1 for Chat and Responses, /inference/anthropic/v1 for Messages. 1.x's /inference/v1, which no OpenCode 2 request goes to, is moved there too. Gemini, on which Zen gives nothing free, goes under /inference as before. Any other URL, Go's (/zen/go) among them, is u.

func OpenCodeHasEnvironment added in v0.1.2562

func OpenCodeHasEnvironment(system string) bool

OpenCodeHasEnvironment says whether a system prompt already carries OpenCode's environment block, as OpenCode's own does.

func OpenCodeProject added in v0.1.2562

func OpenCodeProject(dir string) string

OpenCodeProject is OpenCode's project id for dir (packages/core/src/ project.ts), the home folder when "": in a git repository with a remote, sha1 of git-remote:host/path; anywhere else sha1 of directory: and the repository's root, or dir. A repository with no remote, which OpenCode names by its root commit, is named by its folder, as the zen-free plugin names it: the same shape, and no git to run.

func OpenCodeSession added in v0.1.1258

func OpenCodeSession(h http.Header, u string)

OpenCodeSession names a session on a request to OpenCode's gateway that names none yet: since September 2026 it answers every request without x-opencode-session 400 "Request is missing x-opencode-session and cannot be routed efficiently" (luci on Discord). A call that is no conversation's turn — a model list, a System One decision, a key check — gets a session of its own, as OpenCode gives its own stateless calls one (packages/core/src/generate.ts: "Gateways require session attribution even for a stateless call"). A turn's is named before this, by OpenCodeClient, and stays; so does one the user set on the provider. Sign calls it, so every signed request has it.

func OpenCodeURL added in v0.1.1258

func OpenCodeURL(u string) bool

OpenCodeURL says whether u is at OpenCode's gateway (Zen, Go or the inference API): opencode.ai or a name under it, whatever port the URL gives. What goes there is judged by the URL it goes to, not by the provider's first base (IsOpenCode), so a custom provider whose URL names a port, or one with only some of its endpoints there, is asked as OpenCode asks too.

func OpenCodeUserAgent added in v0.1.1224

func OpenCodeUserAgent() string

OpenCodeUserAgent is the User-Agent OpenCode sends on every protocol, opencode/${channel}/${version}/${name} (packages/core/src/app.ts), as @opencode/cli 2.2.5 sent it to Zen on 2026-11-01: opencode/latest/2.2.5/cli.

func OpenReadOnly added in v0.1.92

func OpenReadOnly(path string) (*sql.DB, error)

OpenReadOnly opens another app's SQLite database without writing to it.

func OutputWithin added in v0.1.1144

func OutputWithin(window, output int) int

OutputWithin is a reply limit as it is published beside a window: kept within it. models.dev lists some models' output above the window their vendor's own list gives (Grok's grok-4.7: 500000 against the 256000 its backend says, #1438; deepseek-chat's 384000 against 128000, #338), and a client that reads both sizes its replies past what the window holds. An unknown window or output is left as it is. Every place that hands out the pair uses it — the agents' files, the gateway's model lists, the GUI and the CLI — while a request is still lowered only to the model's own limit (Entry.Output, withMaxOutput).

func OutputsOf added in v0.1.876

func OutputsOf(providerID string) map[string]int

OutputsOf is the reply limits the user set on a provider's models, by model id, "*" for all of them: what its editor's Max output shows.

func OwnFast added in v0.1.1191

func OwnFast(p Provider, model string) bool

OwnFast reports whether model has a fast mode only as the user's own provider may serve it (#1615): a GPT model on a provider they added by its address, on an OpenAI API, which magpie can't tell serves priority and asks for it all the same when the user switches it fast. Not where CanFast knows the vendor's (OpenAI's own API).

func OwnModelsHidden added in v0.1.1198

func OwnModelsHidden(agent string) bool

OwnModelsHidden reports whether agent's pickers leave out the models it reaches on its own, offering magpie's alone (#1642).

func OwnRoute added in v0.1.3374

func OwnRoute(agent, id string) (to, group string, ok bool)

OwnRoute is where a bare model's id agent asks for goes on the agent's own subscription: its "provider/model". group is the found group's ref ("group/auto-…") the id named, which the request now goes past, "" when it named none (found groups off, or the group removed). ok is false when the id isn't bare, the user has a group of their own by it, or no subscription of the agent's serves it.

func PageTitle added in v0.1.1637

func PageTitle(b []byte) string

PageTitle is a web page's title as plain words, cut to 120 runes: no markup, entities read, whitespace folded. "" when there is none.

func ParseCap added in v0.1.809

func ParseCap(s string) (int, error)

ParseCap reads a cap as the CLI takes it: "70", "70%", or off (none, 0, -) for no cap.

func ParseClock added in v0.1.2200

func ParseClock(s string) (min int, ok bool)

ParseClock reads "HH:MM" as minutes into the day: 0 for 00:00 through 1440 for 24:00, which only an end may be. ok is false for anything else.

func ParseDay added in v0.1.570

func ParseDay(s string) (string, bool)

ParseDay reads a day of the week, "mon" or "Monday", as Weekdays has it.

func ParseDays added in v0.1.570

func ParseDays(v string) ([]string, error)

ParseDays reads days of the week: "mon-fri", "sat,sun", "mon,wed-fri"; a range may run past Sunday (fri-mon).

func ParseKeyPriceRate

func ParseKeyPriceRate(s string) (*float64, error)

ParseKeyPriceRate reads a key's price rate as the CLI takes it: a number ("0.8", "1.5x", "×1.2"), or default (nil) for the provider's.

func ParseLimit added in v0.1.1009

func ParseLimit(s string) (*int, error)

ParseLimit reads a limit as the CLI takes it: a whole number, 0 or off for no limit, default for the provider's (nil).

func ParseRefreshEvery added in v0.1.1234

func ParseRefreshEvery(s string) (time.Duration, error)

ParseRefreshEvery reads a RefreshEvery as typed: a Go duration ("30m", "6h") or a number of days ("1d"); "", "off", "never" or "0" for none.

func ParseSocket added in v0.1.3397

func ParseSocket(v string) (string, bool)

ParseSocket is the Socket v sets: auto, on, off (off, no or false), or "" for the default (default or empty); ok is false for anything else.

func ParseTokens added in v0.1.136

func ParseTokens(v string) (int, error)

ParseTokens reads 200000, 200k, 1.5m.

func ParseVision added in v0.1.1360

func ParseVision(v string) (*bool, error)

ParseVision is a typed vision answer: true or false, nil for auto.

func ParseWeight added in v0.1.2316

func ParseWeight(s string) (int, error)

ParseWeight reads a weight as the CLI takes it: a whole number from 1 to MaxKeyWeight, or default (-, 0) for 1.

func PartnerCountsSent added in v0.1.1126

func PartnerCountsSent(now time.Time)

PartnerCountsSent forgets the days that were sent: those before now's.

func PartnerNoticed added in v0.1.1126

func PartnerNoticed(id string) bool

PartnerNoticed reports whether the user has been shown the partner id.

func PastePluginCallback added in v0.1.1091

func PastePluginCallback(ctx context.Context, page, raw string) (next string, err error)

PastePluginCallback is pluginCallback for the command line, which runs a plugin's sign-in itself: page is the address the sign-in opened.

func Path

func Path() string

Path is the file the user's providers live in.

func PatternMatches added in v0.1.826

func PatternMatches(pattern, id string) bool

PatternMatches reports whether a pattern matches a "provider/model" id. A free rule's scope is matched (FreePrefix): the flag is the model's, not its id's, and a caller asks this of a model the rule took.

func PausedOut added in v0.1.1155

func PausedOut(g Group, ms []Member, agent, folder string, at time.Time) (kept []Member, paused []Paused)

PausedOut leaves out of ms the models a pause rule holds for now, for a request from agent working in folder ("" when it didn't say, or wasn't read: see PausesByFolder): the group's own, or those of a group in it on the way to them. A rule naming a group in the group pauses every model of it.

func PausesByFolder added in v0.1.1191

func PausesByFolder(g Group, ms []Member) bool

PausesByFolder reports whether a pause rule of g, or of a group in it on the way to one of ms, holds by folder: the request's folder is then read before the pauses are looked at.

func PickGroup added in v0.1.1272

func PickGroup(id, pick string) error

PickGroup sends every request to a Manual group of the user's to its member pick from the next request on (#317), as its card's radios do, from wherever the user switches it: the tray panel (#2489) too. Nothing else of the group changes, and only a Manual group can be switched so.

func PickedModels added in v0.1.1130

func PickedModels(agent string) (map[string]bool, bool)

PickedModels are the only entries agent's lists show, by id (a found group by the id it is listed by now, PublicRef), and whether it is shown only those (#1337): a model not among them, one that came after the user switched to it among them, is not shown.

func PlanTerm added in v0.1.209

func PlanTerm(until *time.Time, renew string) string

PlanTerm says when a plan's paid time ends, "renews Oct 18", "expires Oct 18" or "until Oct 18" when the vendor doesn't say which; "" when it isn't known.

func PluginAPIKey added in v0.1.479

func PluginAPIKey(ctx context.Context, id string, method int, inputs map[string]string, key string) (string, error)

PluginAPIKey signs in to a plugin's provider with a key, as its "api" method does, beside the accounts signed in already; it gives the provider's magpie id.

func PluginAccountUser added in v0.1.2620

func PluginAccountUser(id, key string) string

PluginAccountUser is who the plugin id's account at key is (an email, a login), as the Routing trace and the request log name it: "" when no account is kept there.

func PluginCLIMissing added in v0.1.1241

func PluginCLIMissing(id string) string

PluginCLIMissing is the name of the vendor CLI a plugin's sign-in runs through and this machine lacks (Grok Build for Grok's), "" when there is none to install. The command line's sign-in installs it first, as StartPluginSignIn does; without it, `magpie plugin login grok` in Docker said "install Grok Build first: curl … | bash", which the image has no curl to run (#2223).

func PluginCheckinOn added in v0.1.1085

func PluginCheckinOn(s settings.Settings, id string) bool

PluginCheckinOn says whether a plugin provider's accounts are checked in each day: as the user set it for the provider, else as the built-in check-in of its vendor is set, which the plugin took over.

func PluginID added in v0.1.479

func PluginID(id string) string

PluginID is the id magpie gives the provider OpenCode calls id: the same, unless a preset or a built-in subscription has it (google, openai, anthropic), or a provider of the user's own made before the plugin was installed (zenmux, #867), or "auto" or "group", which start the ids of routing groups, when it is id-plugin — but for a built-in moved onto the plugin, whose id the plugin has now.

func PluginIcon added in v0.1.553

func PluginIcon(pp plugin.Provider) string

PluginIcon is the icon a plugin's provider shows: the picture its plugin gives it (the auth hook's icon, or package.json's magpie.icon), kept as a picture given by hand is, else the one the plugin market gives it.

func PluginImportable

func PluginImportable(id string) bool

PluginImportable is whether the subscription id (a magpie id) is a plugin's that takes accounts from a file (auth.import). Factory's plugin has its own importer here (ImportFactoryKeys), which goes first.

func PluginListError added in v0.1.1001

func PluginListError(pp plugin.Provider, key string) string

PluginListError is why the plugin couldn't list the account at key's models, "" when it did or kept the list it had: what it shows instead is its short defaults (Cursor's Auto alone).

func PluginOf added in v0.1.479

func PluginOf(id string) (plugin.Provider, bool)

PluginOf is the plugin provider magpie's provider id is, when it is one.

func PluginOwnIcon added in v0.1.1161

func PluginOwnIcon(said string) string

PluginOwnIcon is the Icon value of a picture a plugin gave (a data:image URI or an https URL), "" while there is none to show: an agent a plugin adds shows it as a provider's does.

func PluginPastesCallback added in v0.1.1091

func PluginPastesCallback(id, page string) bool

PluginPastesCallback says whether a plugin's sign-in that opened page can be finished from the address its browser ends on.

func PluginRouting added in v0.1.1257

func PluginRouting(routing string) bool

PluginRouting says whether routing is one a plugin serves, "<plugin>/<name>" (a JS gateway plugin's strategies). providers.json keeps one as saved, served now or not: one no plugin serves is tried in its listed order.

func PluginServes added in v0.1.1282

func PluginServes(id string) bool

PluginServes is whether the built-in id's subscription is its plugin's to serve, and magpie's built-in code serves none of it: moved onto its plugin, or retired.

func PluginSignedIn added in v0.1.1098

func PluginSignedIn(saved plugin.Saved) string

PluginSignedIn finishes a sign-in to a plugin's provider that magpie doesn't follow, a key or the command line's own, once the plugin has saved the account: as for one it follows (pluginDone), the account's lapsed mark goes and, removed from magpie, it comes back. It gives the provider's magpie id.

func PluginTiers added in v0.1.1269

func PluginTiers(p Provider, model string) []string

PluginTiers are the service tiers p's plugin says its vendor serves model at (m.serviceTiers, #2514): none for a provider not a plugin's, or a model it doesn't list.

func PluginUserOf added in v0.1.2247

func PluginUserOf(id, user string) string

PluginUserOf is the name a plugin's usage gives its account user (usage().user, a masked phone) where that isn't user itself, "" for none or one not read. A plugin's accountId is the account's key in magpie (its own name, proxy and gateway key are kept by it), so codearts keeps an IAM id there, iam::<domain>:user:<name>, and tells the phone only in usage (#4416). It is shown, never kept: what was read this run, else the last reading quotas.json has, so a read that fails or hasn't been made yet shows what was known, or user, never nothing.

func PreferredEndpoint

func PreferredEndpoint(e Entry, members func(id string) []Member) string

PreferredEndpoint is the path a request for the model is best asked on (/v1/models' magpie_prefers, for another magpie that has this one as its provider): its provider's Native API, or for a routing group the one GroupAPI wires an agent to, Responses where its members are best there. "" for a model translated anyway, or a group that stays on Chat. members is nil when the group's aren't known.

func PrefillNewKeys added in v0.1.2674

func PrefillNewKeys(ctx context.Context, before map[string]map[string]bool, ids ...string) int

PrefillNewKeys gives each key on that a provider of ids (every provider when none is named) has and before didn't — a provider before has no entry for is new, all its keys with it — the models its own list answers, as AccountModels: only a key with no models of its own yet, of a provider with more than one key on, whose list leaves out a model the provider's others list. It answers how many keys were given a list.

func PriceKey added in v0.1.504

func PriceKey(pid, model string) (string, bool)

PriceKey is the key a price for pid's model is stored at, and whether the provider naming that key is still there at all.

The spelling that was given comes first, because a price outlives the provider it was set for and nothing rewrites the key when that provider goes: "b/vendor/m" can still be where a price is held while a provider of some other id answers to "b" as its display name. Resolving that name first would take the second provider's price away instead — none is stored under it, so nothing would change, the caller would be told it had, and the price the user meant would stay in the file to be counted at. Only where nothing is stored under the spelling is the provider looked for, by the id it has or the one it was renamed from: that is where SetModelPrice keeps a price set through a display name, and the same resolution EffectivePrice reads it back under.

func PriceRateOK added in v0.1.901

func PriceRateOK(r float64) string

PriceRateOK says what is wrong with a provider's price rate, "" when nothing: from 0 (none) to 1000, in steps of 0.001.

func PricedName added in v0.1.418

func PricedName(model string) string

PricedName is the catalog ID used for a list-price estimate. Prefer a directly listed model before falling back to a documented alias.

func PricedNameFor added in v0.1.1134

func PricedNameFor(providerID, model string) string

PricedNameFor is PricedName for a call to that provider: a Kimi Code membership's k3 is priced as the API's kimi-k3 (kimiCodeAPI).

func ProbeClaudeVia added in v0.1.551

func ProbeClaudeVia(f func(ctx context.Context, configDir, model string) error)

ProbeClaudeVia sets how a Claude account's test runs Claude Code.

func ProbeTranslatedVia added in v0.1.1158

func ProbeTranslatedVia(f func(ctx context.Context, p Provider, proto Protocol, model string) (int, error))

ProbeTranslatedVia sets how a model only the gateway can ask is tested.

func ProxyEdited

func ProxyEdited()

ProxyEdited has Claude Code's env follow a saved proxy that was edited: its settings.json holds the address as a snapshot, so an account that chose the proxy by name needs it written again.

func ProxyGone

func ProxyGone(p Provider) string

ProxyGone is the name of a saved proxy p chooses (its own, or an account's) that isn't on this computer, "" when none is missing: what a sync from a magpie that didn't bring the proxy list leaves.

func ProxyOf added in v0.1.418

func ProxyOf(id string) string

ProxyOf is the own proxy of the provider or signed-in account with id, "" when it follows the global one.

func ProxyOfLogin added in v0.1.427

func ProxyOfLogin(id, user string) string

ProxyOfLogin is the proxy requests made on behalf of the account user of the subscription id go through (gakki: one Codex account through one proxy, another through another): the account's own, or else the subscription's (ProxyOf); "" follows the global one.

func PublicRef added in v0.1.1294

func PublicRef(ref string) string

PublicRef is the id agents are given for ref: a found group's group/auto-<slug>, or an auto/<model> spelt otherwise than it is listed now (auto/glm-5-3-flash for auto/glm-5.3-flash), as its auto/<model> (Group.Ref), its effort and [1m] mark kept; any other ref as it is, a found group magpie has none of now too.

func PublicRefs

func PublicRefs() func(string) string

PublicRefs snapshots the found groups' public spellings for a whole usage read. The returned mapper reads no files or shared catalog; nil means the public namespace is inactive or no found group has a public spelling.

func QianfanBookmarklet

func QianfanBookmarklet() string

QianfanBookmarklet is the bookmarklet the user runs on the console while signed in: it asks the plan's page as the console does, so a page not signed in says so there, and copies the page's cookies to be pasted into magpie.

func QianfanEnded

func QianfanEnded(id string) bool

QianfanEnded reports whether the console has ended the provider's sign-in, so the editor asks for a new one.

func QianfanPlan

func QianfanPlan(p Provider) bool

QianfanPlan says p is on Baidu Qianfan's Token Plan Personal, whose usage magpie reads with a sign-in to Baidu Cloud's console.

func QianfanSignedIn

func QianfanSignedIn(id string) bool

QianfanSignedIn reports whether magpie has a sign-in for the provider, ended or not.

func QianwenAccount

func QianwenAccount(id string) string

QianwenAccount is who the provider's sign-in is, as the platform named them: an email, or "" when it gave none.

func QianwenPlan

func QianwenPlan(p Provider) bool

QianwenPlan says p is on the Qwen AI platform's Token Plan, whose usage magpie reads with a sign-in to the platform.

func QianwenSignInState

func QianwenSignInState(id string) (state, why string)

QianwenSignInState is how the provider's sign-in under way goes: "pending", "done" or "failed" with why, or "" when none is.

func QianwenSignedIn

func QianwenSignedIn(id string) bool

QianwenSignedIn reports whether magpie has a sign-in for the provider, reading the file once until it changes: a provider list asks it on every poll.

func QuietAccount added in v0.1.204

func QuietAccount(id string) error

QuietAccount stops reminding the user of an account they removed: its "Add it back" line goes, and it is offered only from the Add sheet.

func QuotaCardHidden

func QuotaCardHidden(q SubscriptionQuota, s settings.Settings) bool

QuotaCardHidden is whether the Overview hides q's card.

func QuotaHideKey

func QuotaHideKey(q SubscriptionQuota) string

QuotaHideKey is how the app keeps a hidden card (cardHideKey in page.js): its tray card id, then "|balance" for a balance alone, else "|plan".

func QuotaHistoryData added in v0.1.722

func QuotaHistoryData() []byte

QuotaHistoryData is this computer's history as kept, for the usage sync to share.

func QuotaHistorySince added in v0.1.722

func QuotaHistorySince(days string, now time.Time) time.Time

QuotaHistorySince is the start of a range days long (as a query gives it) to now: all that is kept when not a number of days.

func QuotedReply

func QuotedReply(raw []byte) string

QuotedReply is a vendor's reply as an error may quote it: its secrets taken out first (redact.ScrubJSON: a field named for one, AccessToken, access_token, cliAccessToken, client_secret…, wholly, and anything that looks like a key). An error is shown in the GUI, kept in app.log and pasted into reports: the Qwen AI platform's sign-in quoted a reply it couldn't read, live access token and all, and the user posted it on X (@imthe99galaxy, v0.1.4159). Every error that quotes a reply goes through it, a sign-in's or a token's above all.

func RateAt added in v0.1.2200

func RateAt(ws []RateWindow, t time.Time) float64

RateAt is the rate the windows bill at at t, on this computer's clock: 0 when no window holds t, which means the price rate alone, and for a zero t, a price asked for with no call's time (a memo of the price shared by many calls) being the base. The first window that holds t wins. A window's span is from its start in and to its end out; one that crosses midnight belongs to the day it starts on, so its early hours read as that day's.

func ReadAllCards added in v0.1.1078

func ReadAllCards(ctx context.Context)

ReadAllCards has every card read again, the page's Refresh asked by another magpie whose card of this one's said nothing was read yet, or by an app holding a gateway key (POST RemoteRefreshPath with no card named). It is the user's refresh of every allowance, as the Usage page's Refresh is (AskEveryClaudeUsage): each saved Claude account's /usage is run too, under the same 30-second floor and holds (#5443, prgrmrwy: it asked AskUsage alone, and a saved account kept its old reading). The accounts are read side by side, each bounded by subscriptionTimeout, so many of them answer within the gateway's wait.

func ReadKeyRatesSoon

func ReadKeyRatesSoon()

ReadKeyRatesSoon has the keys due a read read now, not at the loop's next tick: a top-up rate the user just gave a provider.

func ReadUsageNow added in v0.1.1792

func ReadUsageNow(ctx context.Context, agent string, users ...string) bool

ReadUsageNow has agent's accounts users read again now, past the minute their readings are kept and though allowances are read only when asked, and waits, till ctx ends, for a reading begun after it asked. It says whether one came back (UsageRead then tells how it went).

func Reasonless added in v0.1.1231

func Reasonless(pid, model string) bool

Reasonless reports whether the user said pid's model takes no reasoning ask (SetModelReasonless).

func RedactWith

func RedactWith(a, b string) string

RedactWith is what two say of masking together: on wins over off, and either over nothing.

func RefreshEach added in v0.1.3113

func RefreshEach(ctx context.Context, cards []SubscriptionQuota)

RefreshEach is RefreshUsage of each of cards, read side by side: a gateway key told some cards has every one of them read again on a Refresh of them all, and one after another, a saved Claude account's /usage about 5 seconds each, a few of them outlasted the gateway's 30 seconds (#5443). Each read is bounded as RefreshUsage's is.

func RefreshUsage added in v0.1.935

func RefreshUsage(ctx context.Context, provider, user string)

RefreshUsage reads the card of provider (of account user, "" for every account it has) again, whether a subscription's, a plan's or a key's balance, and keeps it with the others, which aren't asked. The next Quotas has it.

func RegionID added in v0.1.2735

func RegionID(preset, id string) string

RegionID is the region a preset's region id names now: an id from before regions were made one (a key's plan, an import link, region= on the command line) is the region it became.

func RemoteKeyID added in v0.1.3177

func RemoteKeyID(key string) string

RemoteKeyID is the id a proof names key by: its sha256, in hex.

func RemoteLibrary

func RemoteLibrary(ctx context.Context, id string) ([]byte, string, error)

RemoteLibrary is the body of the Library the remote magpie id shares, and the remote's name.

func RemoteProof added in v0.1.3177

func RemoteProof(key, nonce, at string) []byte

RemoteProof is what a magpie holding key, reached at at (host:port), answers nonce with: HMAC-SHA256 under key of the nonce and the address. The address is in it so that a host passing B's nonce on to the real magpie elsewhere gets a proof for that magpie's address, not its own.

func RemoteTiers added in v0.1.1743

func RemoteTiers(p Provider, model string) []string

RemoteTiers are the service tiers another magpie's list says it offers on model (#1234), nil for a provider that isn't one.

func RemoteVersion added in v0.1.3285

func RemoteVersion(ctx context.Context, p Provider) string

RemoteVersion is the version the Remote magpie p answers GET /v1 with, "" when it can't be told.

func RemoveKey added in v0.1.14

func RemoveKey(id, keyRef string) error

RemoveKey forgets a key. The last key in use stays: turn another on first.

func RemoveKeyExpiring added in v0.1.3310

func RemoveKeyExpiring(id, ref string, x Expiring) error

RemoveKeyExpiring takes a grant of credit that expires off the balance typed for the key ref of the provider id: the one given At, or with no At every one through Until (of Amount, when given). One that matches none is an error, and the rest of the balance stays as it was.

func RemoveKeys added in v0.1.1029

func RemoveKeys(id string, refs []string) (removed int, err error)

RemoveKeys forgets several keys at once (361 on Discord: hundreds of keys, some dead): those named that it has. The first key, when it is among them, gives its place to the next one on that stays. One key in use always stays: removing every key in use is refused.

func RemovePlugin added in v0.1.538

func RemovePlugin(ctx context.Context, name string) error

RemovePlugin removes the plugin named and sets aside the model picks of its providers it leaves in providers.json (plugin_left.go). A built-in moved onto it isn't moved back, as the built-in is going: it is MoveRemoved, its accounts kept with the plugin's sign-ins for when the plugin is installed again. The agent it adds is taken off magpie first (PluginAgentGoing).

func RemoveSearchAPI added in v0.1.587

func RemoveSearchAPI(vendor string) error

RemoveSearchAPI takes the vendor's search API away.

func RemoveSearchKey added in v0.1.3251

func RemoveSearchKey(vendor, ref string) error

RemoveSearchKey takes one key out of the vendor's list.

func RemovedGroups added in v0.1.92

func RemovedGroups() []string

RemovedGroups are the found groups the user removed, whether or not magpie finds them now: each is a record in providers.json ({"id", "hidden": true}) that keeps it removed when two providers serve its model again.

func Rename added in v0.1.125

func Rename(from, to string) error

Rename gives a provider another id, the one its models are picked by (<id>/<model>). What magpie keeps that names it by id follows: the routing groups it is in and their rules and classifiers, the other providers' fallbacks, which agents are shown it, and its StepFun and Qwen AI platform sign-ins. The old id stays with it (Was), so an agent still running on a config that names it the old way reaches it, and its usage so far is counted with it; the agents' own files are the agent package's to rewrite (agent.RenameProvider). A signed-in account keeps the id of its agent.

func RenameGroup added in v0.1.105

func RenameGroup(from, to string) error

RenameGroup gives a group another id, the one agents pick it by (group/<id>). A group magpie found becomes the user's under the new id, the found one kept removed so it doesn't come back beside it. The groups that have it in them, and their rules, name it by the new id.

func RenameKey added in v0.1.14

func RenameKey(id, keyRef, name string) error

RenameKey names one of a provider's keys, "Personal", "Team".

func Renamed added in v0.1.125

func Renamed() map[string]string

Renamed maps the ids providers had to the ones they have now. An id that a provider or a subscription has now is that one's, and is not in it.

func RenamedRef added in v0.1.125

func RenamedRef(ref string) string

RenamedRef is ref with the provider it names by an id the provider had named by the id it has now.

func ReorderedAt

func ReorderedAt(id string) time.Time

ReorderedAt is when NoteReordered was last called for provider id in this process; the zero time before.

func ReplaceKey added in v0.1.1220

func ReplaceKey(id, keyRef, key string) (was, now string, err error)

ReplaceKey puts a new value in place of one of a provider's keys (#1869: a key rotated at the vendor or the relay). The key keeps its name, its place, its protocol and weight, whether it is on, and what was set for it by its fingerprint: the models it serves, its proxy, its concurrency. It returns the key's fingerprint before and after; the same value pasted again changes nothing and returns the same one twice.

func ReplyHeaderPassable added in v0.1.2028

func ReplyHeaderPassable(name string) bool

ReplyHeaderPassable says whether a header of a vendor's reply may be passed on to the agent at all.

func ReplyHeadersNever added in v0.1.2028

func ReplyHeadersNever() (names, prefixes []string)

ReplyHeadersNever are the names and prefixes ReplyHeaderPassable refuses, for the GUI's own check of a list typed (its test holds the two the same).

func ReplyHeadersOK added in v0.1.2028

func ReplyHeadersOK(names []string) string

ReplyHeadersOK says what is wrong with a list of reply headers to pass on, "" when nothing is: a name that isn't one, or one magpie never passes on.

func RepoIcons added in v0.1.1147

func RepoIcons(said []string, wait time.Duration) []string

RepoIcons are the Icon values of the pictures plugins not installed yet give in their package.json (repositories tagged magpie-plugin), checked and kept as an installed plugin's are: "" where there is none to show. An https picture not fetched before is waited for up to wait, so the list's first answer has it (yetone: 非官方插件显示不出来 logo); one slower than that shows the next time the list is asked.

func RequestHeaderPassable added in v0.1.2815

func RequestHeaderPassable(name string) bool

RequestHeaderPassable says whether a header of the agent's request may be passed on to the vendor at all.

func RequestHeadersNever added in v0.1.2815

func RequestHeadersNever() (names, prefixes []string)

RequestHeadersNever are the names and prefixes RequestHeaderPassable refuses, for the GUI's own check of a list typed.

func RequestHeadersOK added in v0.1.2815

func RequestHeadersOK(names []string) string

RequestHeadersOK says what is wrong with a list of request headers to pass on, "" when nothing is.

func ResetClock added in v0.1.211

func ResetClock(at, now time.Time) string

ResetClock is when a window starts again, on the clock: "14:30" today, "tomorrow 09:00", "Wed 14:30" within the week, else "Oct 3 14:30".

func ResetModelSpec added in v0.1.1360

func ResetModelSpec(ref string) ([]string, error)

ResetModelSpec takes every spec the user gave a provider's model away — its window, reply limit, vision answer and levels — leaving it to the vendor's list and models.dev again. "provider/*" takes away the window and reply limit given every model of the provider. It reports what it took away, by part ("context", "output", "vision", "reasoning"). A provider that has gone still has its settings' parts taken away, under the key as typed: a spec outlives the provider it was set for, and `magpie model specs` still lists it.

func ResolveAccount added in v0.1.2618

func ResolveAccount(pid, ref string) (string, error)

ResolveAccount is the entry "<provider>/<id>" an account list — a gateway key's (#905), a routing group's — keeps for provider pid's account or key ref: an account named by its stable id or the name it is shown by, resolved to that id, a key by its fingerprint. It fails for a provider magpie doesn't have, or one with no such account or key.

func RestartCodexApp added in v0.1.1758

func RestartCodexApp(ctx context.Context, bundle string) error

RestartCodexApp restarts the app-server the Codex desktop app at bundle (/Applications/ChatGPT.app) runs for itself, as codexAppStep does: it is ended as a clean exit, and the app starts another, which reads Codex's config and model list afresh, while the app's window, threads and drafts stay as they are. The Agents row's Restart quit the app and opened it again, which opened a new window (yoshi037070 on Discord, 10-27). An app-server another program runs from the bundle (--listen) is left alone. It waits until the ones ended are gone and the app has started another (codexAppBackWait), and errs when none ran or none started.

func RestartCodexAppWhenIdle added in v0.1.2034

func RestartCodexAppWhenIdle(ctx context.Context, wait time.Duration) (ended int, left bool, err error)

RestartCodexAppWhenIdle ends the Codex app's own app-servers once, for a magpie that won't be running to watch them (magpie uninstall): the app starts a new one, which reads Codex's config as it is now. It waits up to wait for a running Codex turn to end, and cuts none short: left says an app-server was still on the old config when it gave up, or couldn't be ended, or that the app started none in its place and couldn't be reopened (codexAppGotNone), so the user quits and opens the app.

func RestartCodexDaemon added in v0.1.368

func RestartCodexDaemon(ctx context.Context) error

RestartCodexDaemon has Codex restart its app-server, which reads the sign-in again: `codex app-server daemon restart`, run with the codex CLI magpie finds and the Codex home it signs Codex in through. Codex 0.162's sessions attached to it reconnect to the new one, a turn running is let finish first (for up to a minute); an older Codex's are ended.

func RestartSwitchedCodexApp added in v0.1.2142

func RestartSwitchedCodexApp(ctx context.Context) error

RestartSwitchedCodexApp is the Restart on Codex's accounts' "the Codex app is still signed in as" notice (nb5p_hQ on X): it restarts the app's own app-servers now, as codexAppStep does once no Codex turn runs, so the app reads the account Codex was switched to; the user said yes to cutting a running turn short. Each is ended as a clean exit, which the app answers by starting another (its window, threads and drafts stay; quitting the app and opening it again opened a new window, yoshi037070); it is never killed, as the app shows a kill as a crash. It waits until the ended ones are gone and a new one runs, and errs when either doesn't happen in time: a listing that fails is unknown, never success.

func Restore added in v0.1.28

func Restore(ps []Provider) (added, replaced int, err error)

Restore puts providers from a backup in. Each replaces the one here with its id; one that came without keys keeps the keys already here, and one without an access key or balance token keeps those (KeepSecrets). It returns how many were new and how many replaced one here.

func RestoreGroups added in v0.1.76

func RestoreGroups(gs []Group) error

RestoreGroups puts groups from a backup in, each replacing the one here with its id.

func RestoreSearchAPIs added in v0.1.587

func RestoreSearchAPIs(as []SearchAPI) error

RestoreSearchAPIs puts search APIs from a backup in, each replacing the one of its vendor here; one that came without a key keeps the key here. They are asked in the backup's order, switched on or off as they were there (#2286), and one only here is asked after them.

func Retire added in v0.1.1148

func Retire(pid, model string)

Retire notes that provider pid's vendor said model is retired: it leaves the lists, and the agents' lists are written again.

func Retired added in v0.1.1148

func Retired(pid, model string) bool

Retired says whether provider pid's vendor said model is retired, within retiredFor.

func RetryCodexKeychain added in v0.1.1261

func RetryCodexKeychain() error

RetryCodexKeychain is Try again beside a sign-in the keychain didn't give (#2367): Codex's item is read once, now, past a refusal or a prompt with no answer kept (a fresh read), and what it gets is kept in their place. It gives what that read gave: errKeychainWaiting while the prompt is up (joining it, never a second one), its answer kept when it comes.

func RetryOneAuth added in v0.1.1211

func RetryOneAuth(p Provider, req *http.Request, res *http.Response, do func(*http.Request) (*http.Response, error)) (*http.Response, error)

RetryOneAuth hands on res, the answer to req, which p signed for its Anthropic API; or, when the vendor refused it for carrying the key in both x-api-key and Authorization (catalog.BothAuthRefused), the answer to req asked again with each alone, x-api-key first, and remembers for p the one it took (LearnAuthHeader). do sends a request as req was sent.

func RetryOpenCodeFreeOnZen added in v0.1.2708

func RetryOpenCodeFreeOnZen(p Provider, proto Protocol, req *http.Request, res *http.Response, do func(*http.Request) (*http.Response, error)) (*http.Response, error)

RetryOpenCodeFreeOnZen asks Zen's free tier for a free model p's OpenCode Go gateway answered "Model is unavailable" to (req, res), with the public key in place of the user's, and returns what Zen answered when it served it. Otherwise res is returned, its message saying where the model is served. Any other request or answer is res as it was.

func RetryZhipuCoding added in v0.1.1224

func RetryZhipuCoding(p Provider, req *http.Request, res *http.Response, do func(*http.Request) (*http.Response, error)) (*http.Response, error)

RetryZhipuCoding hands on res, the answer to req; or, when req went to Zhipu's or Z.ai's pay-as-you-go OpenAI API and was refused for want of a balance (1113), the answer to req asked again at the GLM Coding Plan's endpoint when that one serves it — remembering it for p (LearnZhipuCoding) — else res with what to change added to its message. do sends a request as req was sent.

func RevokedAccount added in v0.1.1213

func RevokedAccount(a *Account) bool

RevokedAccount says the account's revoked sign-in is marked here: one of the built-in subscriptions that keep no mark of their own.

func RevokedSignIn added in v0.1.1213

func RevokedSignIn(a *Account, req *http.Request) (why string, ok bool)

RevokedSignIn is why the request req, signed for account a, isn't sent: its vendor revoked the credential it carries. ok is false otherwise.

func Routings added in v0.1.1247

func Routings() ([]string, error)

Routings is the routing of each provider and group providers.json sets one for, read from the file alone: for what asks often (the rotation plugin's InUse), without building the catalog and reading every sign-in.

func RuleWords added in v0.1.136

func RuleWords(line string) []string

RuleWords splits a typed line into its words, a "quoted" part in one: intent="a quick question".

func RulesRead

func RulesRead(rules []Rule, field string) bool

RulesRead reports whether a rule of rules has a condition on field, which is then read for it.

func SIWCForTest added in v0.1.1058

func SIWCForTest(issuer, api string) func()

SIWCForTest points the sign-in and the API at test servers.

func SameOrigin added in v0.1.3166

func SameOrigin(scheme, host, toScheme, toHost string) bool

SameOrigin says whether a redirect from scheme://host to toScheme://toHost may carry a credential: the same scheme, host and port (a port left out is the scheme's own), or http to https on the same host and default ports.

func SamePlanAccounts added in v0.1.3059

func SamePlanAccounts() map[string]string

SamePlanAccounts maps each ChatGPT API account to the Codex account that is the same ChatGPT account, both as provider + "\x00" + lowercased name, the way the usage ledger's calls are keyed. They are matched on what the tokens say, never on a name: the ChatGPT account (workspace) id and the user's id, both known and both equal. Two Team seats of one email share a name and a user, not an account id; an account whose tokens don't say both is matched to none.

func SamePriceIn added in v0.1.1258

func SamePriceIn(s settings.Settings, providerID, model string) (catalog.Price, bool)

SamePriceIn is the maker's list price of the model the user said providerID's model is the same as (settings' ModelSameAs, #2344): for an id of the provider's own that no list prices, as WorkBuddy's kimi-k3-1 or a plugin's qfmodel. It is the last place a price is looked for, after the user's own, the provider's list and the model's maker's by its own id, and is never another provider's tariff. MakerPrice reads the id as any vendor spells it, with its prefix ("moonshotai/kimi-k3") or not.

func SameRef added in v0.1.1294

func SameRef(a, b string) bool

SameRef reports whether a and b name the same model or group, a found group by either of its ids.

func Save

func Save(p Provider) error

Save adds or replaces a provider.

func SaveGroup added in v0.1.38

func SaveGroup(g Group) error

SaveGroup adds or replaces a group of the user's. Changing one magpie found makes it the user's.

func SaveQianfanPaste

func SaveQianfanPaste(ctx context.Context, id, text string) error

SaveQianfanPaste keeps the console session the user pasted for the provider id, once the console has taken it.

func SaveStepFunPaste added in v0.1.389

func SaveStepFunPaste(ctx context.Context, id, site, text string) error

SaveStepFunPaste keeps the session the user pasted for the provider id, whose platform is site: what the bookmarklet copied, or the Oasis-Token cookie as the browser's developer tools show it (the access token, three dots, the refresh one).

func SaveStepFunSession added in v0.1.389

func SaveStepFunSession(ctx context.Context, id, site, access, refresh, webID string) error

SaveStepFunSession keeps the session the sign-in page ended in, once the platform has taken it: a page that isn't signed in yet has an anonymous one, which is refused here. It is the provider id's alone; site is the provider's platform.

func SawClient added in v0.1.1158

func SawClient(client string, h http.Header)

SawClient notes the headers the gateway let go on as client sent them, for a test asked as client to ask with.

func SawCodexClient added in v0.1.441

func SawCodexClient(h http.Header)

SawCodexClient notes the version a Codex client's request says it is — its `version` header, else the one in its User-Agent (codex_cli_rs/0.159.0, Codex Desktop/0.159.0) — when the request is Codex's (it names an originator, or its User-Agent is codex_…).

func SearchAPIsSet added in v0.1.1253

func SearchAPIsSet() (int, error)

SearchAPIsSet counts the search APIs that can be asked; a providers.json that can't be read is an error, not none.

func SearchKeyOf added in v0.1.3251

func SearchKeyOf(vendor, ref string) (string, error)

SearchKeyOf is the vendor's key that ref names, on or off.

func SearchKeyRef added in v0.1.3251

func SearchKeyRef(key string) string

SearchKeyRef is how a page names one key without holding it: a hash of it, the same on every computer.

func SeatNameOf added in v0.1.1172

func SeatNameOf(id, user string) string

SeatNameOf is the name of the key plan the account user of the subscription id was found to stand in for, "" when none: the plan's provider as it is named now, and its key's name when it has several.

func SecretHeader added in v0.1.1214

func SecretHeader(name string) bool

SecretHeader reports whether a header or an environment variable by that name looks like it holds a key: what a backup without keys leaves empty.

func SeekHere added in v0.1.3150

func SeekHere(ats []string) (restore func())

SeekHere has every look made at ats alone, as if any look made before were long ago, until restore: for the gateway's tests, whose Remote magpie is on loopback.

func SentIDOf

func SentIDOf(pid, model, effort string) string

SentIDOf is SentIDAt for the provider of id pid, for a caller that holds only the id (a record's, read for each of a ledger's): an id that names no family of the list fetched for pid goes as it is without the providers read, and so does one of no provider's.

func SentNameIn added in v0.1.560

func SentNameIn(wires map[string]string, pid, model, effort string) string

SentNameIn is the name a call on the provider's model goes out under at that effort: the name the vendor would be asked for now, which is the one magpie knows the model by unless the user gave one. It is UpstreamNameAs for the id that call asks for, which is not the model magpie knows everywhere: on an Antigravity account it is the variant of it that effort picks, so a name given for the provider asks for each level by its own id, and a ledger reading a record back reads the vendor's reply against the name that really went out — the same one the gateway sent — rather than against the family it is one level of.

The effort is the one the gateway sent, already fitted to the model's own levels, which is what a record keeps of it, so a level of the model's own is one of its variants and goes out as that one. An effort that is no level of the family names the same id the gateway asked for all the same: the level of the family's own nearest (AntigravitySentID), which is where the envelope went out.

It is SentNameOnIn for the caller that has nothing but the id — a record in the ledger, which keeps the id the call went out on and nothing else. A provider that is an account is built with that account's own id as its own (googleProvider and the rest of the account providers), so the id says which account it was, and a provider of the user's own is no account's whatever its id is. A record's provider need not even be signed in now, which is why nothing here goes looking for the account behind the id: the id a call went out on is all a record has and all it can be read by.

func SentNameOnIn added in v0.1.560

func SentNameOnIn(wires map[string]string, pid, account, model, effort string) string

SentNameOnIn is SentNameIn for a caller holding the provider itself, and so the account behind it: the call goes out on that account, and it is the account the id the effort picks is a question about. A provider's id is that account's own id today (googleProvider and the rest of the account providers build each one with it), so passing the id for the account reads the same — but the two are one id by construction rather than by rule, and a provider of the user's own has no account at all whatever its id is. So the route, which is holding the provider, asks about the account and lets the gateway's dispatch (codeAssistID, on the same agent) be the one rule.

func ServeGroups added in v0.1.1248

func ServeGroups() (remove func())

ServeGroups serves the user's own groups until remove: plugins/groups calls it while it is on.

func ServedID added in v0.1.664

func ServedID(p Provider) string

ServedID names who answers for p, as its Quota is found by: an account by its agent and user ("codex@a@b.c"), a key by its provider and the key's id ("deepseek#k1a2b3c"), else the provider.

func ServedSignIn added in v0.1.1213

func ServedSignIn(a *Account)

ServedSignIn notes a request account a's vendor served: a mark of a revoked sign-in it has is gone, as the account was signed in again or its sign-in refreshed.

func ServesModel added in v0.1.560

func ServesModel(p Provider, model string) bool

ServesModel is whether the provider really serves model, listed or exposed: the question SetUpstreamName asks before it keeps a name for one, and the same one, since a name given for a model the provider does not serve is a request magpie would never send it. It is the answer a caller told to take a name off needs as well: a model the provider has nothing like is not asked for by any name, so reporting which one is in force for it would say magpie asks for a model it does not know.

func SetAccountCap added in v0.1.809

func SetAccountCap(id, ref string, cap int) error

SetAccountCap caps the account ref of the subscription id at cap percent of its windows; 0 lifts the cap.

func SetAccountConcurrency added in v0.1.1009

func SetAccountConcurrency(id, ref string, limit *int) error

SetAccountConcurrency gives the account or key ref of the provider id its own limit on requests at once, 0 for none; nil gives it the provider's again.

func SetAccountModels added in v0.1.610

func SetAccountModels(id, ref string, models []string) error

SetAccountModels gives the account or key ref of the provider id the models it alone serves; none gives it every model the provider has again.

func SetAccountName added in v0.1.1172

func SetAccountName(id, ref, name string) error

SetAccountName names the account ref of the subscription id; "" takes the name off.

func SetAccountOrder added in v0.1.605

func SetAccountOrder(id string, order []string) error

SetAccountOrder changes the order used by routing, not just its presentation. The first enabled account becomes first through the same switch used by Make first, unless the agent is kept signed in to another (KeepLoginAs). Disabled accounts can be moved, but never silently enabled by a drag.

func SetAccountWeight added in v0.1.2316

func SetAccountWeight(id, ref string, weight int) error

SetAccountWeight gives the account ref of the subscription id its weight under Weighted routing, 1 to MaxKeyWeight; 0 or 1 is the default, kept as none.

func SetAffinity added in v0.1.38

func SetAffinity(id, affinity string) error

SetAffinity changes how long a provider's conversations stay with the key or account that answered them.

func SetAgentCompact added in v0.1.2910

func SetAgentCompact(agent string, c *settings.AgentCompact) error

SetAgentCompact gives an agent of CompactAgents a Long conversations of its own, c, over the one for every agent; nil takes it away, and the agent follows that one again.

func SetAgentContexts

func SetAgentContexts(agent string, cs map[string]int) error

SetAgentContexts gives agent the windows in cs, replacing those it had; none takes them away, and it is told each model's own again. A key is a model as the catalog has it ("provider/model", "group/<id>"), a provider's "provider/*", a bare model id or "*". The agents are told when it changes.

func SetAgentEffort added in v0.1.1084

func SetAgentEffort(agent, level string) error

SetAgentEffort asks agent's requests for level, one of MemberEfforts; "" asks for none, leaving each request's own.

func SetAgentSuffix

func SetAgentSuffix(agent, mode string) error

SetAgentSuffix gives the agent of that id a Provider in model names of its own, mode (SuffixOn, SuffixOwn or SuffixOff), over the one for every agent; "" takes it away, and the agent follows that one again. The agents are told when it changes.

func SetAtOnce added in v0.1.2502

func SetAtOnce(id string, n *int) error

SetAtOnce sets how many of the provider's accounts or keys take requests at the same time: 0 for no limit, nil for what its plugin says.

func SetAutoGroupSkip added in v0.1.2246

func SetAutoGroupSkip(ids []string) error

SetAutoGroupSkip keeps the providers ids names out of the groups magpie finds, and every other back in: none of their models is in a found group, so a model one other provider serves is no group of them. The groups the user made or changed, a found one included, keep them: they are the user's. A request still naming a found group skipping took away goes to its model from one provider (AutoStandIn).

func SetAutoGroups added in v0.1.603

func SetAutoGroups(on bool) error

SetAutoGroups turns the groups magpie finds on its own on or off, all of them at once (蓝猫 on Discord: they could only be removed one by one). Off, none is listed or served; the groups the user made or changed, one found included, stay, and so do the records of those removed, so that on again brings back the found groups as they were. A found group one of the user's has in it, or classifies with, keeps them on until it is taken out, as DeleteGroup keeps it: the user's group would lose it unsaid.

func SetAutoInclude added in v0.1.1234

func SetAutoInclude(id string, rules []string) ([]string, error)

SetAutoInclude sets the provider's rules, and takes the models its list has now that they match into its picks; none clears them. It answers the models taken.

func SetBareIDs

func SetBareIDs(on, only bool) error

SetBareIDs sets settings.BareModelIDs to on and BareModelIDsOnly to only (which off clears). The list is built for each request, so the next one has the bare ids, or goes without them; no agent's file names a model by one, so none is written again.

func SetBareModelIDs added in v0.1.1226

func SetBareModelIDs(on bool) error

SetBareModelIDs turns settings.BareModelIDs on, beside the provider/model ids, or off.

func SetBody added in v0.1.1400

func SetBody(req *http.Request, b []byte)

SetBody makes b req's body, as NewRequest would from a bytes.Reader, read again by GetBody for a retry or a redirect until LetGo.

func SetCapCareful added in v0.1.1792

func SetCapCareful(id string, on bool) error

SetCapCareful has a subscription's capped accounts read again near their cap and held while their usage can't be told (Provider.CapCareful), or go by the last reading again.

func SetCapStop added in v0.1.1792

func SetCapStop(id string, on bool) error

SetCapStop has a subscription answer 429 while every account is held at its usage cap, rather than go on to its fallbacks (Provider.CapStop), or go on to them again.

func SetCodexAgentsV1 added in v0.1.715

func SetCodexAgentsV1(on bool) error

SetCodexAgentsV1 turns settings.CodexAgentsV1 on or off, and has Codex's lists written and asked for again.

func SetCodexAsyncCompact added in v0.1.1277

func SetCodexAsyncCompact(on bool, percent int) error

SetCodexAsyncCompact sets Codex's background compaction (settings.CodexAsyncCompact) and the share of a model's window it starts at, 1–100 or 0 for Codex's own, and has Codex's config written again.

func SetCodexAutoReset added in v0.1.507

func SetCodexAutoReset(user string, on bool) error

SetCodexAutoReset turns that on or off for user, at both times.

func SetCodexAutoResetCase added in v0.1.1234

func SetCodexAutoResetCase(user, when string, on bool) error

SetCodexAutoResetCase turns one of the two times (ResetCaseWeek or ResetCaseExpiring) on or off for user, the other kept as it is.

func SetCodexAutoReview added in v0.1.1062

func SetCodexAutoReview(id string) error

SetCodexAutoReview sets settings.CodexAutoReview, the model Codex's auto-review runs on ("" for Codex's own pick), and has Codex's lists written and asked for again.

func SetCodexClient

func SetCodexClient(v string) error

SetCodexClient sets settings.CodexClient.

func SetCodexCompactModel

func SetCodexCompactModel(id string) error

SetCodexCompactModel puts Codex's compactions on id, a model or routing group of magpie's (provider/model, group/<id>); "" leaves each on the session's model. One magpie doesn't serve now is kept all the same: the gateway leaves compactions where they are until it is served.

func SetCodexCredits added in v0.1.1080

func SetCodexCredits(user string, on bool) error

SetCodexCredits turns that on or off for user. On is in its place: it clears "first" and "last" too.

func SetCodexCreditsMode added in v0.1.2511

func SetCodexCreditsMode(user, mode string) error

SetCodexCreditsMode sets how user spends its credits: CreditsOn, CreditsFirst, CreditsLast or CreditsOff. One account has one of them.

func SetCodexOpen

func SetCodexOpen(v string) error

SetCodexOpen sets what Codex opens in from its Agents row menu: "", "app" or "terminal" (Yink88564391 on X).

func SetCodexResetLead added in v0.1.2243

func SetCodexResetLead(minutes int) error

SetCodexResetLead sets how many minutes before a reset about to run out unused it is spent (resetLead), for every account: from settings.CodexResetLeadLeast to CodexResetLeadMost, or 0 for the default half hour.

func SetCodexServiceTier

func SetCodexServiceTier(tier string) error

SetCodexServiceTier sets settings.CodexServiceTier.

func SetCodexSubagentModel added in v0.1.1142

func SetCodexSubagentModel(id string) error

SetCodexSubagentModel puts Codex's subagents on id, a model or routing group of magpie's (provider/model, group/<id>); "" leaves them on the model their lead asks for, CodexSubagentLead puts them on the lead's. One magpie doesn't serve now is kept all the same — a backup or profile put back on a computer whose providers differ, or an account signed in again later — and the gateway leaves subagents on the model asked for until it is served, saying why in the route trace. One of Codex's own bare names is refused: it names no model of magpie's to put the request on.

func SetCodexSuggestionsModel

func SetCodexSuggestionsModel(id string) error

SetCodexSuggestionsModel puts Codex's prompt suggestions on id, a model or routing group of magpie's (provider/model, group/<id>); "" leaves them on the model Codex sends them on.

func SetCodexWarmAt added in v0.1.1080

func SetCodexWarmAt(user, at string) error

SetCodexWarmAt gives user a time of day of its own ("06:00"), none ("off"), or, "", has it follow settings' CodexWarmAts again.

func SetCompactAt added in v0.1.979

func SetCompactAt(n int) error

SetCompactAt has every model without a threshold of its own compacted at n tokens, Full window turned off; 0 is the working window again (settings.WorkingWindow).

func SetContext added in v0.1.532

func SetContext(p Provider, model string, n int) error

SetContext is how long a request one of a provider's models takes, in tokens, over what the vendor's list and models.dev say; 0 takes the user's away, which DropContext does, and "*" is every model of that provider. As with a reply limit, setting one has to name a model the provider serves, and a removal may name one it no longer does.

This is the provider's own Contexts, kept as the one value both the gateway advertises and the routing rules read — a context is a routing input, not only a number agents are shown: at 95% of a held member's window a request moves to a member that takes more (internal/gateway/rules.go). Saving it tells the agents (catalog.Touched), as for any change of the catalog: a window is a number they keep in files of their own — Pi's contextWindow, OpenCode's limit — and read at start-up, so a session already running keeps the window it began with while the gateway's own /models is right at once.

func SetContextCap

func SetContextCap(n int) error

SetContextCap holds every model's window to n tokens at most (settings.ContextCap), where the user set none for the model or its provider; 0 takes the cap away. Agents' lists are written again.

func SetContextCapAll

func SetContextCapAll(all bool) error

SetContextCapAll chooses whether the longest context (SetContextCap) also holds a window the user set for a model or its provider.

func SetCountFree added in v0.1.2273

func SetCountFree(id string, on bool) error

SetCountFree has every model of a provider count as free for the routings that weigh it, or go by its vendor's word again (Provider.CountFree).

func SetDesktopSubagentEffort added in v0.1.1243

func SetDesktopSubagentEffort(level string) error

SetDesktopSubagentEffort sets a level the gateway fits to the model each subagent reaches. It survives model changes; "" clears the pick.

func SetDesktopSubagentModel added in v0.1.1234

func SetDesktopSubagentModel(id string) error

SetDesktopSubagentModel puts Desktop's subagent turns on id, a model or routing group of magpie's (provider/model, group/<id>); "" leaves them on the model their lead asks for. One magpie doesn't serve now is kept all the same, as Codex's subagent model is, so a backup or profile put back on a computer whose providers differ still applies; the gateway leaves subagents on the model asked for until it is served. A bare name is refused: it names no model of magpie's.

func SetDisabledModels added in v0.1.1219

func SetDisabledModels(list []string) error

SetDisabledModels saves the disabled list whole.

func SetDshCompactModel

func SetDshCompactModel(id string) error

SetDshCompactModel puts DSH's compactions on id, a model or routing group of magpie's (provider/model, group/<id>); "" leaves each on the model it asks for. One magpie doesn't serve now is kept all the same, as Desktop's subagent model is: the gateway leaves compactions where they are until it is served.

func SetFastPick added in v0.1.1077

func SetFastPick(agent, id string, fast bool) error

SetFastPick sends agent's requests for the entry id fast, or not. Only a model with a fast mode magpie can ask for (CanFast) is switched on.

func SetFastTier added in v0.1.1270

func SetFastTier(agent, id, tier string) error

SetFastTier sends agent's requests for the entry id at tier: "" the usual speed, "priority" fast, "ultrafast" Ultrafast where the account offers it (CanUltra), priority where it doesn't.

func SetFullContext added in v0.1.836

func SetFullContext(on bool) error

SetFullContext turns settings.FullContext on or off: Codex and Claude Code are told a model's whole window, or the working one, again.

func SetGoogleProject added in v0.1.63

func SetGoogleProject(agent, user, project string) error

SetGoogleProject names the Google Cloud project an account's requests go to, "" to let Code Assist pick; Code Assist Standard and Enterprise need one.

func SetGroupOrder added in v0.1.843

func SetGroupOrder(ids []string) error

SetGroupOrder saves the order the routing groups are listed in, by id. Every id must be a group's, once; the ones left out follow those named, as they are now, and the whole order is kept, so a group made or found later goes after them all.

func SetHiddenModels added in v0.1.460

func SetHiddenModels(agent string, ids []string) error

SetHiddenModels takes these entries out of agent's lists, and puts back every other; none shows it every model its visibility gives it. The agents that keep the models in files of their own are told.

func SetKeepLogin added in v0.1.641

func SetKeepLogin(id string, keep bool) error

SetKeepLogin keeps Codex or Claude Code signed in to the account the user made first (Provider.KeepLogin), or lets magpie move it on again. Either way it is no longer kept on one of the user's choosing (KeepLoginAs): it is signed in to the first again.

func SetKeepLoginAs added in v0.1.672

func SetKeepLoginAs(id, user string) error

SetKeepLoginAs keeps Codex or Claude Code signed in to user, one of its saved accounts, and signs it in to it now; the order the gateway tries the accounts in stays as it was, the first still first.

func SetKeepSelf added in v0.1.3021

func SetKeepSelf(id string, keep bool) error

SetKeepSelf keeps a Remote magpie that is this magpie in routing, or leaves it out again (Provider.KeepSelf).

func SetKeyBalanceRefill added in v0.1.3295

func SetKeyBalanceRefill(id, ref string, r *Refill) error

SetKeyBalanceRefill gives the balance typed for the key ref of the provider id the refill r, nil for none; its amount and when it was typed stay. A key with no balance typed takes none.

func SetKeyOn added in v0.1.14

func SetKeyOn(id, keyRef string, on bool) error

SetKeyOn turns a key on or off. The last key that's on stays on.

func SetKeyOwnBalance added in v0.1.3281

func SetKeyOwnBalance(id, ref string, b *OwnBalance) error

SetKeyOwnBalance gives the key ref (its id or name) of the provider id the balance b (its amount, in USD or CNY), counted from now; nil takes it off. With no Refill of its own, b keeps the one the key had, and with no Expiring, the credit that expires the key had in the same currency (in the other, its amounts would mean other sums, so they go).

func SetKeyPlan added in v0.1.1600

func SetKeyPlan(id, keyRef, plan string) error

SetKeyPlan says which of the preset's plans (a Region's id) a key is for; empty is the provider's own. Its requests then go to that plan's endpoints, with that plan's models (WithKey).

func SetKeyPriceRate

func SetKeyPriceRate(id, ref string, rate *float64) error

SetKeyPriceRate gives the key ref (its id or name) of the provider id a price rate of its own, or with nil the provider's again.

func SetKeyProtocol added in v0.1.15

func SetKeyProtocol(id, keyRef string, proto Protocol) error

SetKeyProtocol says which one protocol a key works with; empty is any.

func SetKeySpendCap added in v0.1.2819

func SetKeySpendCap(id, ref string, c *SpendCap) error

SetKeySpendCap gives the key ref (its id or name) of the provider id the spend cap c, nil to take its cap off. A cap in all keeps the Since it had while it stays one; else it counts from now.

func SetKeyWeight added in v0.1.933

func SetKeyWeight(id, keyRef string, weight int) error

SetKeyWeight sets a key's share of the requests under Weighted routing; 0 takes it back to the default, 1.

func SetLoginAccessOnly

func SetLoginAccessOnly(agent, user string, on bool) error

SetLoginAccessOnly keeps a saved ChatGPT account access token only, or lets magpie renew its sign-in again. The account Codex is signed in to, here or in another of its folders, can't be kept so: Codex renews it itself as it runs.

func SetLoginOn added in v0.1.14

func SetLoginOn(agent, user string, on bool) error

SetLoginOn puts a saved account in use beside the agent's own, or takes it out. The account the agent is signed in to is always in use.

func SetModelAPI added in v0.1.663

func SetModelAPI(ref, api string) error

SetModelAPI says which one of a provider's APIs a model is asked on — chat, responses, anthropic or gemini — for a relay whose one key serves some of its models on one and others on another (01huadalang on Discord: 有的供应商 一个 api 里有很多模型但是不同协议); "" leaves it to the vendor's list and the URLs the provider has, as before. It must be an API the provider has a URL for: a preset's or a subscription's as well as a custom provider's, when it has more than one (01huadalang: OpenCode Go's deepseek-v4.1-flash answers on Responses too, and magpie asked it on chat alone).

func SetModelCompacts added in v0.1.979

func SetModelCompacts(providerID string, cs map[string]int) error

SetModelCompacts makes a provider's thresholds cs, by model id, "*" for all of them, as its editor's Compact at says: those it leaves out are taken away, and every one set or changed has to be a model the provider serves, as for a reply limit (SetModelOutputs); one sent back as it is for a model the provider no longer lists is kept, not refused (#3305). Codex's and Claude Code's lists are written again when anything changed.

func SetModelEfforts added in v0.1.137

func SetModelEfforts(ref string, efforts []string) error

SetModelEfforts keeps only these of a provider's model's reasoning levels in the lists magpie hands out; none, or all it has, offers them all again. They must be levels the model has — or, for a model whose levels aren't known, any of Levels, which it is given; none takes them away.

func SetModelHeaders added in v0.1.3300

func SetModelHeaders(ref string, h map[string]string) error

SetModelHeaders gives a provider's model, spelt "provider/model", the headers h, in place of those it had; none takes them away.

func SetModelID added in v0.1.2345

func SetModelID(ref, id string) (replaced string, changed bool, err error)

SetModelID lists a provider's model, spelled "provider/model" by the id it is listed by now or by the provider's own, by id instead, and says which of its models had the id before (replaced) and whether anything changed: what magpie lists, picks, groups, routes and records it by, while the provider is still asked for it by its own id. A blank id, or the provider's own, lists it by its own again.

One id is one model of a provider, so an id already given another of its models is that model's no more, which it answers (the latest one given it wins): that model is listed by its own id again. A model of the provider's own id is not listed while another is listed by it, and an agent's or a group's ref to the id reaches the model given it.

What the user picked, grouped, set and said of the model goes with it to the new id: its picks, a key's models, its context, the routing groups' refs and fallbacks, the pickers' lists and every per-model setting — but a setting the user already has under the new id, which stays theirs. Agents' own files are not rewritten: a "provider/<own id>" they still name resolves, and is asked for under that id (Resolve).

func SetModelImage added in v0.1.413

func SetModelImage(ref string, images *bool) error

SetModelImage says whether a provider's model takes images, in place of what its vendor's list says. nil gives that answer back.

func SetModelKind added in v0.1.1225

func SetModelKind(ref, kind string) error

SetModelKind says what a provider's model, spelt "provider/model", makes: KindImage, KindVideo, or "" to leave it to its vendor's list and name.

func SetModelLists added in v0.1.1133

func SetModelLists(ls map[string]ModelList) ([]string, error)

SetModelLists puts each agent's model list back as it was kept, exactly, and tells the agents that keep the models in files of their own once, as a pick made by hand does (catalog.Touched). A model of a provider renamed since is the same model by its new id. It returns the agents whose list changed, sorted.

func SetModelName added in v0.1.137

func SetModelName(ref, name string) error

SetModelName names a provider's model, spelled "provider/model"; an empty name gives it back its own. The agents that keep the models in files of their own are told (catalog.Touched), as for any other change of the catalog.

func SetModelOrder added in v0.1.952

func SetModelOrder(agent string, ids []string) error

SetModelOrder lists agent's models in this order, by entry id: the ones it names first, as it names them, then every other as before; none puts them back in magpie's own order. Only agent's lists follow it.

func SetModelOutput added in v0.1.532

func SetModelOutput(id string, n int) error

SetModelOutput is the most a reply of a provider's model may hold, in tokens, over what the vendor's list and models.dev say; 0 takes the user's away, which DropModelOutput does. The id is spelled "provider/model", or "provider/*" for every model of that provider; setting one has to name a model the provider serves, as one no lookup would ever match reads as set and is not. A removal may name a model that has since gone, or a provider that has: that is the entry left to be cleared.

The agents are told of it (catalog.Touched), as for any change of the catalog: a reply limit is a number they keep in files of their own — Pi's maxTokens, OpenCode's limit — and read at start-up, so one only the gateway knew would leave every agent a reply limit behind.

func SetModelOutputs added in v0.1.876

func SetModelOutputs(providerID string, outs map[string]int) error

SetModelOutputs makes a provider's reply limits outs, by model id, "*" for all of them, as its editor's Max output says (ARNO on Discord: a model's maxTokens was wrong, and only the context window could be set in the editor): those it leaves out are taken away, and every one set or changed has to be a model the provider serves, as for SetModelOutput. One the user set for a model the provider has since stopped listing, sent back as it is, is kept and not refused: the editor is given it (OutputsOf) and sends it again on every Save, so refusing it stopped each Save of that provider, whatever else changed, and the model may be listed again at the next refresh (#3305, LoKi). Taking it out of Max output clears it. Nothing is saved, nor the agents told, when nothing changed.

func SetModelPrefs added in v0.1.648

func SetModelPrefs(pid string, prefs map[string]ModelPref) error

SetModelPrefs makes the changes to a provider's models, by model id, as SetModelName, SetModelEfforts, SetModelImage, SetModelAPI and setModelSame do, and tells the agents once, after them all, rather than once a change. It stops at the first that fails, telling the agents of those made before it.

func SetModelPrice added in v0.1.504

func SetModelPrice(id string, p *catalog.Price) error

SetModelPrice is what a provider's model costs the user, in USD per million tokens, kept in settings' ModelPrices the way a name is. A nil price takes the user's away, leaving the model at what its provider lists and only then at its maker's on models.dev; a price of zero is not that, but a model served at no cost. A price no vendor could charge is refused, naming the part that is wrong.

Unlike the other model preferences this does not tell the agents. What a call costs is not what an agent picks a model by, and the model lists magpie keeps in the agents' own files are not its to rewrite over a number in a cost report.

func SetModelReasonless added in v0.1.1231

func SetModelReasonless(ref string, on bool) error

SetModelReasonless says whether a provider's model, spelt "provider/model", takes no reasoning ask, whatever its list says: on, it offers no levels (Efforts, the agents' lists, a group's) and the gateway sends it no reasoning field on any API — Chat's reasoning_effort, Responses' reasoning, Anthropic's thinking and output_config effort — as it does a model known not to think (yuexian7 on Discord: models.dev lists a model with reasoning, and the vendor answers reasoning_effort with 422 while the request without it works). Off gives it the levels it had again.

func SetModelSpec added in v0.1.1360

func SetModelSpec(ref string, c SpecChange) error

SetModelSpec makes the changes c says to a provider's model, spelt "provider/model", or "provider/*" for every model of that provider (the window and the reply limit only, as `magpie model context` and `output` take it). Every part is checked before anything is written, so a bad one writes nothing; the agents are told once, after them all.

func SetModelSystemPrompt

func SetModelSystemPrompt(ref, text string) error

SetModelSystemPrompt gives a provider's model, spelt "provider/model", the system prompt text, in place of the one it had; "" takes it away.

func SetModelTier

func SetModelTier(ref, tier string) error

SetModelTier sends a provider's model, spelt "provider/model", at tier: "" the usual speed, "priority" or "ultrafast" (see CleanModelTier). Only a model with a fast mode magpie can ask for (CanFast) is switched on.

func SetModels added in v0.1.1134

func SetModels(id string, models []string) error

SetModels gives the provider id the models the user picked for its agents; none gives them the vendor's list again.

func SetNativeCompaction added in v0.1.1243

func SetNativeCompaction(id string, on bool) error

SetNativeCompaction turns a provider's native compaction on or off (Provider.NativeCompaction). One whose wire can't carry it is refused turning it on.

func SetNoStandIn

func SetNoStandIn(id string, on bool) error

SetNoStandIn keeps another model's request off a provider, or lets it stand in for any again (Provider.NoStandIn).

func SetOff added in v0.1.346

func SetOff(id string, off bool) error

SetOff switches a provider off, or on again (see Provider.Off). Saving it brings the model lists written into agents' files up to date.

func SetOnlyPicked added in v0.1.1130

func SetOnlyPicked(agent string, on bool) error

SetOnlyPicked switches agent between being shown every model not taken out of its lists, a new one among them, and being shown only the ones picked for it (#1337). Either way the models it is shown now stay as they are: switched on, they are its picks; switched off, the ones listed for it and not picked are taken out, and a model that comes later is shown again.

func SetOrder added in v0.1.627

func SetOrder(ids []string) error

SetOrder saves the order the providers are listed and tried in, by id. Every id must be a provider's, once; the ones left out follow those named, as they are now, so a provider added later goes after them all.

func SetOwnModelsHidden added in v0.1.1198

func SetOwnModelsHidden(agent string, on bool) error

SetOwnModelsHidden switches agent's pickers between offering its own models beside magpie's and offering magpie's alone.

func SetPickedModels added in v0.1.1130

func SetPickedModels(agent string, ids []string) error

SetPickedModels makes these entries the only ones agent's lists show, for an agent shown only the models picked for it. A pick of an entry not listed for it now (its provider switched off for a while, a model its vendor dropped from the list) is kept, so it is shown again when it is back, as it was picked.

func SetPlainNames added in v0.1.516

func SetPlainNames(on bool) error

SetPlainNames has the agents' model lists name models by their names alone (see Labels), or with their providers' again, and the agents told.

func SetPluginOff added in v0.1.538

func SetPluginOff(_ context.Context, name string, off bool) error

SetPluginOff turns the plugin named off, or back on. A built-in moved onto it stays moved, off with it: nothing moves it back, as the built-in is going. The agent it adds is taken off magpie before it is off (PluginAgentGoing), and stays off when it is on again: the agent's switch puts back the model it was on.

func SetQueue added in v0.1.1009

func SetQueue(id string, limit, wait int) error

SetQueue sets how many requests may wait for each of the provider's keys or accounts, and how long one waits, in seconds; 0 is no bound.

func SetQuotaResetAt added in v0.1.1230

func SetQuotaResetAt(id, at string) error

SetQuotaResetAt sets the time of day the provider's keys out of quota are back, when the vendor doesn't say: "" for none. Setting one lets go of QuotaRest, which it would stand over.

func SetQuotaRest added in v0.1.1214

func SetQuotaRest(id string, minutes int) error

SetQuotaRest sets how many minutes the provider's keys sit out of quota when the vendor doesn't say when they are back, 0 for the gateway's own.

func SetRPM added in v0.1.1119

func SetRPM(id string, n int) error

SetRPM sets how many requests a minute each of the provider's keys or accounts may send, 0 for no limit.

func SetRefreshEvery added in v0.1.1234

func SetRefreshEvery(id, every string) error

SetRefreshEvery sets how often the gateway fetches the provider's list by itself, as ParseRefreshEvery reads it; "off" for only when asked.

func SetRemoteUpdateForTest added in v0.1.3285

func SetRemoteUpdateForTest(id string, out RemoteUpdate)

SetRemoteUpdateForTest keeps out as id's last answer.

func SetRestCap added in v0.1.1230

func SetRestCap(id string, minutes int) error

SetRestCap sets the most, in minutes, the provider's keys and accounts sit out while they keep failing or being rate limited, 0 for the gateway's own, RestCapOff for no rest after an unknown failure.

func SetRestartApp added in v0.1.2826

func SetRestartApp(id string, on bool) error

SetRestartApp has magpie restart the Codex app's app-server when it changes Codex's account by itself, or leave the app on its account till it is restarted (Provider.RestartApp).

func SetRouting added in v0.1.25

func SetRouting(id, routing string) error

SetRouting changes how a provider's requests spread over its keys or accounts.

func SetSearchAPI added in v0.1.587

func SetSearchAPI(a SearchAPI) error

SetSearchAPI adds a search API, last, or changes the one of its vendor where it is; a change with no key keeps the key it has, and one with no Pick the pick it has ("turns" puts the default back). One switched off stays off, and one marked mix stays mixed.

func SetSink added in v0.1.777

func SetSink(id string, sink bool) error

SetSink sends a provider's keys or accounts rate limited with quota left to the back of its order, or lets them keep their place (Provider.Sink).

func SetSuffixMode added in v0.1.595

func SetSuffixMode(mode string) error

SetSuffixMode has the agents' model lists name models as mode says (see Labels), and the agents told when it changes.

func SetSwitchOnly added in v0.1.1224

func SetSwitchOnly(id string, on bool) error

SetSwitchOnly has magpie only move Codex's or Claude Code's own sign-in between its accounts (Provider.SwitchOnly): Codex's requests never sent through the gateway for account failover, Claude's accounts serving no request through the gateway (KeptToAgent). Off, both are as before.

func SetThisDevice

func SetThisDevice(id string, only bool) error

SetThisDevice keeps a provider on this computer, out of sync, or lets it sync again (Provider.ThisDevice).

func SetUpstreamName added in v0.1.560

func SetUpstreamName(ref, name string) error

SetUpstreamName is the name to send a provider for one of its models; an empty name takes the user's away and sends the one magpie knows. A name is only given for a model the provider really serves: a relay lists the model under the id magpie knows it by and asks for it under the vendor's own, and one it does not list is a request magpie would never send, so naming it is refused here, as a price and a limit are for the same id. A "*" stands for every model of the provider rather than for one, and a removal is exempt, so an entry left for a model that has since gone can still be taken away.

A provider magpie asks through an agent's own backend has no model field to put a name in — the request goes out carrying the id the agent knows — so a name given for one of its models would never be sent (asksOwnBackend).

The ref is taken as the provider it names, by its id now, and the name is kept under that id: a ref is as likely to be spelled with an id the provider had before a rename (Was) or with the name it is shown by, and every lookup of a wire name goes by the id the provider has (UpstreamName). A name under any other spelling of the provider is one no lookup will ever match — a name the provider is never asked for, and a removal that takes away nothing.

The key is checked here, where it is given, and not as the whole settings are written: a hand-edited key no lookup will ever match is a no-op of the user's own making, and must not keep every other setting from being saved.

Kept in settings, and saved without telling the agents, like a price: which model an agent picks, and what it is called, have not changed — only the name the request goes out under.

A removal goes to DropUpstreamName, which works off the key rather than off this provider, so that taking a name away is the same operation whether or not the provider it was given for is still there.

A blank name is a removal, and whether there was a name there to take away is DropUpstreamName's to say, not this one's: a caller with something of its own to say about a name that was not there — `magpie model wire -- reset`, which tells a mistyped id from a model already asked for by the name magpie knows it by — asks DropUpstreamName for the removal itself, the way `magpie model price --reset` asks DropModelPrice. A caller that only wants the model left as it is has nothing to tell the user either way, which is why a blank name is an error and not a second answer.

func SetUsageAlias added in v0.1.1358

func SetUsageAlias(from, to string) (changed bool, err error)

SetUsageAlias counts usage of the model from under the name to, or, with to "", under its own id again. Both are model ids as any vendor spells them, matched as the groups magpie finds match them (sameModel: a vendor's prefix, case, "_" or a snapshot date make no difference). It refuses an alias of a model to itself and one that would loop back to from through the others. changed is false when there was nothing to change.

func SetUseFirst added in v0.1.3208

func SetUseFirst(id string, on bool) error

SetUseFirst puts a provider's keys or accounts ahead of the other providers' where Smart weighs them together, or back in Smart's own order (Provider.UseFirst).

func SetWindowAmount added in v0.1.3392

func SetWindowAmount(id, ref string, windows []string, amount float64) error

SetWindowAmount caps the windows named windows of the account ref of the subscription id at amount of their own unit (credits, requests, tokens), in place of a share of their own; 0 lifts it, and the windows follow the account's cap again.

func SetWindowCap added in v0.1.1134

func SetWindowCap(id, ref, window string, cap int) error

SetWindowCap sets the share of the window named window of the account ref of the subscription id: 1–99, 100 for no cap on that window whatever the account's cap, or 0 to have it follow the account's cap again.

func SetWindowCaps added in v0.1.2781

func SetWindowCaps(id, ref string, windows []string, cap int) error

SetWindowCaps is SetWindowCap of several windows at once: a family's models' own (Antigravity's Gemini 3.1 Pro (High) and (Low)), which the GUI shows as one meter.

func ShareGroup added in v0.1.1181

func ShareGroup(id string) (string, error)

ShareGroup is group id as text to paste into another magpie: its members as it names them, its patterns, routing, rules, classifier, effort, context, levels, fast and off members. A group holds no key or account of its own, only provider/model ids, so nothing secret goes with it; what is derived (the models its patterns match now, found, hidden, switched off) stays behind, and so do the rules that hold by a folder, in it or outside it: a folder is a path on the sharer's own machine, which names their projects and means nothing on another.

func ShowAccount added in v0.1.31

func ShowAccount(id string) error

ShowAccount brings back the signed-in account of an agent the user had removed from magpie.

func ShowFor

func ShowFor(agent, id string) error

ShowFor puts entry id back in agent's lists, as the user picks it in one of the agent's pickers where its lists leave it out (a routing group made after the agent was narrowed, or shown only its picks): its provider or group is added to the names the agent is narrowed to, and it is picked for an agent shown only its picks, else no longer taken out. Nothing else in the lists changes.

func ShowGroup added in v0.1.38

func ShowGroup(id string) error

ShowGroup brings back a group magpie found that the user had removed.

func Shows added in v0.1.111

func Shows(names []string, e Entry) bool

Shows reports whether a visibility shows e.

func SignInExpired added in v0.1.1335

func SignInExpired(status int, body []byte) bool

SignInExpired says a reply is the vendor's word that the access token it was sent with has expired, for a refresh to mend.

func SignInHooksPath

func SignInHooksPath() string

SignInHooksPath keeps what the gateway's request hooks were told, apart from the app's notifications' marks (signInAlertPath): the magpie serving the gateway tells its hooks, and the app the user, each once.

func SignInMarked added in v0.1.1213

func SignInMarked(a *Account) bool

SignInMarked says account a is marked revoked: a request is asked of another account first where the gateway picks one alone (compaction).

func SignInRevoked added in v0.1.1213

func SignInRevoked(status int, body []byte) bool

SignInRevoked says a reply is the vendor's word that the sign-in it was sent with is revoked.

func SignOutQianfan

func SignOutQianfan(id string) error

SignOutQianfan forgets the provider's sign-in, and no other's.

func SignOutQianwen

func SignOutQianwen(id string) error

SignOutQianwen forgets the provider's sign-in, and no other's.

func SignOutStepFun added in v0.1.389

func SignOutStepFun(id string) error

SignOutStepFun forgets the provider's sign-in, and no other's.

func SiteOf added in v0.1.1751

func SiteOf(host string) string

SiteOf is the registrable domain of host (a URL's host, with or without its port), lowercased: api.leee.baby:443 is leee.baby. A host on a public suffix's own names (a.vercel.app is vercel.app's tenant a), an address or a name with no suffix (localhost) has none, "".

func Slug

func Slug(name string) string

Slug derives an id from a name: "My Relay" → "my-relay".

func SocketTurn added in v0.1.3397

func SocketTurn(req *http.Request) (ok, shun bool)

SocketTurn says req is a Responses turn that may go over the Responses WebSocket: one to chatgpt.com's Codex backend, or to the Responses URL of a provider whose Socket is set (its ctx made by Via). shun says a refused handshake leaves the host to HTTP for a while.

func SpendExpiringCodexResets added in v0.1.701

func SpendExpiringCodexResets(ctx context.Context)

SpendExpiringCodexResets goes over the Codex accounts the user lets spend their resets and spends one about to run out unused (see check).

func SpentShareOf added in v0.1.641

func SpentShareOf(routing string) float64

SpentShareOf is the share past which routing counts an account spent: SpentShare, but In order sends requests to the first until a window of it is used up or the vendor refuses it, so there an account at 98% is still tried in its turn (#530); Until used up stays on one until then too.

func SplitKeys added in v0.1.930

func SplitKeys(text string) []string

SplitKeys is the keys in text pasted at once: one a line, or separated by commas, semicolons or spaces, trimmed of quotes, each once.

func SplitWords added in v0.1.1272

func SplitWords(split []BalancePart) string

SplitWords is a balance's split on one line, in English, for the TUI and the CLI: "granted ¥10.00 · topped up ¥100.00".

func StaleAllowance added in v0.1.38

func StaleAllowance(agent, user string)

StaleAllowance makes the next Allowances ask the vendor again for user's allowance rather than trust what it last said, or what a reading out now, asked before, comes back with: the account just answered that it has run out.

func StaleKeyAllowance added in v0.1.1086

func StaleKeyAllowance(p Provider)

StaleKeyAllowance has the next KeyAllowance ask the vendor again for p's key's windows rather than trust what it last said: the key just answered that it is out of them.

func StartQianwenSignIn

func StartQianwenSignIn(ctx context.Context, id string) (string, error)

StartQianwenSignIn starts a sign-in to the Qwen AI platform for the provider id: the page the user approves it on, in their browser. magpie waits for the approval itself (QianwenSignInState), until the page runs out.

func StatuslineCard added in v0.1.2883

func StatuslineCard(q Quota, now time.Time) string

StatuslineCard is one account: "claude a@x.com* 5h 62% 7d 41%".

func StatuslineMatches added in v0.1.2883

func StatuslineMatches(q Quota, only []string) bool

func StatuslineText added in v0.1.2883

func StatuslineText(model string, qs []Quota, only []string, now time.Time) string

StatuslineText is the whole line: "→ model" when the session has one, then the cards of qs that only (or the lately served) keeps.

func StepFunBookmarklet added in v0.1.389

func StepFunBookmarklet() string

StepFunBookmarklet is the bookmarklet the user runs on a StepFun platform page they are signed in on: it renews the session as the page does, on either site, and copies it to be pasted into magpie.

func StepFunOrigin added in v0.1.389

func StepFunOrigin(site string) string

StepFunOrigin is the site's platform.

func StepFunSignInURL added in v0.1.389

func StepFunSignInURL(site string) string

StepFunSignInURL is the page the user signs in on, for the site.

func StepFunSignedIn added in v0.1.389

func StepFunSignedIn(id string) bool

StepFunSignedIn reports whether magpie has a sign-in for the provider. StepFunSignedIn reads the file once until it changes: a provider list asks it for each StepFun provider on every poll, and each read was a file open, most often of a file that isn't there. One with a site's session from before #2384 is moved first, under the lock.

func StepFunSite added in v0.1.389

func StepFunSite(p Provider) string

StepFunSite is which of StepFun's platforms the provider's key is for, "ai" or "com", or "" for another vendor.

func StopIdleCodexDaemon added in v0.1.3369

func StopIdleCodexDaemon(ctx context.Context) (bool, error)

StopIdleCodexDaemon stops Codex's app-server daemon for the Codex home magpie signs Codex in through, when it runs with no codex session on it, and says whether it did. An update of Codex by npm on Windows asks it first (agent.UpdateCLI): the daemon, which has no idle exit and which magpie restarts (KeepCodexDaemonCurrent), holds the package's codex.exe, which npm can't remove while it runs (EPERM), and the update stopped partway. The next codex started starts it again. One with sessions on it is left: they hold codex.exe too.

func StoreIcon added in v0.1.10

func StoreIcon(data []byte) (string, error)

StoreIcon keeps a picture (PNG, JPEG, GIF, WebP, ICO or SVG) and returns the Icon value that points at it. The same picture is stored once.

func StoreIconFile added in v0.1.10

func StoreIconFile(path string) (string, error)

StoreIconFile is StoreIcon for a picture on disk.

func StoredGroupOrder added in v0.1.843

func StoredGroupOrder() ([]string, error)

StoredGroupOrder is the order the user put the groups in, as saved; as with Stored, a file that can't be read is an error.

func StoredOrder added in v0.1.638

func StoredOrder() ([]string, error)

StoredOrder is the order the user put the providers in, as saved; as with Stored, a file that can't be read is an error.

func StreamRequired

func StreamRequired(msg []byte) bool

StreamRequired is whether a 400's words say the request must ask for a stream.

func SubmitSignInCallback added in v0.1.415

func SubmitSignInCallback(id, raw string) error

SubmitSignInCallback finishes a browser sign-in whose callback could not reach this machine — the address the browser ended on, pasted — or a plugin's with the code its page showed.

func SubscriptionUsageReading added in v0.1.1076

func SubscriptionUsageReading() bool

SubscriptionUsageReading says a read of the accounts' usage is under way: what SubscriptionUsage just gave may be the stale copy it replaces, for a page to ask again once it lands (#959: the panel, opened, kept the old copy until refreshed by hand, while the window's next read had the new).

func SuffixMode added in v0.1.595

func SuffixMode() string

SuffixMode is how the agents' lists name models: SuffixOn, SuffixOwn or SuffixOff.

func SuffixModeFor

func SuffixModeFor(agent string) string

SuffixModeFor is how the lists of the agent of that id name models: its own mode (AgentSuffix), else SuffixMode.

func SwitchGroup added in v0.1.989

func SwitchGroup(id string, on bool) error

SwitchGroup switches a group of the user's on or off (Group.Disabled). A group magpie found is the catalog's, so it is removed rather than switched off; and one that classifies for another stays on, or that group's rules would have no one to ask.

func SwitchLogin added in v0.1.11

func SwitchLogin(agent, user string) error

SwitchLogin signs an agent in to a remembered account. Sessions of the agent that are already running keep the account they started with until they restart; so does Codex's background app-server, which new Codex sessions attach to (CodexDaemonStale says when it is).

func SwitchOnly added in v0.1.1224

func SwitchOnly(agent string) bool

SwitchOnly reports whether magpie only moves agent's own sign-in between its accounts, sending none of its requests through the gateway for account failover (Provider.SwitchOnly). While providers.json can't be read the user's choice is unknown, and failover, magpie's own idea, is not taken up on it.

func SwitchSearchAPI added in v0.1.1258

func SwitchSearchAPI(vendor string, on bool) error

SwitchSearchAPI switches the vendor's search API on or off (#2286), keeping its key, address and place.

func SwitchSearchKey added in v0.1.3251

func SwitchSearchKey(vendor, ref string, on bool) error

SwitchSearchKey switches one key on or off, keeping its place.

func SwitchWhenSpent added in v0.1.402

func SwitchWhenSpent(ctx context.Context, agent string) (string, error)

SwitchWhenSpent signs agent in to the next of its accounts when the one it is on is spent, or back to the one it moved off once that has room (NextLogin), and answers the account it signed it in to, "" when it stayed.

func SyncClaudeProxyEnv added in v0.1.1212

func SyncClaudeProxyEnv(user string) (string, error)

SyncClaudeProxyEnv has the env of Claude Code's settings.json name the proxy of the account user, the one it is signed in to (see the top of this file), and answers the proxy written, "" when none of magpie's is there now.

func TakesAlibabaAccessKey

func TakesAlibabaAccessKey(p Provider) bool

TakesAlibabaAccessKey says p is on Alibaba Cloud's Token Plan, whose editor then asks for the account's AccessKey ID and Secret.

func TakesBalanceToken added in v0.1.90

func TakesBalanceToken(p Provider) bool

TakesBalanceToken says the provider's vendor tells the account's balance to a token of its own (BalanceToken), which the editor then asks for.

func TakesTencentAccessKey added in v0.1.1182

func TakesTencentAccessKey(p Provider) bool

TakesTencentAccessKey says p is on Tencent Cloud's Token Plan 企业版 (at /plan on TokenHub's hosts), whose editor then asks for the account's SecretId and SecretKey.

func TakesVolcAccessKey added in v0.1.1142

func TakesVolcAccessKey(p Provider) bool

TakesVolcAccessKey says p is on Volcengine Ark (ark.<region>.volces.com), whose editor then asks for the account's AccessKey ID and Secret.

func TakesZhipuTeam added in v0.1.431

func TakesZhipuTeam(p Provider) bool

TakesZhipuTeam says p is a key of Zhipu's or Z.ai's, whose editor then offers the team's organization and project (#236).

func TestAs added in v0.1.1158

func TestAs(ctx context.Context, client string) context.Context

TestAs is ctx with Test and TestModels asking as client asks ("" as magpie does).

func TestOn

func TestOn(ctx context.Context, ref string) context.Context

TestOn is ctx with Test and TestModels asking ref's account or key ("" as routing picks one).

func ThenUses added in v0.1.196

func ThenUses(rules []Rule, q RuleRequest, n int, uses []string) []string

ThenUses are the members the rules after the n-th (from 1) that also match q send to, each once and in the rules' order (a rule's own in its order), leaving out those of uses: who a request a rule sent to uses fails over to before the group's others (#112).

func ThroughSelf added in v0.1.3021

func ThroughSelf(id string) string

ThroughSelf is the model id a request names with a Remote magpie that is this magpie, and left out, taken off the front: rem/own/m1 is own/m1 here, as it is on the other computer, whose agents' picks sync brings over (hanslin1666).

func TokenFieldWanted added in v0.1.2155

func TokenFieldWanted(msg []byte) string

TokenFieldWanted is the field a Chat Completions refusal asks for in place of the one sent, or "": only when its words name it as the one to use, so a limit too high ("max_tokens must be at most 32768") is not read as the wrong name.

func TookOpenedURL added in v0.1.574

func TookOpenedURL(args []string) bool

TookOpenedURL is magpie run as the browser of a `claude auth login` it started: the page is written down for magpie's window to open, and nothing else runs.

func TopUpRateOK

func TopUpRateOK(r float64) string

TopUpRateOK says what is wrong with a provider's top-up rate, "" when nothing: above 0 up to 1000, at most four decimals (¥5 for $70 is 0.0714). None (0) is no rate: no key's group rate is read.

func TuckAccount added in v0.1.773

func TuckAccount(id string, on bool) error

TuckAccount hides a removed account from the Add sheet's "Removed from magpie" too (on), or lists it there again (off). Tucked, it is quiet as well: no reminder line either (#116).

func UltraModels added in v0.1.1270

func UltraModels() map[string]bool

UltraModels are the models one of Codex's accounts offers Ultrafast on.

func UltraOn added in v0.1.1270

func UltraOn(p Provider, model string, ultra map[string]bool) bool

UltraOn is CanUltra with UltraModels read once, for a list of them all.

func UltraPicks added in v0.1.1270

func UltraPicks(agent string) []string

UltraPicks are the fast picks agent's requests for are sent as Ultrafast.

func Unflat added in v0.1.1137

func Unflat(id string) (string, bool)

Unflat is the served id (a provider's model or a routing group) whose flat spelling is id, when exactly one has it. An id with a slash, or with no tilde, is never a flat one.

func UnmaskedBy

func UnmaskedBy(redact string, p Provider) bool

UnmaskedBy says a request to p goes as written under what groups say of masking (Group.Redact, Member.Masking): RedactOn never, RedactOff always, else as p is set.

func Unpicked

func Unpicked(id string) (pid string, ok bool)

Unpicked reports whether id, "provider/model", names a model the user has since unchecked in that provider's list (unpicked), and which provider: Resolve still takes it, so an agent left on it goes on asking the vendor for the old model, while the user picked the provider's others (JNDliuliuM on X: Codex CLI still on it after a restart).

func Unretire added in v0.1.1148

func Unretire(pid, model string)

Unretire takes back a retirement of provider pid's model, when it has one: the vendor answered a request for it.

func Unsaid added in v0.1.1637

func Unsaid(b []byte) (string, bool)

Unsaid describes an HTTP error's body that holds no message of its own: an empty one (NoDetails), or a web page (WebPage). ok is false for any other body, whose message is the vendor's to give.

func Unserved

func Unserved(id string) string

Unserved says why a request can't be put on id, a model or routing group a setting of magpie's names, "" when magpie serves that exact one.

func Unwaited added in v0.1.2531

func Unwaited() (release func())

Unwaited has Allowances answer from what is last known, without the first ask's wait, until release: for a caller that only asks whether a model is there, not which account a request goes to. Every agent's model list asks the gateway whether a model sees images, and the migrations at start read Pi's effort, which builds its list: each agent's first ask waited firstWait for its accounts' usage over the network, and magpie's gateway listened ~9 s after start.

func UpdateRemotes added in v0.1.3285

func UpdateRemotes(ctx context.Context, version string)

UpdateRemotes asks every Remote magpie in use (on, not this one) on an older release than version to update itself, each at most once in remoteUpdateAgain for a version. Nothing is asked from a build that isn't a release, nor while automatic updates are off here: the user keeps this magpie where it is, and its remotes with it.

func UpstreamName added in v0.1.560

func UpstreamName(p Provider, model string) string

UpstreamName is the name to send a provider for one of its models: the one the user gave, for the model or for every model of that provider, else the name magpie knows the model by. Every "*" in the name the user gave is that model, wherever it stands: "vendor-c/*" for a provider's every model sends vendor-c/model-3 for model-3, so one name covers a relay that namespaces its models and still asks for each of them by its own, and "vendor/*/pro" sends vendor/model-3/pro. A name with no "*" in it is that one name for every model of the key, which is the right answer only for a relay that does serve them all alike.

The two are deliberately different things. Everything a user or an agent sees — the catalog, the routing groups' membership, what a call is recorded and priced as — is in magpie's name for the model, so a rename upstream never renames a model here. Only the request that goes out carries the vendor's name, and what a reply says answered is compared with it, so a model asked for by the name the vendor serves it under is not read as another one.

A relay's effort family offered as one model (effort_variants.go) is asked for by the id of its default effort, as a request with no effort is (Provider.SentIDAt): the Test button and the key check try the id the relay lists.

func UpstreamNameAs added in v0.1.560

func UpstreamNameAs(p Provider, model, sent string) string

UpstreamNameAs is UpstreamName for a request that goes out asking for sent, which is not always the model magpie knows: an Antigravity account is asked for the variant of it the effort picks, and that is the id the body carries. The two levels of the lookup are kept apart, since they are about different things. A name given for the model itself is the model's, whichever variant answers for it, so a "*" in it is that model and not the variant: the vendor is asked for the model by the name its owner gave, as it is everywhere else in magpie, and not for a "*" it never heard of. A "*" in the provider's own name is whatever the request is going out under, so one name for a provider asks for gemini-3.7-flash-high and gemini-3.7-flash-low each by its own, rather than for the one id whatever level the effort picked.

func UpstreamNameAsIn added in v0.1.560

func UpstreamNameAsIn(wires map[string]string, pid, model, sent string) string

UpstreamNameAsIn is UpstreamNameAs over a settings' ModelWires already read. A name that is only whitespace is no name, as it is in UpstreamNameIn: the lookup falls through to the level below it, and a request with no name at all goes out under the id it was built with.

func UpstreamNameIn added in v0.1.560

func UpstreamNameIn(wires map[string]string, pid, model string) string

UpstreamNameIn is UpstreamName over a settings' ModelWires already read, for a caller that walks a whole ledger of models in a row. A name that is only whitespace — one an older magpie stored, or one hand-edited into the file — is no name, as it is where one is given.

func UsageAlias added in v0.1.1358

func UsageAlias() func(string) string

UsageAlias names a model's usage after pricing: a found group's public id, then the user's alias. Both group spellings count together, including in old session files. Read once before any usage lock; the returned function reads no settings or providers. It is nil when no names need mapping.

func UsageAliasFor added in v0.1.1358

func UsageAliasFor(id string) (from, to, counted string, ok bool, err error)

UsageAliasFor is the alias the user set for the model id, as settings.json has it (from as written there), and where usage of it is counted in the end, through any alias of that. ok is false when it has none. err is settings.json not read: unknown, not "none".

func UsageAliasIn added in v0.1.1358

func UsageAliasIn(m map[string]string) func(string) string

UsageAliasIn maps only the user aliases m, without the current group catalog.

func UsageAliasKeyed

func UsageAliasKeyed() (func(string) string, string)

UsageAliasKeyed is UsageAlias and the UsageNamesKey of the names it was made from, from one read of them.

func UsageAliases added in v0.1.1358

func UsageAliases() map[string]string

UsageAliases are the aliases the user set, as settings.json has them.

func UsageClaudeVia added in v0.1.558

func UsageClaudeVia(f func(ctx context.Context, configDir string) (string, error))

UsageClaudeVia sets how Claude Code's /usage runs. It returns once no run is still going through the one it replaces.

func UsageNamesKey

func UsageNamesKey() string

UsageNamesKey changes when an alias or a found group's public spelling does, so a cached view never holds the names from before a catalog change.

func UsageRead added in v0.1.1792

func UsageRead(agent, user string) (at time.Time, failed, ok bool)

UsageRead is when user's allowance under agent was last read well, and whether the last try to read it failed (or was held back); ok is false when it hasn't been tried since magpie started. A careful provider holds an account whose reading is too old or failed (Provider.CapCareful).

func UseKey added in v0.1.14

func UseKey(id, keyRef string) error

UseKey makes one of a provider's keys the first, and turns it on; the one it replaces stays on, next in line.

func UsedUp added in v0.1.791

func UsedUp(q SubscriptionQuota, now time.Time) bool

UsedUp is usedUp for the CLI's magpie quota wait, so what it waits out is what stops an account here.

func ValidZone added in v0.1.1524

func ValidZone(name string) bool

ValidZone reports whether name is a time zone a window can be in: an IANA name this magpie knows, or "" for this computer's clock.

func VendorWords

func VendorWords(b []byte) string

VendorWords is what a vendor's error body says in its own words, as APIError reads them but with none of magpie's hints after them: the error's message (with its type and code when the message is only a status line), or the body itself cut short. "" for a body that says nothing (empty), for the caller to say so.

func Verification added in v0.1.304

func Verification(b []byte) (link string, ok bool)

Verification says whether an error body is Google's refusal of an account it wants verified first — Cloud Code Assist's 403 whose details say VALIDATION_REQUIRED (#152) — and the https link to verify it at, when the body has one. The link is taken as Gemini CLI takes it (classifyValidationRequiredError): the google.rpc.Help detail's link first, past a "Learn more" one, then the ErrorInfo's validation_link, then its validation_url.

func VerifyMessage added in v0.1.304

func VerifyMessage(said, link string) string

VerifyMessage is a verification refusal as the agent and the app show it: the vendor's words, then what to do.

func VertexClaude added in v0.1.2196

func VertexClaude(model string) bool

VertexClaude is whether model is one of Anthropic's Claude models on Vertex AI (claude-opus-5-5, claude-sonnet-4-5@20250929), which Google serves on Anthropic's own Messages API at the project, under the anthropic publisher (VertexClaudeRequest), not on generateContent or chat completions. The id alone says so, as the slash says a partner model's: no Gemini id starts so, and Claude's ids have no publisher before a slash.

func VertexClaudeRequest added in v0.1.2196

func VertexClaudeRequest(path string, body []byte) (string, []byte, bool)

VertexClaudeRequest is where at a Vertex AI provider (under its Base(Anthropic)), and with what body, a request made for Anthropic's Messages API at path (/v1/messages, its count_tokens, with or without ?beta=true) goes, as Anthropic's Vertex SDK asks it: a message at /publishers/anthropic/models/<model>:streamRawPredict when it streams, :rawPredict when it doesn't, the model taken out of the body since the path names it; a count at the publisher's count-tokens:rawPredict, the model kept in the body. Either body names anthropic_version (vertex-2023-10-16) unless it has one. ok is false for a body with no model, which has no path.

func VertexForTest added in v0.1.1162

func VertexForTest(root, token, iam string) func()

VertexForTest points Vertex AI at root, Google's token endpoint at token and IAM Credentials at iam until the returned function runs, and forgets the tokens minted. Tests outside this package use it.

func VertexPartner added in v0.1.1929

func VertexPartner(model string) bool

VertexPartner is whether model is one of Vertex AI's partner or open models (Model as a Service: DeepSeek, GLM, gpt-oss, Gemma, Llama…), which Google serves on its OpenAI-compatible chat completions at the project (Base(Chat), …/endpoints/openapi) under a publisher/model id such as deepseek-ai/deepseek-v4.1-flash-maas. Every such id models.dev lists for google-vertex has the publisher before a slash, and no Gemini id on generateContent has one, so the slash is what tells them apart.

func VertexPath added in v0.1.1162

func VertexPath(model string) string

VertexPath is where, after a Vertex AI provider's base, a request for model goes: streamed, as the gateway asks every one there but a Gemini client's own asked whole (VertexWholePath).

func VertexWholePath added in v0.1.1162

func VertexWholePath(model string) string

VertexWholePath is where a request for model answered as one JSON body goes.

func Via added in v0.1.418

func Via(ctx context.Context, id string) context.Context

Via is ctx for requests made on behalf of the provider or signed-in account with id (see Provider.Via).

func ViaLogin added in v0.1.427

func ViaLogin(ctx context.Context, id, user string) context.Context

ViaLogin is ctx for requests made on behalf of the account user of the subscription id (ProxyOfLogin).

func ViaRemoteMagpieAt

func ViaRemoteMagpieAt(ctx context.Context, u *url.URL) context.Context

ViaRemoteMagpieAt is ctx for a request to u made on behalf of the Remote magpie whose gateway u is on (its scheme and host): Via of that provider, so the Library's connection to its MCP router goes as its model calls do (hhdaxia on X: a client certificate the remote asks for went with the model calls alone). ctx as it is when no Remote magpie is at u.

func ViaSignedIn added in v0.1.427

func ViaSignedIn(ctx context.Context, id string) context.Context

ViaSignedIn is ctx for requests made with the sign-in an agent has now (Codex's own, relayed as it came): through the proxy of the account it is signed in to.

func VisibleTo added in v0.1.111

func VisibleTo(agent string) ([]string, bool)

VisibleTo is what agent's lists are narrowed to, and whether they are.

func WBRestricted added in v0.1.1217

func WBRestricted(status int, body []byte) bool

WBRestricted says body is WorkBuddy's refusal of a restricted account: its code 11140 (top level, or under data or error, as a number or a string), or its displayMsg's words. Only for a WorkBuddy answer: another vendor's 11140 is its own.

func WarmClaudeVia added in v0.1.2013

func WarmClaudeVia(f func(ctx context.Context, configDir string) error)

WarmClaudeVia sets how a Claude account's warm-up runs Claude Code.

func WarmNow added in v0.1.2013

func WarmNow(ctx context.Context, agent, user string) error

WarmNow sends agent's ("codex" or "claude") account user the warm-up's one tiny request now, and says why it failed. Once it went, what the account has left is read again, as after a scheduled warm-up.

func WatchQuotas added in v0.1.540

func WatchQuotas(ctx context.Context, wake <-chan struct{}, send func(QuotaAlert))

WatchQuotas reads every allowance and balance while an alert is set, and hands send each one due, until ctx ends. wake, when it gets a value, has it look at once (an alert just turned on).

func WatchSignIns added in v0.1.3309

func WatchSignIns(ctx context.Context, send func(SignInAlert))

WatchSignIns hands send each sign-in alert due, a minute after it starts and every signInAlertEvery after, until ctx ends.

func WebPage added in v0.1.1637

func WebPage(b []byte) (string, bool)

WebPage describes a web page served in place of the API's answer — a firewall's, a CDN's, a relay's own — by its title. ok is false for a body that isn't one.

func Widen

func Widen(agent string, ids []string) error

Widen lets agent's visibility give it these entries, of those it keeps now (whysugarsweet on X: Claude Desktop narrowed to five providers, set from the terminal, never listed OpenCode Go added later, and the Agents page's list had no way to it): each one's provider, or its group, is added to the names the agent is narrowed to, so the provider's other models are listed too, for its list to show or not. When nothing is kept after, the agent is narrowed no more. An id not kept is passed by.

func WindowCapID added in v0.1.1134

func WindowCapID(name string) string

WindowCapID is how a window is known to its cap: its name, trimmed, in lower case.

func WindowTyped added in v0.1.1214

func WindowTyped(id string) bool

WindowTyped says the window agents are told for a model, by its catalog id (as CompactSet takes it), is one the user typed: the group's own size, a group's smallest member's that the user typed (smallestWindow, #2224), its largest member's when it names no size and the user typed that one (largestWindow), or one set on the provider for the model or all of its models. Claude Code then isn't handed magpie's default compaction window for it (CompactFor's rule, as Entry.WindowSet).

func WithAutoPicks added in v0.1.921

func WithAutoPicks(ctx context.Context, onPick func(model string)) (context.Context, func() []AutoPick)

WithAutoPicks has the Auto picks a request is sent with noted: the func returns them. onPick, when set, is told each model the request goes as, for the reply to name the one it went as last.

func WithAutoPrompt added in v0.1.914

func WithAutoPrompt(ctx context.Context, prompt string) context.Context

WithAutoPrompt carries the prompt of the request Copilot's Auto picks a model for: POST /auto picks for a prompt.

func WithCapped added in v0.1.809

func WithCapped(m map[string]SubscriptionQuota) map[string]SubscriptionQuota

WithCapped is m with Capped set on each window an account's usage cap counts, for the GUI to mark the cap and say an account is held at it as routing does — a window one model's own counts for that model, so it is marked as the rest are; the windows are copied, the cache's left as they are.

func WithClientHeaders added in v0.1.2815

func WithClientHeaders(ctx context.Context, id string, h http.Header) context.Context

WithClientHeaders is ctx carrying h, the headers of the agent's request, for Sign to pass on to the provider id those it lists (PassHeaders): that provider's request alone, never another's made under the same ctx.

func WithConversation added in v0.1.2058

func WithConversation(ctx context.Context, c Conversation) context.Context

WithConversation is ctx carrying the conversation its requests are part of, for the headers Sign puts on them.

func WithEffort

func WithEffort(ctx context.Context, effort string) context.Context

WithEffort is ctx carrying the effort a request asks of a plugin's model, which pluginFetch tells the plugin in EffortHeader.

func WithMemberAccount

func WithMemberAccount(member, account string) string

WithMemberAccount is member on account: the member itself for "".

func WithMemberEffort added in v0.1.379

func WithMemberEffort(model, effort string) string

WithMemberEffort is the member id of model at effort: the model itself for "".

func WithModel added in v0.1.3300

func WithModel(ctx context.Context, pid, model string) context.Context

WithModel is ctx carrying the model of provider pid its requests ask, for the headers the user gave that model, which Sign puts on pid's requests alone, never another provider's made under the same ctx.

func WithScheme

func WithScheme(raw, def string) string

WithScheme is a typed address with its scheme made certain: one that is there already, http or https in any letter case, stays (its scheme in lower case) and is never given a second; one with none gets def. A scheme saved twice ("http://http://host", from before this was checked) is one again. Other schemes are left as they are. The rest of the address, its path and trailing slash, is not touched.

func WithStream

func WithStream(body []byte) ([]byte, bool)

WithStream is body, a JSON object that doesn't ask for a stream, asking for one, and whether it changed. Its other fields keep their bytes.

func WithTokenField added in v0.1.2155

func WithTokenField(body []byte, want string) ([]byte, bool)

WithTokenField is body with its reply length named want (MaxTokensField or CompletionTokField), and whether it changed. The key is renamed in place, so the rest of the body keeps its bytes; a body that names both keeps want's value and drops the other.

func WriteExport

func WriteExport(res ExportResult, dir string) ([]string, error)

WriteExport writes the files of res into dir (made 0700 when it is not there), each 0600 and never over a file that is there: a name taken gets -2, -3 … before its extension. It answers the paths written.

func YuanPriced

func YuanPriced() []string

YuanPriced are the ids of the providers that PricesInYuan, for the window to show their costs in yuan; nil when none do.

func YuanPricedSet

func YuanPricedSet() map[string]bool

YuanPricedSet is YuanPriced as a set, for a table of rows looked up one by one (the TUI's and the CLI's).

func ZedBody added in v0.1.632

func ZedBody(body []byte) []byte

Zed's cloud reads an OpenAI model's request into its own Responses types (zed-industries/zed, crates/open_ai/src/responses.rs) before it goes on to OpenAI, and turns the whole request away over anything they don't name: "failed to parse OpenAI Responses API request: unknown variant `developer`, expected one of `user`, `assistant`, `system`, `tool`" on Codex's developer messages. What they take:

  • input items tagged by type: message, function_call, function_call_output, custom_tool_call, custom_tool_call_output, reasoning, compaction, compaction_trigger;
  • a message's role: user, assistant, system, tool; its content a list;
  • a reasoning item's content a list, if there (serde's default is for a missing field, not a null one);
  • tools of type function or custom;
  • include: reasoning.encrypted_content alone;
  • reasoning.summary: auto, concise, detailed.

ZedBody is a Responses request fitted to those, Codex's above all; a request in another API (one with no input list) goes as it came.

func ZhipuCodingBase added in v0.1.1224

func ZhipuCodingBase(base string) (string, bool)

ZhipuCodingBase is the GLM Coding Plan's OpenAI base for base, Zhipu's or Z.ai's pay-as-you-go one (https://open.bigmodel.cn/api/paas/v4 → https://open.bigmodel.cn/api/coding/paas/v4), and whether base is one.

func ZhipuCodingSearch added in v0.1.3014

func ZhipuCodingSearch(p Provider) string

ZhipuCodingSearch is where p, a GLM Coding Plan with a key, searches the web (ZhipuSearchPath on its OpenAI endpoint's host), "" for a provider that isn't one. A plan is known by its OpenAI endpoint, the Coding Plan's /api/coding/paas/v4, on Zhipu's or Z.ai's host or at the zhipu or zai preset's: the Anthropic endpoint is the same for a plan and pay as you go, and the MCP server serves only a plan's key. A key of another plan than p's (KeyAccount.Plan) is asked at its own: see ZhipuSearchKeys.

func ZhipuEnveloped added in v0.1.1252

func ZhipuEnveloped(req *http.Request, res *http.Response) *http.Response

ZhipuEnveloped is res, or — when it is a 2xx from Zhipu or Z.ai holding the platform's refusal envelope — the refusal at its status, with the body as their OpenAI API words one. A stream, a compressed body and every other host's reply pass as they came.

func ZhipuKeyRefused added in v0.1.1252

func ZhipuKeyRefused(code int) bool

ZhipuKeyRefused says whether an envelope's code is Zhipu refusing the key itself (1000–1005: not taken, missing, expired, needs a second factor), not the request.

func ZhipuNoBalanceHint added in v0.1.1224

func ZhipuNoBalanceHint(from, coding, said string) string

ZhipuNoBalanceHint says what a 1113 at the pay-as-you-go endpoint from means when the Coding Plan's endpoint coding didn't serve the key either (said is what it answered), and what to change.

func ZhipuSearches added in v0.1.3014

func ZhipuSearches(p Provider) bool

ZhipuSearches is whether a key of p in use is on a GLM Coding Plan (ZhipuSearchKeys has one), read from the keys themselves: the gateway asks it for every request, and KeysOn is counted per list.

Types

type Account

type Account struct {
	Agent string `json:"agent"`          // the agent's id: codex, copilot
	User  string `json:"user"`           // who is signed in: an email, a GitHub login
	Plan  string `json:"plan,omitempty"` // the subscription, when the agent says

	// Stream is set when the backend only streams; magpie then translates
	// a non-streaming request instead of relaying it.
	Stream bool `json:"-"`

	// Home is where a Grok, Kiro or Devin account keeps its sign-in: the
	// agent's own (the CLI's home for Grok, "" for Kiro and Devin), or one
	// of magpie's for a further account (grok_accounts.go, kiro_accounts.go,
	// devin_accounts.go).
	Home string `json:"-"`
	// contains filtered or unexported fields
}

Account is the signed-in agent behind a provider.

func (*Account) AgentsOwn added in v0.1.648

func (a *Account) AgentsOwn() bool

AgentsOwn says the account is the one the agent itself is signed in to, run in the agent's own home with what it keeps there, not with a sign-in magpie hands it. Which account that is moves with a switch (SwitchLogin): a Claude Code started on it before goes on as whatever Claude Code is signed in to by then, as it reads its keychain again every half minute.

func (*Account) Levels added in v0.1.635

func (a *Account) Levels(model string) (levels []string, ok bool)

Levels are the reasoning levels the account's own list gives the model — a Free ChatGPT plan's may be fewer than a Plus one's — and ok is false when that list wasn't fetched, doesn't have the model or gives it none.

func (*Account) Lists added in v0.1.35

func (a *Account) Lists(model string) bool

Lists reports whether the account's plan has the model, as far as magpie knows: one whose list was never fetched is taken to have them all.

func (*Account) StandIn added in v0.1.623

func (a *Account) StandIn() bool

StandIn says the account is a saved one served in the place of the agent's own sign-in, which is signed out.

func (*Account) Tiers added in v0.1.1122

func (a *Account) Tiers(model string) (tiers []string, ok bool)

Tiers are the service tiers the account's own model list offers on model, when its list says: a list that gives no model a tier doesn't say, as one fetched before ChatGPT listed them.

func (*Account) Token added in v0.1.14

func (a *Account) Token(ctx context.Context) (tok string, ok bool, err error)

Token is the access token of a saved account in use beside the agent's own — for a Claude account, the config directory Claude Code runs on it in; ok is false for the agent's own, which the agent signs itself. A Claude account that can't be used, Anthropic having refused its sign-in, is an error, whichever it is (claude_auth.go).

func (*Account) Unnamed added in v0.1.1552

func (a *Account) Unnamed() bool

Unnamed says the account is Claude Code's own sign-in known by no name yet: its User is made from its plan, and it is named by its email once Claude Code's first run has put its profile in Claude Code's config.

func (*Account) UsageAgent added in v0.1.514

func (a *Account) UsageAgent() string

UsageAgent is the agent an account's allowance is asked for by (LoginUsage, Allowances): a plugin's accounts by their provider's.

type AccountOn added in v0.1.3223

type AccountOn struct {
	Provider
	Own  bool
	Rank int
}

AccountOn is one of a signed-in provider's accounts a request may take: Own is the one the agent is signed in to, Rank its place in the user's order.

type AccountRef added in v0.1.1076

type AccountRef struct {
	ID   string
	User string
	Plan string
	Key  bool // one of the provider's keys, not a signed-in account
}

AccountRef is one of a provider's accounts or keys as a gateway key's account list knows it (#905): ID what the list keeps — an account's stable id, kept through renames, a key's fingerprint — User and Plan what it is shown as.

func (AccountRef) Shown added in v0.1.1326

func (a AccountRef) Shown(p Provider) string

Shown is how the account or key a is shown on p: an account by the name the user gave it, a key by its own name.

type AgentModels

type AgentModels struct {
	Agents map[string]map[string]string `json:"agents"`
}

AgentModels is what a magpie tells of its agents' models: by agent id, each model field's key and the catalog ref it is on there (group/smart, deepseek/deepseek-chat).

type Allowance added in v0.1.29

type Allowance []Limit

Allowance is an account's allowance windows as last known.

func ClaudeAllowanceForTest

func ClaudeAllowanceForTest(ls []ClaudeLimit, now time.Time) Allowance

ClaudeAllowanceForTest is the allowance routing weighs for limits as Claude Code told them, for the gateway's tests.

func FactoryAllowanceForTest added in v0.1.1227

func FactoryAllowanceForTest(limits []byte, now time.Time) Allowance

FactoryAllowanceForTest is the allowance an account's /api/billing/limits answer gives routing, for the gateway's tests.

func KeyAllowance added in v0.1.1086

func KeyAllowance(p Provider) (Allowance, bool)

KeyAllowance is the provider's key in use's own usage windows as last read, asked for again in the background when that was over a minute ago; ok is false for a key without any, or one not read yet. It never waits: a key not read yet goes by the last reading on its card, else counts as not known.

func PluginAllowanceForTest added in v0.1.1227

func PluginAllowanceForTest(usage []byte, now time.Time) Allowance

PluginAllowanceForTest is the allowance a plugin's usage answer gives routing, for the gateway's tests.

func RemoteAllowance

func RemoteAllowance(p Provider, model string, ask bool) (a Allowance, inner string, ok bool)

RemoteAllowance is what the Remote magpie p has left for model, its id there ("claude/claude-sonnet-5-5"), by the card of the provider serving it there ("claude"; "relay" for "relay/strata/m" when no card of relay/strata is told), as last read from p. inner is model as that card counts it ("claude-sonnet-5-5"). Of several accounts there, the one with the most left for the model: the other magpie's own routing sends it there. ok is false when nothing is known.

It never waits. With ask, cards older than remoteCardsFor, or none, are asked for in the background (the other magpie answers from what it keeps, asking no vendor), and what was read stands meanwhile: routing asks only when it weighs p against another, so a request to one Remote magpie alone sends it nothing more.

func RemoteSeat

func RemoteSeat(p Provider, model string, ask bool) (a Allowance, inner string, free, ok bool)

RemoteSeat is RemoteAllowance, with whether the account its allowance is of is signed in to a free plan there: a subscription's card whose plan FreePlan names free. Free quota by expiry spends it before a paid one, as it does an account of this magpie's own (#6708: weighRouted asked only Account.Plan, which a Remote magpie has none of).

func (Allowance) CapHeld added in v0.1.809

func (a Allowance) CapHeld(model string, caps WindowCaps, now time.Time) *CapHold

CapHeld says how an allowance, as last known, holds the account for model at now: some window counting model at or past its own share of caps (WindowCaps.Of), not renewed since; nil when none is. A window whose reset has passed is empty again; no caps hold nothing.

func (Allowance) CapUsed added in v0.1.2920

func (a Allowance) CapUsed(model string, now time.Time) float64

CapUsed is For's share over the windows that count model other than a budget known to run a day or longer: a rate cap (the five hours), or a window that doesn't say how long it runs. Smart and Use before expiry hold an account back at routes.LowShare of these only: a rate cap near full refuses the requests sent into it before the allowance is read again, while what a week has left is lost at its reset, so a week at 90% renewing today is spent first, not kept for last (ysicing_01858 on Discord). A window whose reset has passed is empty.

func (Allowance) Count added in v0.1.738

func (a Allowance) Count(model string, now time.Time) (amount, of float64, unit string)

Count is the count of the window For's share is of — the fullest that counts model — when the vendor counts it (WorkBuddy's credits): how much of of is used, in unit; of is zero when it isn't counted so. A window whose reset has passed is empty again.

func (Allowance) For added in v0.1.38

func (a Allowance) For(model string, now time.Time) (used float64, renews []time.Time)

For is what an allowance leaves a request for model at now: the share used of the fullest window that counts it, and when those windows renew, the biggest first — the longest, the week before the five hours in it. A window whose reset has passed is empty again, its next reset not known.

func (Allowance) Full added in v0.1.38

func (a Allowance) Full(model string, share float64, now time.Time) time.Time

Full is when an account used up for model can take it again: the last reset of its windows that are full, zero when none is or it isn't known.

func (Allowance) Fullest added in v0.1.1210

func (a Allowance) Fullest(model string, now time.Time) time.Time

Fullest is when the window For's share is of renews: the fullest that counts model, the later of those as full. A display pairs the two, so it names one window: a Factory account 32% into its week and 16% into its month is 32% used, renewing with the week, not the month (#1778). Zero when that window's reset isn't known, or has passed (it is empty again then, its next reset not known).

func (Allowance) FullestName

func (a Allowance) FullestName(model string, now time.Time) string

FullestName is the name of the window For's share is of (Fullest's), when more than one window counts model: the share alone ("41% used") read as the five hours on the Routing page while it was the week's, the five hours at 0% (Wing8Aqua on X). Empty when one window, or none, counts it, or the vendor didn't name it.

func (Allowance) Lapse added in v0.1.1678

func (a Allowance) Lapse(model string, now time.Time) time.Time

Lapse is the soonest moment credits left in a window that counts model are lost (Limit.RunsOut), zero when none is told or all have passed. Smart goes by it when the renewals tie: two WorkBuddy free accounts renew together, at the end of the month every one shares, but the credits one was given lapse before the other's, and spent first they aren't lost (zhaocai_83020 on Discord). Renewal already takes it when it comes before the window renews; this tells apart those that come after.

func (Allowance) Lapsing

func (a Allowance) Lapsing(model string, now time.Time) float64

Lapsing is the share of an allowance, in points of the 0–100 used share, that is lost soon whatever is done: what a window that counts model loses at RunsOut (RunsOutLeft of Of, never more than it has left), when that is within lapseHorizon. Credits that are lost unspent cost nothing to spend, so a ranking by the share used takes them off it, and an account whose month is half used but whose check-in credits lapse tomorrow is not kept behind a fresh one (kudi3699 on X). Zero when no window says how much lapses: the amount is never guessed from what is left. The most of any window's, as they overlap.

func (Allowance) Left added in v0.1.1790

func (a Allowance) Left(model string) (left float64, unit string, ok bool)

Left is how much a wallet that counts model has left, in unit (Limit.Balance): the least of its windows that tell a balance. ok is false when none does. Only balances in the same unit of one provider are compared (routes.Seat.Left).

func (Allowance) NearCap added in v0.1.1792

func (a Allowance) NearCap(model string, caps WindowCaps, points float64, now time.Time) bool

NearCap says whether an allowance, as last known, has some window counting model within points of its own share of caps (or past it) at now, not renewed since: a careful provider reads such an account again before it is sent a request (Provider.CapCareful). No caps are near nothing.

func (Allowance) OnCredits added in v0.1.1339

func (a Allowance) OnCredits() bool

OnCredits says whether the account goes on past its allowance on its credits, as its last reading says (a ChatGPT account holding them, QuotaWindow.Credits): a window used up doesn't stop it. Whether it is let spend them is the user's (CodexCredits).

func (Allowance) Pace added in v0.1.644

func (a Allowance) Pace(model string, now time.Time) (pace float64, due time.Time)

Pace is the share of its week an account has left for model, per hour until that week renews: the rate it would have to be used at to spend the week just in time, so the account with the highest has the most to lose at its reset. Of several budget windows that count the model (Opus's own beside the general), the tightest; due is when that one renews, zero when it isn't known. A window not started, or whose reset isn't known, is taken to run its whole span from now; one that doesn't say how long it runs (a plugin may not) is a budget, for as long as its reset says, else a week. The hours until a reset are never taken as fewer than one, or a window a minute from renewing would outweigh all the rest. An account whose vendor tells no budget window, only a short one (Claude Enterprise's five hours), has nothing longer to keep for: what its five hours have left is lost at their reset, so it goes by that, per hour until then — the whole span when not started (#576): ahead of nearly every week, behind only one with more of it to lose sooner. Where the reading may leave a week out (a Claude account only heard of as Claude Code answered, partial) it is instead taken to have a week not started with the share its fullest window has used: those go by what they have used, among the rest as the fresh are. An account whose windows an auto-used reset starts again sooner than they renew (Restarts) goes by that instead, and due is then that time: what it has left is lost there. Credits in a budget window that expire before it renews (Limit.RunsOut) are lost sooner still: the window goes by those that expire first, per hour until they do, when that is the more — what expires as a share of the window (RunsOutLeft of Of), or all it has left when the amount isn't told, as Renewal takes it. A WorkBuddy account whose check-in credits expire tomorrow goes ahead of one whose month has more left but nothing expiring (lcyksp on Discord); due is then the expiry.

func (Allowance) Pooled added in v0.1.1046

func (a Allowance) Pooled(model string, share float64, now time.Time) bool

Pooled says whether a refusal of model for its allowance leaves the account's other models alone: the windows that count model and are full at share are each of some models only (Opus's own week, Cursor's Other Models pool) — or, none known full, no window of the whole account counts it, only pools. Then it is that model which is out, not the account: Cursor's Other Models used up leaves Auto and Composer in theirs (Xiaopodev on X).

func (Allowance) Renewal added in v0.1.670

func (a Allowance) Renewal(model string, now time.Time) []time.Time

Renewal is For's renews as routing ranks them: a window not started, or whose reset has passed, that says how long it runs is taken to renew that long from now — a five hours not started renews within five hours, the soonest of an account that has nothing longer (#576). One whose credits left run out before it renews (Limit.RunsOut) renews then, as what is left is lost then all the same: WorkBuddy's accounts, whose credits have no reset, go by the package that ends first (cdredfox on X).

func (Allowance) Restarts added in v0.1.792

func (a Allowance) Restarts(now time.Time) time.Time

Restarts is when an auto-used reset starts the account's windows again, as the Codex reset about to run out is spent (expiringResetSpent): resetLead before it runs out, or now when the account is held up past then. What they have left then is lost, as at their own reset, so Use before expiry and Smart take it for their renewal when it comes sooner (#717, #718). Zero when none will be.

func (Allowance) Scoped

func (a Allowance) Scoped(model string) bool

Scoped says whether some window of the allowance counts some models only and counts model: Opus's or Fable's own week. A refusal of model with none of its windows read full may be that window's, read before it filled.

func (Allowance) Unreached added in v0.1.3269

func (a Allowance) Unreached(model string, now time.Time) int

Unreached is how many of Renewal's windows, the biggest first, Smart passes over, ranking the account by the next one: a window whose left the next shorter window can no longer let through before it renews, once that one renews, unless what that one has left is used first. Both are counted in one unit (Limit.Of): a Volcengine Agent Plan's month of 20,000 with 18,372 left, renewing two weeks after its week of 7,000 does, can take at most 14,000 after the week renews, so what the week has left is lost at its reset as a weekly plan's is, and it ranks by its week (#5639, louisgreen0726). While the weeks still to come can carry what the month has left, the month is the real cap, as when the month holds less than its weeks add up to (#1778), and it ranks by the month as before. A week partly before the month renews counts for the share of it that is. Only a budget window ranks so (budgetSpan): what five hours leave at their reset is never taken for lost, as everywhere in Smart. Windows that don't tell their counts, or tell them in different units, are never compared: 0.

func (Allowance) WeekUsedUp added in v0.1.1977

func (a Allowance) WeekUsedUp(now time.Time) bool

WeekUsedUp says whether the allowance's week, a window of a day or more that counts every model, is used up at now, as its last reading says: weekUsedUp's rule (AutoUseCodexReset) on an allowance, credits or none.

type AppImport added in v0.1.25

type AppImport struct {
	Ref      string   `json:"ref"`            // stable within its source
	From     string   `json:"from,omitempty"` // where in the app: Claude Code, Codex…
	Provider Provider `json:"provider"`
	// Status is "new", "same" (magpie has it already: same endpoint and
	// key) or "taken" (its id is another provider's here).
	Status   string `json:"status"`
	Existing string `json:"existing,omitempty"` // the magpie provider it matches or collides with
	// KeyOf is a magpie provider at the same address with another key:
	// this one can join it as one more key instead of being a provider
	// of its own.
	KeyOf string `json:"keyOf,omitempty"`
	// Reserved: its id is a subscription's (claude, workbuddy…), whose
	// name it happens to have. It can't replace that subscription, only
	// come in as a provider of its own beside it.
	Reserved bool   `json:"reserved,omitempty"`
	Off      string `json:"off,omitempty"`  // why it isn't picked by default
	Skip     string `json:"skip,omitempty"` // why it can't be imported at all
}

AppImport is one provider an app holds, as magpie would add it.

type AppPick added in v0.1.25

type AppPick struct {
	Source string `json:"source"`
	Ref    string `json:"ref"`
	Mode   string `json:"mode,omitempty"`
	Name   string `json:"name,omitempty"`
}

AppPick is one entry the user chose, and how it comes in: as a provider ("add", beside any with its id), in place of the one with its id ("replace"), or as one more key of the provider KeyOf names ("key"). Name is the name the user gave it in the picker, when its own collides with one magpie has (#1487); a renamed entry is added, never replaces.

type AppSource added in v0.1.25

type AppSource struct {
	ID    string      `json:"id"`   // cc-switch, alma
	Name  string      `json:"name"` // as the app calls itself
	Path  string      `json:"path"` // the file read
	Found bool        `json:"found"`
	Error string      `json:"error,omitempty"`
	Items []AppImport `json:"items"`
}

AppSource is one app magpie can import from, with what it holds.

func DiscoverSources added in v0.1.1256

func DiscoverSources() []AppSource

DiscoverSources reads the apps the Providers page looks in by itself: those not read only when asked.

func ImportSources added in v0.1.25

func ImportSources() []AppSource

ImportSources reads every app magpie can import from, as the user asked.

type AutoPick added in v0.1.921

type AutoPick struct {
	Model   string `json:"model"`
	Via     string `json:"via"`
	Skipped string `json:"skipped,omitempty"`
	Refused string `json:"refused,omitempty"`
	API     string `json:"api,omitempty"`
	Session bool   `json:"session,omitempty"`
}

AutoPick is a model Copilot's Auto picked for a try of a request: where the pick came from, why not from /auto when it didn't, and Copilot's refusal of it, which the route shows (#256: a Student plan's picks were refused, the tries logged as "auto"). API is the path it was sent to (/responses, /chat/completions), Session whether Auto's session token went with it.

type BalanceEstimate added in v0.1.3281

type BalanceEstimate struct {
	Set   float64   `json:"set"`
	At    time.Time `json:"at"`
	Spent float64   `json:"spent"`
	// Currency is the amount's, "cny" when typed in yuan, else unset (USD)
	Currency string `json:"currency,omitempty"`
	// Rate is the yuan a dollar is counted at, for one in yuan
	Rate float64 `json:"rate,omitempty"`
	// Left is what is left, in Currency; nil while it can't be told (in
	// yuan with spend counted and no rate ever learned)
	Left *float64 `json:"left"`
	// From is what the spend is counted from: At, or the last refill
	From   time.Time  `json:"from"`
	Refill *Refill    `json:"refill,omitempty"`
	Next   *time.Time `json:"next,omitempty"`
	// Expiring is the grants of credit that expires not expired yet,
	// the soonest to go first
	Expiring []ExpiringLeft `json:"expiring,omitempty"`
	// Expired is the end of the last grant that has expired and still
	// tells what the rest paid; Left no longer counts it
	Expired *time.Time `json:"expired,omitempty"`
}

BalanceEstimate is what a card shows of a balance typed by hand: the amount typed (in Currency), when, and what magpie counted spent on the key since (in USD), from the last refill when it refills.

type BalancePart added in v0.1.587

type BalancePart struct {
	Label   string   `json:"label,omitempty"`
	Text    string   `json:"text"`
	Percent *float64 `json:"percent,omitempty"`
	// Error is why the amount couldn't be read, its Text then "—".
	Error string `json:"error,omitempty"`
	// Expires is when the part counts no more, for a balance typed with
	// credit that expires (key_balance_own.go); the GUI says in how many
	// days, its Label then empty
	Expires *time.Time `json:"expires,omitempty"`
}

BalancePart is one amount of a balance field, for a card to show each of several on a line of its own, its label apart from its figure, rather than all of them run together: Percent is its share, 0 to 100, when it was asked as one ("%" after it), for a meter.

type BalancePoint added in v0.1.1050

type BalancePoint struct {
	At     time.Time `json:"at"`
	Amount float64   `json:"amount"`
}

BalancePoint is one reading of a balance: Amount was left at At.

type BalanceTrend added in v0.1.1050

type BalanceTrend struct {
	Points   []BalancePoint `json:"points"`
	FitFrom  *time.Time     `json:"fitFrom,omitempty"`
	FitStart float64        `json:"fitStart,omitempty"`
	FitNow   float64        `json:"fitNow,omitempty"`
	PerDay   float64        `json:"perDay,omitempty"`
	RunsOut  *time.Time     `json:"runsOut,omitempty"`
	// Currency is the sign the points are in ("$"), set when the balance
	// is told in several currencies and the points are only the first's
	Currency string `json:"currency,omitempty"`
}

BalanceTrend is a balance's points over balanceShowSpan, oldest first, and the line fitted through the latest of them: spent PerDay a day, from FitFrom (the amount FitStart then) to now (FitNow), running out at RunsOut. With no fit (too few points, or a top-up just now) only Points.

type Bare added in v0.1.1226

type Bare struct {
	ID string
	Of int
}

Bare is a row a list adds for a bare id: ID, and Of, the index in the list of the entry a request for it reaches.

func BareEntries added in v0.1.1226

func BareEntries(shown []Entry) []Bare

BareEntries are the rows a list of shown adds for the bare ids, in the order the models first appear in shown, each once, then the routing groups the user made, by their own ids (groupBare).

type CapHold added in v0.1.1134

type CapHold struct {
	Used    float64
	Cap     int
	Back    time.Time
	Credits bool
	// Amount is the cap when the fullest window holding it is capped at a
	// fixed amount (AccountWindowAmounts): Count of it used, in Unit. Cap
	// is then that amount as a share, rounded up.
	Amount, Count float64
	Unit          string
}

CapHold is how an account is held by its caps for a model: the share used of the fullest window holding it, that window's cap, when the last of those windows renews (zero when one doesn't say), and Credits when only the credits hold it, at 100%.

type CheckinAccount added in v0.1.1224

type CheckinAccount struct {
	Key  string `json:"key"`
	By   string `json:"by"`
	User string `json:"user"`
	On   bool   `json:"on"`
}

CheckinAccount is an account a daily check-in reaches, for Settings: its entry in its vendor's file (Key, which settings.CheckinOff names), the vendor (By, as WorkBuddyCheckin's), and whether it is checked in while its vendor's check-in is on (#1902, magicLaLa: 根据每个账号设置是否开启 自动签到).

func CheckinAccounts added in v0.1.1224

func CheckinAccounts() []CheckinAccount

CheckinAccounts are the accounts in use that each vendor's check-in reaches, WorkBuddy's, Trae CN's, MiniMax Code's, Qoder's and the plugins' that check in themselves, each once; asks nothing.

type ClaudeLimit added in v0.1.199

type ClaudeLimit struct {
	Kind     string
	Used     float64
	ResetsAt int64
}

ClaudeLimit is one allowance window as Claude Code tells it: its kind (five_hour, seven_day, seven_day_opus, seven_day_sonnet, seven_day_overage_included), the share used, 0–1, and when it renews, in Unix seconds (0 when not said).

func KeptClaudeLimits added in v0.1.1113

func KeptClaudeLimits(user string) []ClaudeLimit

KeptClaudeLimits is what is kept of user's allowance as of now, in the windows Claude Code names (ClaudeLimit's kinds), each that says when it renews: what Claude Code last said as it answered, or its /usage read. Nil when nothing is kept.

type CodexDaemonCheck added in v0.1.1151

type CodexDaemonCheck struct {
	// Behind: a daemon runs that started before what it reads changed
	Behind bool
	// Since is when that daemon started
	Since time.Time
	// Attached is how many codex sessions may be on it, which magpie
	// doesn't restart it under
	Attached int
	// Restarted: magpie restarted it, and new sessions get the new list
	Restarted bool
	Err       error
}

A CodexDaemonCheck is what KeepCodexDaemonCurrent found and did.

func KeepCodexDaemonCurrent added in v0.1.1151

func KeepCodexDaemonCurrent(ctx context.Context, home string, changed time.Time) CodexDaemonCheck

KeepCodexDaemonCurrent restarts the managed app-server of the Codex home home when it started before changed (when magpie last changed what Codex reads at start) and no codex session is attached to it. One that can't be found or timed, or a restart already under way, is left as it is.

type CodexLimit added in v0.1.1118

type CodexLimit struct {
	Used   float64
	Span   time.Duration
	Resets time.Time
}

CodexLimit is one of an account's windows as a reply tells it: the share used (0–100), how long the window runs, and when it renews (zero when not said).

type CodexWarm added in v0.1.182

type CodexWarm struct {
	User    string   `json:"user"`
	Windows []string `json:"windows"`
	Err     string   `json:"error,omitempty"`
}

CodexWarm is what came of looking at one account: the windows it was sent a request for, and why that failed.

type Cond

type Cond struct {
	// Field is what the condition looks at: one of CondFields.
	Field string `json:"field"`
	// Op is how: one of the field's CondOps.
	Op string `json:"op"`
	// Value is what it is compared with: a length in tokens; off, on or a
	// reasoning level; agents, comma separated; the text to find in the
	// message. A subagent condition has none.
	Value string `json:"value,omitempty"`
}

Cond is one condition of a rule's Where.

func ParseCond

func ParseCond(s string) (Cond, error)

ParseCond reads a typed condition: "effort is not off", "tokens < 20k", "agent is not codex,opencode", "subagent", "not subagent", "message contains run the tests".

func (Cond) Holds

func (c Cond) Holds(q RuleRequest) bool

Holds reports whether the request is as the condition says.

func (Cond) Text

func (c Cond) Text() string

Text is the condition as a rule's conditions show it.

func (Cond) Words

func (c Cond) Words() string

Words is the condition as ParseCond reads it back: "effort is not off", "tokens < 20000", "not subagent".

type Conversation added in v0.1.2058

type Conversation struct{ Session, Thread, Subagent string }

Conversation is what ${sessionId}, ${threadId} and ${subagentId} stand for in a request: Thread "" is the session's own thread; Subagent is the Claude Code subagent the request is of (x-claude-code-agent-id), "" on the conversation's own turns, which never send it.

func OwnConversation added in v0.1.2058

func OwnConversation(prefix string) Conversation

OwnConversation is a conversation of a request's own: prefix and 12 random letters, its thread the same.

type DailyCredits added in v0.1.664

type DailyCredits struct {
	// Since is the day magpie first read the account's credits: the days
	// before it aren't known, not unused.
	Since string `json:"since"`
	// Days are the days of the last creditsShown with credits used, oldest
	// first.
	Days []DayCredits `json:"days"`
	// Window is the card's window they are of ("Credits", "Add-on
	// credits"), and Unit a currency's code when it counts money ("usd"),
	// "" when credits.
	Window string `json:"window,omitempty"`
	Unit   string `json:"unit,omitempty"`
}

DailyCredits is what one of an account's credits windows went to day by day.

type DayCredits added in v0.1.664

type DayCredits struct {
	Day  string  `json:"day"`
	Used float64 `json:"used"`
}

DayCredits is one day's credits used ("2006-01-02", the local day).

type Deleted added in v0.1.1776

type Deleted struct {
	ID   string    `json:"id"`
	Name string    `json:"name,omitempty"`
	Icon string    `json:"icon,omitempty"`
	At   time.Time `json:"at"`
	Was  []string  `json:"was,omitempty"`
	Gave []Gave    `json:"gave,omitempty"`
	// Into is the provider the user merged its calls into on the Usage
	// page (MergeDeleted): they are listed and counted as that one's,
	// priced as they were (Renames.Own). Only this record is merged, so
	// a provider added under its id later keeps its own calls. A provider
	// deleted under Into after MergedAt ends the merge.
	Into     string    `json:"into,omitempty"`
	MergedAt time.Time `json:"mergedAt,omitzero"`
	// Label is the name the user gave it on the Usage page (NameDeleted),
	// shown instead of Name.
	Label string `json:"label,omitempty"`
}

Deleted is a provider the user deleted (Delete): the calls recorded under its id, and under the ids it had (Was, Gave), until it was deleted are its own, under its id while no other has taken it and under UsageID once one has, never a provider's added later under the same id. cybercaius on Discord: a provider deleted and another added under its id showed as one on the Usage page.

func (Deleted) Shown added in v0.1.1807

func (d Deleted) Shown() string

Shown is the name the Usage page lists it by: the user's Label, its own name, or its id.

func (Deleted) UsageID added in v0.1.1776

func (d Deleted) UsageID() string

UsageID is the id its calls are counted under: its id and when it was deleted, which no provider can take ("~" is never in one, Slug).

type Detection added in v0.1.663

type Detection struct {
	Result
	// Base is the URL the provider keeps for it, as the editor's fields
	// take it: …/v1 for OpenAI's two, the root for Anthropic's, …/v1beta
	// for Gemini's.
	Base string `json:"base"`
}

Detection is what one API answered at the URL it was asked at.

type DevinFamily added in v0.1.45

type DevinFamily struct {
	UID     string
	Label   string
	Aliases []string
	Models  []catalog.Model
}

DevinFamily is one entry of `devin models list`: a name that follows the family's newest model, and the pinned variants under it.

func DevinFamilies added in v0.1.45

func DevinFamilies(ctx context.Context) ([]DevinFamily, error)

DevinFamilies is the CLI's model list, kept a few minutes: the picker and the provider ask for it often and `devin models list` spawns a process that takes seconds (switching Claude Code's model took 5–10s while every state asked it anew). A list past its time is served as it is while it is read again in the background; only a caller with nothing known yet waits, and not one marked DevinNoWait.

type Entry

type Entry struct {
	ID      string `json:"id"`                // what the agent sends magpie
	Model   string `json:"model"`             // what magpie sends the vendor
	Name    string `json:"name"`              // the user's name for it, when they gave one (SetModelName)
	Default string `json:"default,omitempty"` // the model's own name, when the user gave it another
	// Plain is a remote magpie's model's name there alone, when Name is
	// its label there with that magpie's provider after it (catalog.Model's)
	Plain string `json:"-"`
	// By is the provider a remote magpie's list names as serving the
	// model there, the first in a chain of magpies (catalog.Model's)
	By         string    `json:"-"`
	Efforts    []string  `json:"efforts,omitempty"`
	Provider   *Provider `json:"-"`                // a group's: its first member's; shared, read only
	Group      string    `json:"group,omitempty"`  // set on a routing group (group.go)
	Named      bool      `json:"-"`                // a routing group the user made or changed: its name is theirs (Labels)
	Icons      []string  `json:"-"`                // a group's: its providers' icons, one per provider
	Images     bool      `json:"images,omitempty"` // takes images as input (a group's: a member does)
	ImageInput *bool     `json:"-"`                // explicit answer, nil when unknown
	// Inputs and Outputs are what the model's source listed it takes and
	// gives (catalog.Model's InputModalities, OutputModalities); see
	// Modalities
	Inputs, Outputs []string `json:"-"`
	// Context is the tokens a prompt may hold, when known (a group's: the
	// least of its members')
	Context int `json:"context,omitempty"`
	// WindowSet is set when Context is a window the user typed: on the
	// provider for the model or for all of its models (ContextOf), or on
	// the group (Group.Context, a size). Codex and Claude Code are then
	// told it whole rather than magpie's default working window
	// (CompactFor, #1809).
	WindowSet bool `json:"-"`
	// MaxContext is the most a prompt may hold when asked for, above
	// Context, as the provider's list says it (catalog.Model's: a Codex
	// entry's max_context_window, which Codex is handed and may work to)
	MaxContext int `json:"-"`
	// Output is the most tokens a reply may hold, when known (a group's:
	// the least of its members')
	Output int `json:"output,omitempty"`
	// OutputSet is set when Output is a Max output the user typed on the
	// provider, for the model or for all of its models (outputOf). An
	// agent's own cap on a vendor's figure gives way to it (#2064).
	OutputSet bool `json:"-"`
	// Family is the provider's or group's tag (see Visible).
	Family string `json:"family,omitempty"`
	// Free is set on a model its subscription serves at no cost to it.
	Free bool `json:"free,omitempty"`
	// Rate and RateWas are the credits a request costs its subscription,
	// as a multiple, and before a discount running now (catalog.Model's).
	Rate    float64 `json:"rate,omitempty"`
	RateWas float64 `json:"rateWas,omitempty"`
	// Shared are a group's levels its members have in common: its Efforts,
	// unless the group names its own (Group.Levels).
	Shared []string `json:"-"`
	// Reasoning is set on a model that thinks, levels or not: one with a
	// thinking switch alone has it and no Efforts (a group's: a member
	// thinks).
	Reasoning bool `json:"reasoning,omitempty"`
	// Reasonless is set on a model the user said takes no reasoning ask
	// (SetModelReasonless): it is sent none, and as a group's member it
	// leaves the group the levels the others have
	Reasonless bool `json:"-"`
	// AgentsV2 is set on a model offering Codex's Ultra that no ChatGPT
	// account answers for (a group's: none of its members): Codex is told
	// multi-agent V2 for it, so Ultra hands work to its agents, whose
	// tasks a magpie-served lead writes as text.
	AgentsV2 bool `json:"-"`
	// Tiers are the service tiers its list offers Codex on the model:
	// another magpie's, those it offers its own Codex (#1234); a provider
	// plugin's, those it says its vendor serves the model at (#2514)
	Tiers []string `json:"-"`
	// Released is the model's release day (YYYY-MM-DD) as its list or
	// models.dev says it, "" when neither does: what a group's template
	// weighs a newer model by (grouptemplate.go)
	Released string `json:"-"`
	// Codex is the entry the provider's own list gives the model in
	// Codex's shape (catalog.Model's), handed to Codex as it is
	Codex json.RawMessage `json:"-"`
	// AlwaysThinks, DynamicTools and DefaultEffort are what the provider's
	// own list says of the model (catalog.Model's): it always thinks, it
	// loads tools mid-conversation, it thinks at this effort unasked.
	// Kimi Code's list says them, and Kimi Code is told them. A group
	// has each one its members all share (groupSharedKimi)
	AlwaysThinks  bool   `json:"-"`
	DynamicTools  bool   `json:"-"`
	DefaultEffort string `json:"-"`
}

Entry is one model as the agents see it.

func BareEntry added in v0.1.1226

func BareEntry(shown []Entry, id string) (Entry, bool)

BareEntry is the entry of shown a client asking for a model by its bare id is told of (GET /v1/models/{id}), its ID the bare id.

func Catalog

func Catalog() []Entry

Catalog lists the routing groups, then every exposed model of every ready provider not kept unlisted. A provider switched off has none in it.

func CatalogFor added in v0.1.111

func CatalogFor(agent string) (shown, hidden []Entry)

CatalogFor is the catalog as agent is shown it, and what is kept from it (none when its lists aren't narrowed): its visibility's, less the models taken out of its lists one by one (HiddenModels), or, when it is shown only the models picked for it, those alone (PickedModels).

It is kept across requests with the catalog (keptOf): a window poll asks it for every agent, and building each again from the whole catalog was ~140 MB of what twenty polls allocated. Each caller gets its own copy of the lists.

func CatalogGroups

func CatalogGroups() ([]Entry, int)

CatalogGroups is Catalog's routing groups, the caller's own, and how many entries Catalog has, without copying the providers' models: the Providers page reads only these, on every poll, and a whole Catalog was ~0.3 MB of each poll's garbage with real accounts.

func CatalogOf added in v0.1.2176

func CatalogOf(agent string) []Entry

CatalogOf is the catalog agent's lists start from, before its visibility and picks narrow it (CatalogFor): every model that agent may be given by name.

func CodexSubagentModels added in v0.1.1142

func CodexSubagentModels() []Entry

CodexSubagentModels are the models and routing groups Codex's subagents may be put on, the ones Codex's own lists show (a model taken out of them, or not picked, isn't offered here either): the ChatGPT accounts' first, as they open a task sealed for them too, then the rest in the catalog's order. The list is kept while the catalog is held, only for reading: Codex's Agents row asked it each poll, a copy of Codex's whole catalog and the list made from it, 17 MB of forty polls with real accounts.

func Deciders added in v0.1.142

func Deciders() []Entry

Deciders are the models of the decision providers ready now, as a group's classifier names them: every one the gateway answers.

func EntryOf added in v0.1.532

func EntryOf(id string) (Entry, bool)

EntryOf is the model as the agents see it, by the id they ask for. It is the catalog's own entry, so the window and reply limit it carries are the ones a request is routed and metered against, with whatever the user set already applied.

func InOrder added in v0.1.952

func InOrder(agent string, es []Entry) []Entry

InOrder is es in agent's order: the entries ModelOrder names first, as it names them, then the rest as they come — a model added since goes after. Codex's own, a ChatGPT account's models, lead the rest, as Codex's list has them before magpie's.

func ListedFor added in v0.1.460

func ListedFor(agent string) (listed, kept []Entry)

ListedFor is the catalog agent's visibility gives it, the models it may pick to show or not among, and what the visibility keeps from it.

func OfferedDeciders added in v0.1.1242

func OfferedDeciders(keep func(id string) bool) []Entry

OfferedDeciders are the Deciders a routing group's pickers and templates offer: of a provider whose decision models are listed beside its chat models (OpenRouter's, a plugin's, a remote magpie's), with picks saved, those among the picks alone, as its editor shows the rest unpicked (coeo91 on Discord: two OpenRouter models picked, and a new group's picker listed OpenRouter's twenty-odd decision models after them). With none picked every one is offered, as before. keep, when given, says a decision model a group names already, offered whatever the picks, so a group made of one before reads as it did. A vendor's own one decision model beside its chat models (a Bailian plan's, Ark's pay as you go) is offered whatever the picks.

func Served added in v0.1.77

func Served() []Entry

Served is the catalog with the unlisted providers' models as well: every model a routing group can be made of, or a request can name. Like providerEntries it is shared, only for reading: a request asks it for each model it may go to, and a copy each time was ~380KB with 12 providers of 20 models (#3725).

func ServedEntryOf added in v0.1.532

func ServedEntryOf(id string) (Entry, bool)

ServedEntryOf is the model a limit may be set on, by the id the user typed: any model its provider serves, not only the catalog's own entry. The setters ask serves — the provider's own models deciding, switched off or not — so a provider kept unlisted, still served through a routing group, takes a window and a reply limit all the same, and a provider switched off is served again as soon as it is on, keeping what it was given. Both keep it in the entry they answer with, so a query that said "is not a model this provider serves" about such an id would contradict the command run right after it, which stores one.

func Unlisted added in v0.1.572

func Unlisted() []Entry

Unlisted are the models Served has and agents aren't offered: those of the providers kept for routing groups (Provider.Unlisted), and those a group keeps out of the lists (Group.Unlists).

func (Entry) Label added in v0.1.137

func (e Entry) Label() string

Label is how an agent's list names the entry: its name (the user's own, when they gave one, else the vendor's) with its provider's after it, or "routing group" for a group's — dropped only when a name of the user's own already carries the provider's, so it isn't said twice.

A Remote magpie's model, with its upstream names on (UpstreamProviders), is named by its name there alone and the provider serving it there after this one's: "Claude Sonnet 5 · Office › RelayA" (lcc580 on X).

func (Entry) Modalities added in v0.1.1189

func (e Entry) Modalities() (in, out []string)

Modalities are what the model takes and gives, as an agent's model list says them: every kind its source listed (a plugin's audio, video and pdf too, #1595), with image as Images has it, the user's say included. With no list, the input is text and image or text alone when whether it takes images is known, and nil when it isn't; output is nil unless said.

func (Entry) Names added in v0.1.111

func (e Entry) Names() []string

Names are what an entry answers to in a visibility: its family, and its provider's id or its group's id (as group/<id> too, and a found group's auto/<model>).

func (Entry) PlainName added in v0.1.1158

func (e Entry) PlainName() string

PlainName is the entry's name alone: a remote magpie's model's without the provider its list put after it by that magpie's own setting, which this one's Provider in model names Off leaves out as well (ARNO on Discord: "· Relay A" and "· routing group" stayed under Off).

func (Entry) PublishedOutput added in v0.1.1144

func (e Entry) PublishedOutput() int

PublishedOutput is e's reply limit as it is handed out beside its window (OutputWithin).

func (Entry) Quiet added in v0.1.1112

func (e Entry) Quiet() bool

Quiet reports whether the model is known not to think: magpie has a word on it — its vendor's or its maker's list, or its provider's own account list — and that word says no reasoning. A model nothing speaks for isn't quiet: the gateway sends it the effort the agent asked for, as #597 leaves it. Nor is one that takes levels — a model that thinks, or one the user gave levels of their own, which the gateway fits an effort to. A group's member that is quiet is sent no reasoning ask, which some vendors turn away with a 400 on a model that can't think, but for one the user fixed at an effort (Group's member syntax, #189): the gateway leaves that alone, the user's word over magpie's.

func (Entry) ServedBy

func (e Entry) ServedBy() string

ServedBy is the provider this magpie's list tells another magpie serves the entry (magpie_by): its own provider, or, for a model it has from a magpie further on, the one there, the first in the chain; "routing group" for a group's.

func (Entry) Thinks added in v0.1.1258

func (e Entry) Thinks() bool

Thinks is whether the model thinks, as /v1/models says it and every agent's list is told it: a model with levels, or one marked Reasoning with a thinking switch alone. An export that read the levels alone marked Trae CN's kimi-k3-max, which always thinks and has no levels magpie knows, not reasoning for Pi, and `magpie pi effort high` was clamped to off (#2380).

type Exclusion

type Exclusion struct {
	Agent    string `json:"agent"`
	Provider string `json:"provider,omitempty"` // set when the user removed it; saving it brings it back
	// Name is the removed provider's, for a sign-in no agent names: a
	// plugin's, whose Agent is "plugin" (#694)
	Name string `json:"name,omitempty"`
	Why  string `json:"why"`
	// SignedOut: the agent has accounts saved in magpie but isn't signed
	// in where magpie looks, and so none of them is offered.
	SignedOut bool `json:"signedOut,omitempty"`
	// Users names those saved accounts (no secrets), so they can be
	// removed from magpie while none of them is offered.
	Users []string `json:"users,omitempty"`
	// Quiet: the user asked not to be reminded of it; only the Add sheet
	// offers it back.
	Quiet bool `json:"quiet,omitempty"`
	// Tucked: hidden from the Add sheet too, but for its "Show N hidden"
	// and a search by name (#116).
	Tucked bool `json:"tucked,omitempty"`
	// Retry: the keychain didn't give Codex's sign-in (refused, no
	// answer, or its prompt still up); Try again asks it once more
	// (RetryCodexKeychain, #2367).
	Retry bool `json:"retry,omitempty"`
}

Exclusion is a sign-in magpie found but will not offer as a provider.

func Excluded

func Excluded() []Exclusion

Excluded lists sign-ins magpie detects but leaves out: the accounts the user removed from magpie, and the saved accounts of an agent that isn't signed in here (a magpie serve under another HOME, say).

type Expiring added in v0.1.3305

type Expiring struct {
	Amount float64   `json:"amount"`
	Until  string    `json:"until"`
	At     time.Time `json:"at"`
}

Expiring is a grant of credit on a key that is gone after a day: Amount (in the balance's currency) as it stood At, spent before the rest of the balance, and counted through Until (a date, 2006-01-02), to midnight after it in the user's local time.

func ParseExpiring added in v0.1.3305

func ParseExpiring(s string) (*Expiring, error)

ParseExpiring reads credit that expires as the CLI takes it, an amount and the last day it counts: "20@2026-12-31", the amount in the balance's currency (so no sign of its own); off for none (nil).

func ParseExpiringDay added in v0.1.3310

func ParseExpiringDay(s string) (*Expiring, error)

ParseExpiringDay reads which grants of credit that expires to take off, as the CLI takes it: a day, "2026-12-31", every grant through it, or "20@2026-12-31", the one of that amount.

func (Expiring) End added in v0.1.3305

func (x Expiring) End(loc *time.Location) (time.Time, bool)

End is when the credit counts no more: midnight after Until, in loc. false when Until is no date.

type ExpiringLeft added in v0.1.3305

type ExpiringLeft struct {
	Set   float64   `json:"set"`
	At    time.Time `json:"at"`
	Until string    `json:"until"`
	Left  *float64  `json:"left"`
	Ends  time.Time `json:"ends"`
}

ExpiringLeft is what is left of a grant of credit that expires: Set as typed, At, Until (the last day it counts, as typed), Left of it now (in the balance's currency) and Ends when it counts no more. Left is part of the estimate's Left, not on top of it.

type ExportFile

type ExportFile struct {
	Name string
	Data []byte
}

ExportFile is one file of an export.

type ExportResult

type ExportResult struct {
	Files    []ExportFile
	Accounts []string
	Skipped  []ImportedAccount // Status "skipped", Error says why
}

ExportResult is what an export made: its files, the accounts in them and the accounts left out, with why.

func ExportLogins

func ExportLogins(agent, format string, users []string) (ExportResult, error)

ExportLogins writes the accounts of agent (codex, claude) named in users (every one when empty) in format (ExportSub2API or ExportCLIProxy).

type ExtraBody added in v0.1.1191

type ExtraBody map[string]json.RawMessage

ExtraBody is a provider's extra body fields, each value as the user wrote it, a name that begins with "!" forced.

func (*ExtraBody) UnmarshalJSON added in v0.1.1191

func (e *ExtraBody) UnmarshalJSON(b []byte) error

UnmarshalJSON reads an object; anything else written by hand (a string, a list) is read as none, rather than failing the whole providers file.

type GatewayKeyLimit added in v0.1.1179

type GatewayKeyLimit struct {
	// Limited is false for a key the remote holds to no limit.
	Limited bool `json:"limited"`
	// Period is "day", "week", "month", "days" (a cycle of Days days) or
	// "hours" (of Hours hours), "total" (until reset by hand) or "account"
	// (one subscription account's window there; Reset zero while the
	// remote can't read it).
	Period string    `json:"period,omitempty"`
	Days   int       `json:"days,omitempty"`
	Hours  int       `json:"hours,omitempty"`
	Start  time.Time `json:"start,omitzero"`
	Reset  time.Time `json:"reset,omitzero"`
	Calls  int       `json:"calls,omitempty"`
	// TokensLeft and CostLeft are what is left of each cap there is.
	TokensLeft *int64   `json:"tokensLeft,omitempty"`
	CostLeft   *float64 `json:"costLeft,omitempty"`
	// Spent: the remote refuses the key until Reset.
	Spent bool `json:"spent,omitempty"`
	// Unpriced calls add nothing to the cost, so it reads low.
	Unpriced int `json:"unpriced,omitempty"`
}

GatewayKeyLimit is a remote gateway key's limit as its card carries it. Windows on the card show each cap; this says what they don't.

type Gave added in v0.1.1478

type Gave struct {
	ID    string    `json:"id"`
	Until time.Time `json:"until"`
}

Gave is an id a provider had and gave up to another (Provider.Gave).

type Group added in v0.1.38

type Group struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Note is the user's own word on the group (ConatusMoon2222 on X:
	// which key it is for, why it is ordered so): one line, shown under
	// its name on the Routing page and by magpie group, never sent to an
	// agent or a vendor. Empty shows nothing (CleanNote).
	Note    string   `json:"note,omitempty"`
	Members []string `json:"members"` // "provider/model[:effort]" or "group/<id>", in order (see MemberEffort)
	// Former are the ids it had before a rename (RenameGroup), newest
	// last: a request still asking group/<old> is routed to it, until a
	// group takes that id for its own (xinvxueyuan on Discord).
	Former []string `json:"former,omitempty"`
	// Match are patterns its models are found by as well (#766): a glob
	// over the "provider/model" id with * in it ("openrouter/*:free"), or
	// a regular expression after "re:". Kept apart from Members, so the
	// group follows the catalog: read, it has the models they match now
	// after those it names (see withMatches).
	Match []string `json:"match,omitempty"`
	// Matched are the members the patterns match now, as Members has them
	// after its own. Derived each time the group is read, never stored.
	Matched []string `json:"matched,omitempty"`
	// Placed is the order the user put the members in, those the
	// patterns match among those it names (usrname1833 on Discord), as
	// Members spells them. Read, the members follow it: a model matched
	// since comes after them in the catalog's order, and one no longer
	// matched drops out (placedIn). Empty when it is the order the group
	// has unasked, its own members first, then the matched. Saved, it
	// places the matched; the named go in Members' order (placedOver).
	Placed   []string `json:"placed,omitempty"`
	Routing  string   `json:"routing,omitempty"`  // as Provider.Routing, over all the members' keys and accounts; or Manual
	Affinity string   `json:"affinity,omitempty"` // as Provider.Affinity
	// RoutedAt is when the user last changed Routing (SaveGroup): a
	// conversation the group last answered before it is routed the new
	// way at its next turn under Stays: Auto, whatever its old member
	// cached, as a reorder of a provider's accounts is (NoteReordered;
	// #6708: picked by hand to A, then Use before expiry, the
	// conversation stayed on A by a 2.8k-token cache)
	RoutedAt time.Time `json:"routedAt,omitzero"`
	// Sink is Provider.Sink over the group's members' accounts and keys
	// together: one rate limited with quota left goes behind every other
	// member's. Not for "rotate" or Manual.
	Sink bool `json:"sink,omitempty"`
	// NoSink is the user's Keeps its place for the group itself: none
	// sinks, whatever the default for every group says (Sinks). Neither
	// set, the group follows that default.
	NoSink bool `json:"noSink,omitempty"`
	// FirstToken is how many seconds a member's streamed reply may take to
	// its first content — text, reasoning or a tool call — before the next
	// member is asked instead, nothing of it having reached the agent;
	// FirstTokenWait waits as long as it takes, and 0 follows the default
	// for every group (FirstTokenOr). The last one left is always waited
	// for, and the slow one doesn't rest.
	FirstToken int `json:"firstToken,omitempty"`
	// Patience is how many seconds more a request may be kept, once every
	// member has failed and nothing of a reply has been sent, for the
	// members that failed in a way that passes —
	// busy, overloaded, rate limited for a moment — to be asked again
	// after a pause, in turn, until one answers (#1418). 0 follows the
	// default for every group, PatienceDefault while that is unset (Waits);
	// PatienceOff gives the agent the last one's error once each has been
	// asked.
	Patience int `json:"patience,omitempty"`
	// Off are the members switched off: kept where they are in the
	// order, with their rules, but sent nothing until switched on again,
	// so trying a group without one doesn't mean taking it out.
	Off []string `json:"off,omitempty"`
	// Pick is the member a Manual group sends every request to, as the
	// user picked it on the group's card; "" is its first. It is kept
	// while the group routes otherwise, for when it is manual again.
	Pick string `json:"pick,omitempty"`
	// Rules send the requests they match to one member first, in order:
	// the first that matches decides (see Rule).
	Rules []Rule `json:"rules,omitempty"`
	// Classifier is the model ("provider/model") asked which of the rules'
	// intents a user's message is, or a group ("group/<id>", never this
	// one) whose models are asked in turn, failing over as for any request.
	// Rules with an intent need one; a small, fast model without reasoning
	// does.
	Classifier string `json:"classifier,omitempty"`
	// IntentSure is how confident a decision model (Jev, from TypeSafe's
	// decision API) must be of an intent of this group's for it to count:
	// from 0, its likeliest intent taken however unsure it is ("none of
	// these" never counting), to 1, certain. nil asks 0.4, as groups have
	// always asked (#5101).
	IntentSure *float64 `json:"intentSure,omitempty"`
	// Effort "auto" has the classifier — Jev, from TypeSafe's decision API,
	// or any model, asked in words — judge how hard each turn is to think
	// about as it begins, and the turn asks its model for that much
	// reasoning, where the agent asked for some (see EffortAuto).
	Effort string `json:"effort,omitempty"`
	// Context is how long a request the user says the group takes, in
	// tokens: agents are told it rather than its largest member's.
	// ContextSmallest tells them its smallest member's, whichever that is
	// as the members change (Mikan on Discord), so the agent compacts
	// before any member would turn the conversation away.
	Context int `json:"context,omitempty"`
	// Compact is where Codex and Claude Code compact a conversation on the
	// group, in tokens (NovaStudiosss on X): over what its members' own
	// thresholds (settings.ModelCompacts) and Long conversations say, so a
	// group carries both its window (Context) and its compaction and no
	// provider needs either set for it. 0 leaves it to those.
	Compact int `json:"compact,omitempty"`
	// Levels are the reasoning levels agents are offered for the group,
	// lowest first, when the user names them (#295): rather than those
	// every member has, so that a member with few doesn't take the rest
	// from the others. A member without the level a request asks for is
	// sent the one it has nearest, as ever. Empty offers the members'
	// shared levels.
	Levels []string `json:"levels,omitempty"`
	// Fast are the members (as Members spells them) sent in their
	// vendor's fast mode, where the model has one (see CanFast). Kept
	// beside Members, not in their ids, so a version before it still
	// routes to them, only not fast.
	Fast []string `json:"fast,omitempty"`
	// Ultra are the members of Fast sent in the vendor's faster mode
	// still (Codex's Ultra Fast, kdajenks on X), where the account
	// offers it and priority where not. Always a part of Fast.
	Ultra []string `json:"ultra,omitempty"`
	// Weights are the members' shares (as Members spells them) when the
	// group routes by weight (Weighted, #1910): one weighing 3 takes three
	// requests for every one a member weighing 1 takes. One not in it
	// weighs 1. Kept while the group routes otherwise, for when it is by
	// weight again.
	Weights map[string]int `json:"weights,omitempty"`
	// EffortMaps are, for the members (as Members spells them) that
	// follow the group's effort, the level each sends in place of the one
	// asked for ("high" → "xhigh"): see groupeffortmap.go. A level not in
	// a member's map is sent as asked.
	EffortMaps map[string]map[string]string `json:"effortMaps,omitempty"`
	// Family is a tag the group goes by in which agents are shown it
	// (settings' Visible), with its id.
	Family string `json:"family,omitempty"`
	// Unlists keeps the models the group names, or its patterns match,
	// out of the lists agents and the gateway's model list show (#1783):
	// they are offered through the group alone, as a provider kept for
	// routing groups offers its own (Provider.Unlisted), and a request
	// naming one is still served. A group in it keeps its own, as it
	// says. Not while the group is switched off.
	Unlists bool `json:"unlists,omitempty"`
	// Accounts hold the group to some accounts or keys of the providers
	// they name (duanckham on X: a personal and a company GPT account,
	// each group's tasks on its own), as a gateway key's account list
	// does (#905) and in its form, "<provider>/<account stable id or key
	// fingerprint>": a request through the group is sent only on those
	// of a provider it names, a provider it names none of on every
	// account it has. Empty, every account of every member serves.
	Accounts []string `json:"accounts,omitempty"`
	// Keys bind the group to some gateway keys (access.Key.ID; Xerxes754
	// on X: a group for one or two keys alone). Set, a request with
	// another key may neither use the group nor see it in a model list,
	// whatever models that key may use; a key issued under one of them
	// may, as it may what its issuer may. A request with no key (this
	// computer's own) is held by no key and passes. Empty, every key the
	// group is given passes, as before. Saved, nil keeps the group's
	// (SaveGroup), so a caller that doesn't know of them leaves them be;
	// empty clears them.
	Keys []string `json:"keys,omitempty"`
	// Redact is whether a request through the group is masked (1dwsdqwd2
	// on X: some groups masked, some not): "" follows each member's
	// provider ("Send requests unmasked") and Settings, RedactOn masks it
	// as Settings say whichever provider, RedactOff sends it as written.
	// It is the user's alone: Settings with masking off mask nothing, a
	// shared group carries none, and in a group inside a group any RedactOn
	// among them wins over RedactOff. Saved, "" keeps the group's
	// (SaveGroup) and RedactFollow clears it, so a caller that doesn't
	// know of it leaves it be.
	Redact string `json:"redact,omitempty"`
	// Auto is set on a group magpie found: one model served by several
	// providers. It is derived, never stored.
	Auto bool `json:"auto,omitempty"`
	// Spelled is how a vendor spells the model of a group magpie found
	// (auto-…), which agents are given it by: auto/<Spelled> (Ref). It is
	// derived from the members each time the groups are read, never stored.
	Spelled string `json:"-"`
	// Hidden is stored for a found group the user removed.
	Hidden bool `json:"hidden,omitempty"`
	// Seen is stored for a found group the user changed (an auto-… id):
	// the models, as "provider/model", magpie had found in it by the
	// user's last save, and those the user named. A provider that serves
	// the model since joins the group as it is read (joined), as it joins
	// one magpie finds; one seen and not a member is one the user took
	// out, and stays out. Empty, the group was changed before magpie
	// kept this, and gets no member it doesn't name (Kxsg79bEYFP4 on X).
	Seen []string `json:"seen,omitempty"`
	// Disabled is a group of the user's switched off (PAMI on Discord):
	// kept on the Routing page as it is, but not offered to agents, a
	// request to it turned away with a word of why, and skipped where
	// another group has it in it, until switched on again (SwitchGroup).
	// Only SwitchGroup changes it: a save keeps it as it was.
	Disabled bool `json:"disabled,omitempty"`
}

Group is a routing group.

func AddTemplate added in v0.1.1163

func AddTemplate(kind, name string) (Group, error)

AddTemplate saves the template kind as the user's models make it now, as a group of the user's named name (the template's own name when empty), numbered past a name or id in use, so it never replaces a group there is. It is listed last, as a group made in the editor is.

func CopyGroup added in v0.1.1158

func CopyGroup(id, name string) (Group, error)

CopyGroup makes a group of the user's that is the group id as it is now (lc on Discord): its models and patterns, routing, rules, classifier, effort, context, levels, fast and off members, under name — "<name> copy" when empty, numbered past a name or id in use — listed right after the one it copies. A found group's copy is the user's, with the members it has now. The copy is on, whether the group was or not, and the original is left as it is.

func DisabledGroup added in v0.1.989

func DisabledGroup(id string) (Group, bool)

DisabledGroup is the group of the user's a model id names ("group/<id>", or a model's as GroupFor takes it) when it is switched off.

func GroupDisabledOut added in v0.1.1219

func GroupDisabledOut(id string) (Group, []string, bool)

GroupDisabledOut is the group id names when it has no model left only because the user disabled every one it would have (#1867), and those models: the gateway says so, not that the group is empty.

func Groups added in v0.1.38

func Groups() []Group

Groups lists the user's groups, then those magpie found, hidden ones too (marked so), in the order the user put them in (SetGroupOrder) where they did: the Routing page, the gateway's model list, the CLI and the TUI all list them so.

func GroupsWith added in v0.1.102

func GroupsWith(id string) []Group

GroupsWith are the groups that have the group id in them as a member.

func StoredGroups added in v0.1.76

func StoredGroups() ([]Group, error)

StoredGroups is the groups as saved: the user's own, and the found ones the user removed. As with Stored, a file that can't be read is an error.

func (Group) Decides added in v0.1.1170

func (g Group) Decides() bool

Decides reports whether g is a decision group: every model it names is a decision model.

func (Group) FirstTokenOr added in v0.1.3270

func (g Group) FirstTokenOr() int

FirstTokenOr is the seconds the group lets a member take to its first content: its own FirstToken, else the default for every group (settings' GroupFirstToken); 0 or less waits as long as it takes.

func (Group) IsFast added in v0.1.577

func (g Group) IsFast(id string) bool

IsFast reports whether the group sends its member id fast.

func (Group) IsOff added in v0.1.688

func (g Group) IsOff(id string) bool

IsOff is whether the group's member id is switched off.

func (Group) IsUltra

func (g Group) IsUltra(id string) bool

IsUltra reports whether the group sends member id in the faster mode.

func (Group) Live added in v0.1.498

func (g Group) Live() Group

Live is the group as the gateway routes it: a manual group's rules wait (the member picked is all it sends to), though they are kept.

func (Group) MemberEffortMap added in v0.1.3246

func (g Group) MemberEffortMap(id string) map[string]string

MemberEffortMap is the levels the group's member id sends in place of the ones asked for; nil when it sends them as asked.

func (Group) MemberWeight added in v0.1.1224

func (g Group) MemberWeight(id string) int

MemberWeight is the share of the group's requests its member id takes when the group routes by weight (Group.Weights): 1 when none is set.

func (Group) Picked added in v0.1.498

func (g Group) Picked() string

Picked is the member a manual group sends to: the one the user picked while it is in the group, else its first.

func (Group) Ref added in v0.1.1294

func (g Group) Ref() string

Ref is the id agents pick the group by: auto/<model> for a group magpie found (one with an auto-… id whose members are that model), its model spelt as a vendor spells it; group/<id> for any other, and for every group while a provider of the user's is called auto.

func (*Group) RenameMember added in v0.1.577

func (g *Group) RenameMember(from, to string)

RenameMember has the group's member from go by to (its effort changed): its rules, its pick, its fast mode, its being off and its weight follow it.

func (Group) Ruled added in v0.1.142

func (g Group) Ruled() bool

Ruled reports whether the group decides anything as a user's turn begins: a rule to put a member first, or the turn's effort. A pause rule decides nothing then (PausedOut is looked at on every request).

func (*Group) SetMemberEffortMap added in v0.1.3246

func (g *Group) SetMemberEffortMap(id string, to map[string]string)

SetMemberEffortMap has the group's member id send to[l] when l is asked; an empty map sends every level as asked.

func (*Group) SetMemberFast added in v0.1.577

func (g *Group) SetMemberFast(id string, fast bool)

SetMemberFast sends the group's member id fast, or not, where it is in the group.

func (*Group) SetMemberTier

func (g *Group) SetMemberTier(id, tier string)

SetMemberTier sends the group's member id at tier: "" the usual speed, "priority" fast, "ultrafast" the faster mode of an account that offers it. Only a member that is in the group is switched on.

func (*Group) SetMemberWeight added in v0.1.1224

func (g *Group) SetMemberWeight(id string, weight int)

SetMemberWeight sets the share the group's member id takes when the group routes by weight; 1 or less is the default, left out.

func (Group) Sinks added in v0.1.3270

func (g Group) Sinks() bool

Sinks is whether one of the group's accounts or keys rate limited with quota left goes to the back (Sink): the group's own word, Sink or NoSink, else the default for every group (settings' GroupSink). Whether its routing can sink at all is the gateway's to say.

func (Group) Waits added in v0.1.1159

func (g Group) Waits() time.Duration

Waits is how long a request to the group may be kept for its members to come back (Patience), 0 for not at all. A group that sets none follows the default for every group (settings' GroupPatience, jiezhengj on Discord), PatienceDefault while that is unset too.

func (Group) Within added in v0.1.1776

func (g Group) Within(in Group) Group

Within is g, a group in the group in, as in routes it: one left on the default (Smart) is routed as in is, as a provider left on the default is weighed with the group it is in (ownRouting, #3847, mycf_711) — Free first on the outer group reaches the seats of a group in it that says nothing of its own. One that sets a routing keeps it (#576), and so does every one in a group In order, By weight or Manual: those try each member whole, by its own routing, as they do a provider's keys.

type GroupStandIn added in v0.1.3051

type GroupStandIn struct {
	Entry  Entry
	Groups []string
}

GroupStandIn is a model a routing group listing alone (Group.Unlists) keeps out of the lists, with the catalog ids ("group/<id>") of the groups that stand in for it there.

func GroupStandIns added in v0.1.3051

func GroupStandIns() []GroupStandIn

GroupStandIns are the models groups listing alone keep out of the lists, in the catalog's order: a caller the groups are not given (a gateway key that doesn't name them) is listed these in their place, those it may use, as no group stands in for them for it (luckymanjc on Discord: a key held to every Codex model was listed only the one no group of his listed alone). A provider kept for routing groups alone (Provider.Unlisted) is not among them: the user kept all of it out.

type Imported added in v0.1.1181

type Imported struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Missing are the models and groups the text names that this magpie
	// has none of, left out of the group: members, and the classifier.
	Missing []string `json:"missing,omitempty"`
	// Instead are the members this magpie has under another provider: the
	// same model (AutoGroupOf), "shared → here".
	Instead []string `json:"instead,omitempty"`
	// Rules is how many of the group's rules were left out with the
	// member they send to, or the classifier their intent needs, or for
	// holding by a folder of the sharer's.
	Rules int `json:"rules,omitempty"`
	// Replaced: the text's id was a group of the user's, which it
	// replaced (ImportGroupOver) instead of adding another.
	Replaced bool `json:"replaced,omitempty"`
}

Imported is what ImportGroup made of a shared group.

func ImportGroup added in v0.1.1181

func ImportGroup(text string) (Imported, error)

ImportGroup adds the group a shared text holds as a group of the user's, named as it was shared and numbered past a name or id in use, so it never replaces a group there is. It is listed last. A member this magpie has no provider of is the same model under one it has, where it serves it (Instead), else left out (Missing), and with it the rules that send to it and its place among the fast and off members. Nothing is added when none of its members is left.

func ImportGroupOver added in v0.1.2878

func ImportGroupOver(text string) (Imported, error)

ImportGroupOver is ImportGroup that, when the text's group id is a group of the user's own (not one magpie found, not one removed), replaces that group by what the text holds, in its place in the list, rather than adding another. Only that group changes. What the text can't carry stays as the user has it: the group's accounts, its rules that hold by a folder, whether it is switched on and its place among the groups. With no such group it adds one, as ImportGroup does.

type ImportedAccount added in v0.1.326

type ImportedAccount struct {
	// User is the account's email, or "#n" (its place in the file) when
	// the file doesn't say and Google wasn't asked or didn't answer.
	User string `json:"user"`
	// Status: "added", "updated" (in magpie already, now with this
	// sign-in), "exists" (in magpie already with this very sign-in),
	// "failed".
	Status string `json:"status"`
	Plan   string `json:"plan,omitempty"`
	Error  string `json:"error,omitempty"`
	// File is the place (from 1) of a file, among several imported at
	// once, that held no account to read: User is empty then, and Error
	// says why. A file that can't be read is said so, never passed over.
	File int `json:"file,omitempty"`
}

ImportedAccount is what became of one account in an import.

func ImportCodexAccessOnly

func ImportCodexAccessOnly(ctx context.Context, files []string) ([]ImportedAccount, error)

ImportCodexAccessOnly is ImportLogins for ChatGPT accounts kept access token only (codex_access_only.go): each is kept with the access token the file has, never refreshed, so the sign-in it came from stays signed in. One whose access token has run out isn't taken.

func ImportFactoryKeys added in v0.1.638

func ImportFactoryKeys(ctx context.Context, texts []string) ([]ImportedAccount, error)

ImportFactoryKeys adds Factory accounts by their API keys, found in the pasted texts, each checked with whoami first, and says what became of each.

func ImportGoogleAccounts added in v0.1.326

func ImportGoogleAccounts(ctx context.Context, agent string, files []string) ([]ImportedAccount, error)

ImportGoogleAccounts brings in the accounts in exports from other tools (see above), each file's text one element of files, and says what became of each.

func ImportLogins added in v0.1.401

func ImportLogins(ctx context.Context, agent string, files []string) ([]ImportedAccount, error)

ImportLogins brings in ChatGPT (agent "codex") or Claude ("claude") accounts from other tools' files (see above), each file's text one element of files, and says what became of each.

func ImportPluginFiles

func ImportPluginFiles(ctx context.Context, id string, texts []string) ([]ImportedAccount, error)

ImportPluginFiles brings in the accounts the files' texts hold for the plugin's subscription id (a magpie id): the plugin reads them, checks each with its vendor as a sign-in does, and keeps the ones it takes, through the proxy the subscription's requests go through (#1663).

func MoveToAgy

func MoveToAgy(ctx context.Context) ([]ImportedAccount, error)

MoveToAgy brings Antigravity's accounts into agy-cli: the plugin installed (or brought up to the version that takes them) and agy with it, then each account checked with agy and kept as agy-cli's. The old sign-ins are left as they are; one agy refuses is said, not moved.

func PastedSignIns added in v0.1.1697

func PastedSignIns(texts []string) (done []ImportedAccount, rest []string)

PastedSignIns takes out of an import's texts each one that is a browser sign-in's end and finishes the sign-in it belongs to with it, as its Callback URL field does. done says what became of each, in the texts' order; rest are the texts left to import as accounts.

type KeyAccount added in v0.1.14

type KeyAccount struct {
	Name string `json:"name,omitempty"`
	Key  string `json:"key"`
	Off  bool   `json:"off,omitempty"`
	// Protocol, when set, is the only one the key works with: some relays
	// give out one key for Anthropic and another for OpenAI. Empty is any.
	Protocol Protocol `json:"protocol,omitempty"`
	// Weight is the key's share of the requests when the provider's
	// routing is Weighted (#841): one with 3 takes three for every one a
	// key with 1 takes. None, or 0, counts as 1.
	Weight int `json:"weight,omitempty"`
	// Plan, on a preset whose plans are sold on keys of their own
	// (PresetDef.KeyPlans), is the id of the Region the key is for: its
	// requests go to that plan's endpoints, and it is asked only for that
	// plan's models. Empty is the provider's own plan, as before.
	Plan string `json:"plan,omitempty"`
}

KeyAccount is a saved key after the first. Off keeps it without using it.

func (KeyAccount) WeightOf added in v0.1.933

func (k KeyAccount) WeightOf() int

WeightOf is the key's weight as Weighted routing counts it: 1 when none.

type KeyCapState

type KeyCapState struct {
	Used float64   `json:"used"`
	Cap  int       `json:"cap"`
	Back time.Time `json:"back,omitzero"`
}

KeyCapState is a key held at its usage cap: the share used of the fullest window at its cap, that cap and when the last such window renews (zero when one doesn't say).

type KeyInfo added in v0.1.14

type KeyInfo struct {
	ID     string `json:"id"` // a fingerprint, to name it in a switch
	Name   string `json:"name,omitempty"`
	Masked string `json:"masked"`
	Active bool   `json:"active"` // the first, where requests go
	On     bool   `json:"on"`     // in use: the first, or next in line

	Protocol Protocol `json:"protocol,omitempty"` // the only one it works with
	Weight   int      `json:"weight,omitempty"`   // its share when routing is Weighted
	Plan     string   `json:"plan,omitempty"`     // its plan's region id, "" for the provider's

	// Rest is why the gateway passes it over now, after a failure, and
	// until when; nil while it takes requests.
	Rest *KeyRest `json:"rest,omitempty"`
	// Spend is the spend cap set on it and what it has spent in its
	// period; nil with none.
	Spend *KeySpend `json:"spend,omitempty"`
	// UsageCap: its own usage windows are read, so it can be capped at a
	// share of them; CapHeld is how the cap holds it now (key_allowance.go,
	// account_caps.go), nil while it takes requests
	UsageCap bool         `json:"usageCap,omitempty"`
	CapHeld  *KeyCapState `json:"capHeld,omitempty"`
	// Balance is the balance the user typed for it and what is left of
	// it by magpie's count (key_balance_own.go); nil with none.
	Balance *BalanceEstimate `json:"balance,omitempty"`
}

KeyInfo describes one of a provider's keys without giving it away.

type KeyOn added in v0.1.3223

type KeyOn struct {
	KeyAccount
	Rank, Of int
}

KeyOn is one of a provider's keys on, at its place among them (Rank), of how many it has on (Of).

type KeyRest added in v0.1.930

type KeyRest struct {
	Why    string    `json:"why"`
	Status int       `json:"status"`
	Until  time.Time `json:"until"`
	Key    string    `json:"key"`
	// Probed: the gateway asks it again in the background, and lifts the
	// rest as soon as it answers (gateway/rest_probe.go)
	Probed bool `json:"probed,omitempty"`
	// By: what set how long (gateway.Rest.By): "resets" or "retry-after"
	// when the vendor named the time
	By string `json:"by,omitempty"`
	// Model: the one model resting, the account still answering its
	// others; "" for the whole account or key
	Model string `json:"model,omitempty"`
	// Error: what the vendor said
	Error string `json:"error,omitempty"`
	// Rate: the vendor called it a rate limit and named when it lifts
	// (gateway.Rest.Rate): the page says rate limited, not quota used up
	Rate bool `json:"rate,omitempty"`
	// Notice: it rests no more, but the vendor's limit is still shown
	// (gateway.LimitNotice): Until is when the vendor said it lifts, zero
	// when it named no time, and At when it was refused
	Notice bool      `json:"notice,omitempty"`
	At     time.Time `json:"at,omitzero"`
}

KeyRest is a key's rest as the gateway keeps it: failQuota, failRate…, the status it answered, until when, and the key to lift it by.

type KeySpend added in v0.1.2819

type KeySpend struct {
	SpendCap
	Spent float64    `json:"spent"`
	Reset *time.Time `json:"reset,omitempty"`
	Held  bool       `json:"held,omitempty"`
}

KeySpend is a key's spend cap as its row tells it: the cap, what magpie counted spent in its period, when that renews (none for a cap in all), and whether routing holds the key at it now.

type KeyWindow

type KeyWindow struct {
	Account  string    `json:"account"`  // "<provider>/<user>"
	Window   string    `json:"window"`   // the window's name, as the account's card says it
	Provider string    `json:"provider"` // the card's name: "Codex", "Claude"
	User     string    `json:"user"`
	Alias    string    `json:"alias,omitempty"`
	Start    time.Time `json:"start"`
	Reset    time.Time `json:"reset"`
}

KeyWindow is a subscription account's window a gateway key's limit can follow, as the limit editor lists it.

func KeyWindows

func KeyWindows(ctx context.Context, now time.Time) []KeyWindow

KeyWindows are the windows of every subscription account a key's limit can follow: each that runs out and starts again on a clock the vendor tells, from the accounts' cards as last read. One with no reset clock can't place a window, nor can money set aside, a text row or another magpie's card.

type Kind

type Kind string

Kind groups presets in the picker.

const (
	KindVendor Kind = "vendor" // the model's own maker
	KindRelay  Kind = "relay"  // an aggregator / API relay reselling many vendors
	KindLocal  Kind = "local"  // something running on this machine
	// KindRemote is another computer's magpie: not a relay, so the add
	// lists give it a heading of its own, after this machine's
	KindRemote Kind = "remote"
)
const KindPartner Kind = "partner"

KindPartner is a partner's Kind: the add sheet lists them apart.

type KiroAuth added in v0.1.141

type KiroAuth struct {
	Token     string
	TokenType string // the tokentype header: API_KEY, EXTERNAL_IDP, or none
	Profile   string // the profile ARN
	Region    string // where the account's API is
}

KiroAuth is what a call to Kiro's API is made with.

func KiroAuthOf added in v0.1.141

func KiroAuthOf(ctx context.Context, key, home string, stale bool) (KiroAuth, error)

KiroAuthOf is a Kiro account's credentials: those of the key saved on the provider, of the account magpie signed in in home, or of Kiro's own sign-in when both are "". A token about to expire is refreshed first; stale, after Kiro turned one down, refreshes it now.

func (KiroAuth) Header added in v0.1.141

func (a KiroAuth) Header(h http.Header)

Header sets the headers that say who is calling.

type LeftRecord added in v0.1.1232

type LeftRecord struct {
	Package  string   `json:"package"`
	Provider Provider `json:"provider"`
}

LeftRecord is a record set aside when the plugin it was one of was removed: Package is the plugin's package name, as plugin.PackageName gives it.

type Limit added in v0.1.38

type Limit struct {
	Used   float64       // share used, 0–100
	Resets time.Time     // zero when not known
	Span   time.Duration // how long the window runs; zero when not known
	Model  string        // the only models it counts, by a word in their ids
	// Amount of Of in Unit: the window's own count, used, when the vendor
	// counts it so (QuotaWindow.Amount)
	Amount, Of float64
	Unit       string

	Name string // QuotaWindow.Name: which window it is, one reading to the next (WindowCapID)

	// ResetRunsOut is when the reset the account spends by itself before
	// it runs out does (resetRunsOut): spent then, it starts this window
	// again — at Restarts, which routing takes for the window's renewal
	// when it is the sooner. Zero when none will be spent so.
	ResetRunsOut time.Time
	// RunsOut is when the soonest of what the window has left is lost,
	// apart from its reset (QuotaWindow.RunsOutAt): zero when not known.
	RunsOut time.Time
	// RunsOutLeft is how much, in Unit, is lost at RunsOut
	// (QuotaWindow.RunsOut): zero when not told
	RunsOutLeft float64
	// Credits: the account goes on past this window on its credits
	// (QuotaWindow.Credits)
	Credits bool
	// Balance is how much is left in Unit, a wallet's reading with no
	// share (QuotaWindow.Balance); nil when not told
	Balance *float64
	// contains filtered or unexported fields
}

Limit is one window of an allowance.

type Listed added in v0.1.2688

type Listed struct {
	ID     string
	Models int
}

Listed is a provider RefreshLists asked, and how many models it listed.

func RefreshLists added in v0.1.2688

func RefreshLists(ctx context.Context) []Listed

RefreshLists asks every provider that is ready, and not switched off, for its model list, each for at most refreshEach, and answers those that answered, in order: the Refresh of every list (the GUI's, `magpie sync`). One switched off is asked nothing and keeps the list it had (ChangQiu on Discord: Off means no request goes to it).

type Listing added in v0.1.2463

type Listing struct{ Available, Exposed, Newest []catalog.Model }

Listing is a provider's models as the Providers page draws them: the vendor's list (Available), what of it is exposed (ExposedOf) and the newest of each family (NewestInFamily).

func KeptListing added in v0.1.2463

func KeptListing(p Provider) Listing

KeptListing is the Listing of a provider All gave, kept across requests with the catalog (keptOf) while nothing it is built from changed: each poll of the Providers page built every provider's list and its newest of each family again, 9 MB a poll in a real setup. What it gives is shared, so read only.

type Login added in v0.1.11

type Login struct {
	Agent  string    `json:"agent"`
	User   string    `json:"user"`
	Plan   string    `json:"plan,omitempty"`
	Seen   time.Time `json:"seen"`
	Active bool      `json:"active"` // the agent is signed in to this one now
	On     bool      `json:"on"`     // in use: the active one, or next in line
	// Lapsed says the vendor refused to refresh a saved account's sign-in:
	// it has to be signed in again before it can be used.
	Lapsed string `json:"lapsed,omitempty"`
	// Until is when the account's paid plan ends, as its sign-in says (a
	// ChatGPT one's chatgpt_subscription_active_until, codexUntil): nil
	// when it doesn't, or names a time gone by.
	Until *time.Time `json:"until,omitempty"`
	// Own is the agent's own sign-in, which magpie only reads: removed, it
	// is hidden rather than deleted (side_logins.go).
	Own bool `json:"own,omitempty"`
	// Paused is the account the agent is signed in to, passed over by the
	// gateway while another is on (savedLogin.Paused).
	Paused bool `json:"paused,omitempty"`
	// Returns is the account magpie signed the agent out of when it was
	// spent, and signs it back in to once it has room again (#408).
	Returns bool `json:"returns,omitempty"`
	// Token is a Claude account added by a setup-token: magpie's
	// requests use it, and Claude Code itself only through its
	// settings.json (Uses).
	Token bool `json:"token,omitempty"`
	// Uses is the setup-token account Claude Code itself uses now, its
	// token put in its settings.json by magpie (claude_token_env.go). The
	// account Claude Code's stored sign-in is (Active) stays as it is.
	Uses bool `json:"uses,omitempty"`
	// AccessOnly is a ChatGPT account kept access token only
	// (codex_access_only.go): magpie never renews its sign-in, nor signs
	// Codex in to it.
	AccessOnly bool `json:"accessOnly,omitempty"`
	// contains filtered or unexported fields
}

Login is a remembered subscription account, without its secrets.

func Logins added in v0.1.11

func Logins(agent string) []Login

Logins lists the remembered accounts of an agent ("" for every one), the active one flagged. A request lists an agent's once: /api/providers asks it of every provider, twice with its account models, and each took logins.json's lock, a file opened across magpies (a seventh of the list's CPU). The caller gets its own copy.

type Member added in v0.1.38

type Member struct {
	ID string // the group's member it is: the model, or the group in the group it is of
	// Path is the members from the group's own down to the model: [ID] for
	// a model the group names itself, ["group/fast", "a/m"] for one of
	// its group fast, and so on down.
	Path []string
	// Via are the groups in the group it is of, the outermost first: the
	// group each of Path's members but the last names.
	Via []Group
	// Redact is what the groups it is reached through say of masking, the
	// group itself and each in Via (Group.Redact): RedactOn if any says so,
	// else RedactOff if any does, else "".
	Redact   string
	Provider Provider
	Model    string // what the vendor is asked for
	// Effort is the reasoning the member is fixed at ("provider/model:low"),
	// asked of the model whatever the agent or the group's classifier
	// asked; "" follows the group.
	Effort string
	// Levels are the reasoning levels the member follows the agent among
	// ("provider/model:low+high"), lowest first: the agent's effort is
	// sent at the nearest of them. nil for a member fixed at one (Effort)
	// or following the group.
	Levels []string
	// EffortMap is, for a member following the group's effort, the level
	// it sends in place of the one asked for (Group.EffortMaps); nil
	// sends it as asked.
	EffortMap map[string]string
	// Fast is set on a member the group sends in its vendor's fast mode
	// (Group.Fast), where its model has one.
	Fast bool
	// Ultra is set on a Fast member the group sends in the faster mode.
	Ultra bool
	// Account is the one account or key of Provider the member is sent
	// on, "<provider>/<stable id>", as Group.Accounts has them
	// ("provider/model#<id>", groupaccount.go); "" for every one the
	// groups it is in allow.
	Account string
	// At is where the walk down the group met it, counting every model of
	// every group in it, the same model's later places too: a group's own
	// models are met in its own order.
	At int
	// Also are the other places further down the walk that have the same
	// model at the same effort, which the group asks once, where it was
	// met first: a rule naming a later group in the group still has it,
	// in that group's own order (#2361).
	Also []Member
}

Member is one of a group's models as it resolves now.

func FallbackModels added in v0.1.1962

func FallbackModels(p Provider) []Member

FallbackModels are the models p's fallbacks reach, in order: an entry naming a model, that model as routing reaches it (ResolveRoute); one naming a routing group, the group's members. An entry that reaches nothing is left out, as the gateway passes it over, and a model met again is listed where it was met first.

func (Member) Below added in v0.1.102

func (m Member) Below(depth int) Member

Below is the member as the group at depth (0 the group itself, 1 the group in it Path[0] names, …) has it.

func (Member) Groups added in v0.1.102

func (m Member) Groups() []string

Groups are the ids of the groups in the group the model is of, the outermost first.

func (Member) Homed added in v0.1.1258

func (m Member) Homed(path []string) (Member, bool)

Homed is the member as the place under the members path names (the group's member ids from the top) has it, its others in Also; ok is false when none of its places is there.

func (Member) In added in v0.1.1258

func (m Member) In(id string) (Member, bool)

In is the member as the group's member id has it: itself, where it was met further down the walk (Also), or, for a model, where a group in the group ahead of it has it too (#625). ok is false when id isn't one of its places.

func (Member) Masking

func (m Member) Masking() string

Masking is what the groups the member is reached through say of masking, all its places counted (Also, the same model met again in another group): RedactOn if any says so, RedactOff only if all do, else "". The model's provider is the same in each place.

func (Member) Spelled added in v0.1.1883

func (m Member) Spelled() string

Spelled is the member's model as the group names it: with the effort it is fixed at, or the levels it follows the agent among.

func (Member) Unmasked

func (m Member) Unmasked() bool

Unmasked says a request to the member goes as written: its groups say so (Masking), or none says otherwise and its provider is set to send unmasked (Provider.SkipsRedaction).

type Migration added in v0.1.506

type Migration struct {
	State   string    `json:"state"`
	Package string    `json:"package,omitempty"`
	At      time.Time `json:"at"`
	Err     string    `json:"error,omitempty"`
	// Accounts are the plugin's accounts the move made or took over.
	Accounts []movedAccount `json:"accounts,omitempty"`
	// Backup is the built-in's accounts as logins.json kept them.
	Backup []savedLogin `json:"backup,omitempty"`
	// Kept is what else of the built-in's the move set aside (Kiro's key).
	Kept json.RawMessage `json:"kept,omitempty"`
	// Installed is whether the move installed the plugin: a failed move
	// takes it away again.
	Installed bool `json:"installed,omitempty"`
	// Host is the built-in's API host, which the plugin's provider shows.
	Host string `json:"host,omitempty"`
	// Why is a failed move's reason, for the page to say in the user's
	// language.
	Why *MoveWhy `json:"why,omitempty"`
}

Migration is where one built-in's move stands.

func MigrationOf added in v0.1.506

func MigrationOf(id string) (Migration, bool)

MigrationOf is where the built-in id's move stands.

type ModelDetection added in v0.1.671

type ModelDetection struct {
	Model   string      `json:"model"`
	Results []Detection `json:"results"`
}

ModelDetection is what each API answered for one model (01huadalang on Discord: 应该能看出来选择的模型支持情况…有的仅支持 response 有的双协议).

type ModelList added in v0.1.1133

type ModelList struct {
	// Visible is what its lists are narrowed to; nil when they aren't.
	Visible *[]string `json:"visible,omitempty"`
	Hidden  []string  `json:"hidden,omitempty"`
	// Only: it is shown only Picked, none when Picked is empty.
	Only   bool     `json:"only,omitempty"`
	Picked []string `json:"picked,omitempty"`
	Order  []string `json:"order,omitempty"`
}

ModelList is everything that decides which of magpie's models an agent's lists show, and in what order, as a profile keeps it (#1368): its visibility (Visible), the models taken out one by one (HiddenModels) or, for an agent shown only its picks, the ones picked (PickedModels), and the order it was put in (OrderedModels). The fast picks are not here: they say how a model is sent, not whether it is listed.

func ModelListOf added in v0.1.1133

func ModelListOf(agent string) ModelList

ModelListOf is agent's model list as it is now.

func (ModelList) Default added in v0.1.1133

func (l ModelList) Default() bool

Default reports whether l is what an agent never picked for is shown: every model, in magpie's own order.

type ModelPref added in v0.1.648

type ModelPref struct {
	Name    *string   `json:"name,omitempty"`
	Efforts *[]string `json:"efforts,omitempty"`
	// Reasonless, set, is SetModelReasonless's word: true for no
	// reasoning ask, false to take that back
	Reasonless *bool          `json:"reasonless,omitempty"`
	Images     *bool          `json:"images,omitempty"`
	OwnImages  bool           `json:"ownImages,omitempty"`
	API        *string        `json:"api,omitempty"`
	Same       *string        `json:"same,omitempty"`
	Price      *catalog.Price `json:"price,omitempty"`
	OwnPrice   bool           `json:"ownPrice,omitempty"`
	// Kind is what the model makes, as SetModelKind takes it: "image",
	// "video", or "" for what its vendor's list and name say (#1399)
	Kind *string `json:"kind,omitempty"`
	// ID is the id the model is listed by at its provider, as SetModelID
	// takes it: "" for the provider's own. It is applied after every
	// other change of the save, so those go with the model to its id.
	ID *string `json:"id,omitempty"`
	// Headers are the model's own request headers, as SetModelHeaders
	// takes them, in place of those it had: none takes them away
	Headers *map[string]string `json:"headers,omitempty"`
	// System is the model's own system prompt, as SetModelSystemPrompt
	// takes it, in place of the one it had: "" takes it away
	System *string `json:"system,omitempty"`
	// Tier is the model's own speed, as SetModelTier: "" usual, "priority"
	// or "ultrafast".
	Tier *string `json:"tier,omitempty"`
}

ModelPref is what the provider editor's Model settings changed of one model, sent with its Save: each part left nil is as it was. Name "" gives the model its own name back, Efforts [] all its levels, OwnImages the vendor's answer for whether it sees images, API "" every API the provider has for it, Same "" its own id to merge it with other vendors' by (see setModelSame), OwnPrice its list price again in place of Price, what the user said it costs (SetModelPrice, #819), and Kind "" what its vendor's list says it makes (SetModelKind, #1399).

type MoveCandidate added in v0.1.552

type MoveCandidate struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	Package  string `json:"package"`
	Accounts int    `json:"accounts"`
	// Error and Why are the last try's failure, when one failed
	Error string   `json:"error,omitempty"`
	Why   *MoveWhy `json:"why,omitempty"`
}

MoveCandidate is a built-in with accounts its plugin could run instead.

func MoveCandidates added in v0.1.552

func MoveCandidates() []MoveCandidate

MoveCandidates are the built-ins not on their plugins that have accounts to move, by name. One whose plugin the user removed (MoveRemoved) is none: its accounts moved already and are kept with the plugin's sign-ins, and installing the plugin again gives it back (HandOver), as MoveRetiring and HandOver leave it too. A login row of the built-in's left behind kept it here, so the Providers page's line said its accounts "haven't moved yet" for good, with a Move that would install the plugin the user had just removed (plugins#404: Grok, after the plugin, the provider and its sign-ins were removed; #3542: ZCode).

type MoveWhy added in v0.1.552

type MoveWhy struct {
	Code string            `json:"code"`
	Args map[string]string `json:"args,omitempty"`
}

MoveWhy is why a move didn't go through: Code names the case, Args fill in its sentence.

offline   magpie couldn't reach npm (or Bun's download) to install the plugin
install   npm couldn't install it: line

An older magpie also failed a move for an account (lapsed, unserved, account), which the page still reads from migrations.json; since the built-ins are retired every account goes along.

func WhyOf added in v0.1.552

func WhyOf(err error) *MoveWhy

WhyOf is the reason a move failed, nil for one it has no words for.

type Moving added in v0.1.506

type Moving struct {
	User string
	// ID is the vendor's id of the account, where the built-in kept one
	// (WorkBuddy's uid).
	ID        string
	First, On bool
	// Lapsed is an account the vendor already refused: it goes along, but
	// isn't tried.
	Lapsed bool
	// Plan is the plan the account showed, kept beside it until the
	// plugin tells it anew.
	Plan string
	// Own is the agent's own sign-in (its CLI's, its app's), which the
	// plugin reads where the agent keeps it, as the built-in did.
	Own  bool
	Auth map[string]any
}

Moving is one of a built-in's accounts on its way to the plugin.

type OwnBalance added in v0.1.3281

type OwnBalance struct {
	USD float64 `json:"usd,omitempty"`
	// CNY is the amount when it was typed in yuan; USD is then unused
	CNY    *float64  `json:"cny,omitempty"`
	At     time.Time `json:"at"`
	Refill *Refill   `json:"refill,omitempty"`
	// Expiring is the credit on top of the balance, in its currency, each
	// grant good until a day; none for none
	Expiring []Expiring `json:"expirings,omitempty"`
}

OwnBalance is a key's balance as the user typed it: USD left at At, or, with CNY set, that many yuan; with Refill, whole again at each refill.

func ParseOwnBalance added in v0.1.3281

func ParseOwnBalance(amount string) (*OwnBalance, error)

ParseOwnBalance reads a balance as the CLI takes it, an amount in USD ("20", "$20", "12.5 usd") or in yuan ("¥100", "100cny", "100 rmb", "100元"); off for none (nil).

func (OwnBalance) Amount added in v0.1.3295

func (b OwnBalance) Amount() (float64, string)

Amount is the balance typed and its currency, "cny" or "usd".

func (*OwnBalance) UnmarshalJSON added in v0.1.3310

func (b *OwnBalance) UnmarshalJSON(data []byte) error

UnmarshalJSON reads b as saved, and a v0.1.3305 balance's one grant (`expiring`, an object) as the first of its grants: an older magpie reads the list's field as nothing, never as a balance it can't parse.

type Partner added in v0.1.1122

type Partner struct {
	PresetDef
	// IconURL is the partner's logo, kept beside the user's own pictures
	// and shown as Icon.
	IconURL string `json:"iconUrl,omitempty"`
	// Notes is the tagline by language ("en", "zh", "zh-TW", "ja", ...);
	// "en" stands in for a language without one.
	Notes map[string]string `json:"notes,omitempty"`
	// Langs, when set, are the only languages the partner is listed in.
	Langs []string `json:"langs,omitempty"`
	// From and Until bound when it is listed; zero is unbounded.
	From  time.Time `json:"from,omitzero"`
	Until time.Time `json:"until,omitzero"`
	// Plugin is the npm package of a partner listed on the Plugins page:
	// one with no endpoint, which the add sheet never lists. An app from
	// before it drops such an entry, as it has no endpoint.
	Plugin string `json:"plugin,omitempty"`
}

Partner is one entry of the list: a preset, its tagline in each language, the languages it is shown in, and when it is shown.

func Partners added in v0.1.1122

func Partners() []Partner

Partners are the add sheet's partners listed now, in the list's order: what was fetched last, never waited for. A list this process hasn't fetched, or fetched an hour ago, is fetched again behind the call, and the page asked again shows it.

func PartnersNow added in v0.1.1122

func PartnersNow(wait time.Duration) []Partner

PartnersNow is Partners for a command that ends at once, before a fetch behind it could: a list due is fetched first, waited for at most wait.

func PluginPartners

func PluginPartners() []Partner

PluginPartners are the Plugins page's partners listed now, in the list's order, as Partners.

func (Partner) IsPlugin

func (p Partner) IsPlugin() bool

IsPlugin reports whether the partner is listed on the Plugins page, not in the add sheet.

func (Partner) Live added in v0.1.1122

func (p Partner) Live(now time.Time) bool

Live reports whether the partner is listed at now.

type PartnerCount added in v0.1.1126

type PartnerCount struct {
	Day   string `json:"day"` // 2006-01-02, UTC
	ID    string `json:"id"`
	What  string `json:"what"`
	Count int    `json:"count"`
}

PartnerCount is one day's count of one kind for one partner.

func PartnerCounts added in v0.1.1126

func PartnerCounts(now time.Time) []PartnerCount

PartnerCounts are the counts of the days before today, to be sent.

type PatternHit added in v0.1.826

type PatternHit struct {
	Pattern string `json:"pattern"`
	Models  int    `json:"models"`
}

PatternHit is one of a group's patterns and how many of the models served now it matches.

func PatternHits added in v0.1.826

func PatternHits(g Group) []PatternHit

PatternHits are the group's patterns, each with the number of models it matches now — those the group names itself as well — so that one that matches nothing is said, not left an empty group.

type Paused added in v0.1.1155

type Paused struct {
	Member string   `json:"member"`          // "provider/model[:effort]"
	Group  string   `json:"group,omitempty"` // the group in the group whose rule it is; "" the group's own
	Rule   int      `json:"rule"`            // the rule, from 1
	Use    string   `json:"use"`             // the member the rule names: the model, or a group in the group
	When   []string `json:"when"`
	// Folder: the folder the agent said it works in, when the rule holds
	// by folder (ByFolder); "" when it said none, which is outside every
	// folder of a rule's ExceptFolders.
	Folder   string `json:"folder,omitempty"`
	ByFolder bool   `json:"byFolder,omitempty"`
}

Paused is a model a pause rule left out of a request's group.

type PluginCheckin added in v0.1.1085

type PluginCheckin struct {
	ID       string             `json:"id"`
	Name     string             `json:"name"`
	On       bool               `json:"on"`
	Checkins []WorkBuddyCheckin `json:"checkins,omitempty"`
}

PluginCheckin is a plugin's provider that checks in, for Settings: its switch and how each account's last check-in went.

func PluginCheckins added in v0.1.1085

func PluginCheckins() []PluginCheckin

PluginCheckins are the plugins' providers that check in, each with its accounts' last check-ins as kept; asks nothing.

type PresetDef

type PresetDef struct {
	ID        string   `json:"id"`
	Name      string   `json:"name"`
	Icon      string   `json:"icon"`
	Kind      Kind     `json:"kind"`
	Chat      string   `json:"chat,omitempty"`
	Responses string   `json:"responses,omitempty"`
	Anthropic string   `json:"anthropic,omitempty"`
	Decide    string   `json:"decide,omitempty"` // a decision API: the provider only routes (see decide.go)
	Catalog   string   `json:"catalog,omitempty"`
	Website   string   `json:"website,omitempty"`
	SiteHost  string   `json:"siteHost,omitempty"` // a partner's: the host its usemagpie.ai/go Website sends the browser to, which the editor's link reads
	KeysURL   string   `json:"keysUrl,omitempty"`
	NoKey     bool     `json:"noKey,omitempty"`     // local servers: a key is optional
	KeyHint   string   `json:"keyHint,omitempty"`   // the key field's placeholder, when it says more than NoKey's
	Sponsored bool     `json:"sponsored,omitempty"` // shown first, with a tag
	Note      string   `json:"note,omitempty"`      // one line under the name
	Short     string   `json:"short,omitempty"`     // the add sheet's name for it, when Name is long
	Regions   []Region `json:"regions,omitempty"`   // base-URL choices (a relay's regional endpoints, a vendor's plans)
	// RegionLabel names what the Regions choose between, "Region" if unset.
	RegionLabel string `json:"regionLabel,omitempty"`
	// SplitAccounts is set on a partner whose regions are China's and
	// Global's, whose accounts don't work at each other's endpoints (Kimi
	// Code): its region picker says to pick by the account.
	SplitAccounts bool `json:"splitAccounts,omitempty"`
	// KeyPlans: each key may be on a Region of its own (KeyAccount.Plan),
	// a vendor whose plans and pay as you go are sold on keys of their own
	// that only their own endpoints take (Volcengine's Coding and Agent
	// Plans beside its pay as you go, yckonnnn on X). Not a relay's
	// regions, where one key works at all of them.
	KeyPlans bool `json:"keyPlans,omitempty"`
	// HeaderHints name optional request headers the vendor documents, which
	// the editor offers to add; their values are the user's to fill in.
	HeaderHints []string `json:"headerHints,omitempty"`
	// Only, for a plan behind a key that also buys much else, is what its
	// models' ids start with: the rest of the vendor's list is left out.
	// Models are the plan's, for when the list has none of them.
	Only   string   `json:"only,omitempty"`
	Models []string `json:"models,omitempty"`
	// NoList: the vendor has no list of models to ask for (Bedrock's
	// runtime serves no /models), so Models are its list
	NoList bool `json:"noList,omitempty"`
	// Endpoint, for a vendor reached at the user's own resource (Azure
	// OpenAI), is an example of its address: the preset gives no URL, and
	// the editor asks for the one the user's resource is at, with
	// EndpointHint under it.
	Endpoint     string `json:"endpoint,omitempty"`
	EndpointHint string `json:"endpointHint,omitempty"`
	// EndpointNeeded is what the editor says when no endpoint was given.
	EndpointNeeded string `json:"endpointNeeded,omitempty"`
	// Hosts: a vendor serving other makers' models as well as its own
	// (Groq, Ollama Cloud, Azure), whose list is no maker's word on theirs
	Hosts bool `json:"-"`
	// Embeddings and Rerankers are the models of a vendor of retrieval
	// models alone (Voyage AI), which has no list to ask: served on
	// /v1/embeddings and /v1/rerank, kept out of agents' model pickers.
	// A Region's own lists stand over them.
	Embeddings []string `json:"embeddings,omitempty"`
	Rerankers  []string `json:"rerankers,omitempty"`
	// Drawers, Videos, Speakers and Transcribers are the image, video,
	// text-to-speech and speech-to-text models of a plan that names them
	// beside its text models (Alibaba's Token Plans), for a preset with no
	// regions: served on /v1/images, /v1/videos, /v1/audio/speech and
	// /v1/audio/transcriptions, kept out of agents' model pickers.
	Drawers      []string `json:"drawers,omitempty"`
	Videos       []string `json:"videos,omitempty"`
	Speakers     []string `json:"speakers,omitempty"`
	Transcribers []string `json:"transcribers,omitempty"`
}

PresetDef describes one preset.

func AtAddress added in v0.1.1224

func AtAddress(pr PresetDef, addr string) (PresetDef, error)

AtAddress is pr reached at addr: the scheme, host and port of each of its URLs replaced by addr's, its decision API's (oMLX's System One, #1641) among them, which the same server serves. An empty addr leaves pr as it is.

func Preset

func Preset(id string) *PresetDef

Preset finds a preset by id, or by an id it carried before (presetAliases), or a partner listed now or before (partners.go).

func Presets

func Presets() []PresetDef

Presets lists every preset, sponsored ones first within their kind.

type Pricer

type Pricer struct {
	// contains filtered or unexported fields
}

Pricer prices a provider's models as ListPrice and PricedFree do, with what is the provider's alone (the catalogs it is priced from) worked out once: the Providers page prices every model of every provider on each ask, and worked out for each model, twice, it was 4 MB of what forty asks allocated with real accounts.

func (Pricer) Prices

func (r Pricer) Prices(s settings.Settings, model string) (list catalog.Price, listed, free bool)

Prices is model's ListPrice on the Pricer's provider, and its PricedFree under s.

type Protocol

type Protocol string

Protocol is a wire API magpie can speak to an upstream.

const (
	Chat      Protocol = "chat"      // OpenAI Chat Completions
	Responses Protocol = "responses" // OpenAI Responses
	Anthropic Protocol = "anthropic" // Anthropic Messages
	Gemini    Protocol = "gemini"    // Google Gemini's generateContent: served to clients; spoken upstream at a custom provider's Gemini URL, Vertex AI and Factory's generate route
)
const CodeAssist Protocol = "codeassist"

CodeAssist is Google's Code Assist API, which magpie only speaks upstream, to a Gemini CLI or Antigravity account. Not in Protocols: no other provider serves it.

const DecideAPI Protocol = "decide"

DecideAPI is the API a model is set to be asked on (SetModelAPI) when it is a decision model at its provider's System One URL (axelburks on Discord: a relay that serves its chat models and its own decision model under one key, the decision model named as the relay names it). Such a model is a decision model (DecidesModel): a routing group can ask it as a turn begins, and it is refused for a conversation, as Jev is.

func GroupAPI added in v0.1.3157

func GroupAPI(ms []Member) Protocol

GroupAPI is the API an agent that asks each model on one API is wired to ask a routing group on, "" for Chat. It is Responses when a member is served best there (a ChatGPT sign-in, GPT on OpenAI's API or Copilot's, a relay given as a Responses URL) and every other member takes a Responses request as it is too, or translates every request anyway (a Claude Code subscription): no member is then translated that Chat would have relayed, and the ones best on Responses are relayed instead of translated from Chat (zyh6036 on X: a group of subscriptions that all serve Responses was asked on Chat, as only a group whose members were all best there went on Responses, #1594). A group with a member Responses doesn't reach (a Chat-only key, a Messages-only Claude) stays on Chat, so that member keeps being relayed; a Messages-only group stays on Chat too, as the thinking a Claude member takes is known by its own model, not by the group's id.

type Provider

type Provider struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Was are ids the provider had before it was renamed (see Rename):
	// a model still picked by one of them reaches it.
	Was []string `json:"was,omitempty"`
	// Gave are ids it had that another provider took after it (a rename
	// onto one, a provider added under one), each with when: the calls
	// recorded under such an id before then were this one's (Renames).
	Gave []Gave `json:"gave,omitempty"`
	Icon string `json:"icon,omitempty"`
	// IconFrom is the picture's address a custom provider's Icon was
	// fetched from in its editor, shown there again (hoobnn): only a
	// record, never fetched again
	IconFrom string `json:"iconFrom,omitempty"`
	Preset   string `json:"preset,omitempty"` // preset this was created from, if any
	Key      string `json:"key"`              // API key, as typed by the user

	// AccessKeyID and SecretAccessKey are a Volcengine account's access
	// key (TakesVolcAccessKey), what Ark tells its Coding or Agent Plan's
	// windows to (volcengine_usage.go), or a Tencent Cloud account's API
	// key, its SecretId and SecretKey (TakesTencentAccessKey), what TokenHub
	// tells Token Plan 企业版's usage to (tencent_usage.go), or an Alibaba
	// Cloud account's AccessKey ID and Secret (TakesAlibabaAccessKey), what
	// its console tells a Token Plan's usage to (alibaba_usage.go); not the plan's
	// inference key in Key. They are kept, backed up and synced as the keys are: the Secret
	// is never sent to the GUI, and a backup without keys has neither.
	AccessKeyID     string `json:"accessKeyID,omitempty"`
	SecretAccessKey string `json:"secretAccessKey,omitempty"`

	// KeyName names the key in use, and Keys are the provider's other
	// accounts: keys saved to switch to (see keys.go).
	KeyName string       `json:"keyName,omitempty"`
	Keys    []KeyAccount `json:"keys,omitempty"`
	// KeyProtocol, when set, is the one protocol the first key is good
	// for: a relay that hands out one key for Anthropic and another for
	// OpenAI (see KeyAccount.Protocol).
	KeyProtocol Protocol `json:"keyProtocol,omitempty"`
	// KeyWeight is the first key's weight (see KeyAccount.Weight).
	KeyWeight int `json:"keyWeight,omitempty"`
	// KeyPlan is the first key's plan (see KeyAccount.Plan).
	KeyPlan string `json:"keyPlan,omitempty"`

	// Base URLs, one per protocol the vendor serves natively. magpie appends
	// the usual paths: chat/responses bases end in /v1 (OpenAI style),
	// the Anthropic base is the root (what ANTHROPIC_BASE_URL takes).
	Chat      string `json:"chat,omitempty"`
	Responses string `json:"responses,omitempty"`
	Anthropic string `json:"anthropic,omitempty"`
	// Gemini is the base of Google's Gemini API, or of one that answers as
	// it does (…/v1beta): models/{model}:streamGenerateContent is asked
	// under it, with the key in x-goog-api-key, and models under it lists
	// them (#1346).
	Gemini string `json:"gemini,omitempty"`
	// GeminiFilled is that magpie filled Gemini in once, for a provider
	// at AI Studio's OpenAI-compatible URL (aiStudioNative): a Gemini URL
	// the user cleared after that stays empty.
	GeminiFilled bool `json:"geminiFilled,omitempty"`
	// Decide is the base of a decision API (TypeSafe's System One, which
	// Jev answers), for routing groups' choices of model and effort. The
	// provider may also serve conversations on the other endpoints.
	Decide string `json:"decide,omitempty"`
	// BaseAPI is the API the user gave a custom provider's Base URL as,
	// in its editor: "chat", "responses", "anthropic", "gemini" or "decide". The
	// editor shows that pick again, where it would otherwise show the
	// first API with a URL (01huadalang: Responses picked and saved came
	// back as OpenAI compatible). Requests go by which URLs are set.
	BaseAPI string `json:"baseAPI,omitempty"`

	// Fallback is where a request goes when this provider can't take it —
	// out of quota, rate limited, overloaded or down — before any of the
	// reply has been sent: models as agents pick them (provider/model),
	// tried in order.
	Fallback []string `json:"fallback,omitempty"`

	// Routing is how requests spread over the keys or accounts it has on:
	// "" smart, the first while it has quota to spare, then whichever has
	// the most; "order" in order, the next one only when the one before
	// can't take it; "rotate" each in turn; "usage" the least used first;
	// "pace" the one with the most remaining allowance per hour until
	// its window resets first, so less allowance is lost at reset.
	// The window can be shorter than a week. "weight" by each key's
	// weight, a key with 3 taking three requests to one with 1's.
	// "drain" one until it is used up, then the next, which keeps them
	// when an earlier one renews (routes.Drain). Whichever it is, one out
	// of credit, out of quota, rate limited or failing is passed over for
	// as long as that lasts.
	Routing string `json:"routing,omitempty"`

	// Sink sends a key or account that a 429 rate limited while it still
	// had quota to the back of the order Routing gives (01huadalang): it
	// is tried again only after every one not rate limited since — so the
	// load goes round, rather than back to the first each time its rest
	// ends. Off, the default, it keeps its place. Not for "rotate", which
	// goes round already. See gateway.sink.
	Sink bool `json:"sink,omitempty"`

	// UseFirst puts its keys or accounts ahead of the other providers'
	// where Smart weighs them together: a group of several providers'
	// models (hzh_1119 on Discord: an OpenAI API key's monthly credit
	// spent before the ChatGPT subscription serving the same models). One
	// resting after a failure, out of credit or out of quota (a 429
	// insufficient_quota) is passed over as ever, and one all but used up
	// goes with the others that are. Off, the default, Smart goes as it
	// always has (routes.Seat.Lead).
	UseFirst bool `json:"useFirst,omitempty"`

	// NoStandIn keeps another model's request off it (sonnnnnnnnnnnna on
	// X): a request that went first to a provider not so marked, such as
	// a local uncensored model that is down or out of room, is never sent
	// on to it as a fallback or a routing group's next member, so text
	// written for that model can't get a vendor's account banned. One
	// that goes first to it, or to another provider so marked, still
	// moves on as ever. Off, the default, it stands in for any. See
	// gateway.standInsOut.
	NoStandIn bool `json:"noStandIn,omitempty"`

	// Affinity is how long a conversation stays with the key or account
	// that answered it, so the vendor's prompt cache it filled is read
	// again rather than lost (see Affinities): "" auto, "session",
	// "turn", "off", "strict".
	Affinity string `json:"affinity,omitempty"`

	// KeepLogin, on Codex's or Claude Code's subscription, keeps the agent
	// signed in to the account the user made first: magpie doesn't sign it
	// in to another when that one runs low or out (#524). The gateway still
	// spreads its requests over the accounts that are on, as Routing says.
	KeepLogin bool `json:"keepLogin,omitempty"`
	// KeepLoginAs, with KeepLogin, is the account the agent is kept signed
	// in to whichever is first in the order the gateway tries them: the one
	// the user uses the agent as, while the first is only the one whose
	// allowance is spent first (#524). Empty, it is the first.
	KeepLoginAs string `json:"keepLoginAs,omitempty"`
	// SwitchOnly, on Codex's subscription, has magpie only move Codex's
	// own sign-in (auth.json) to the next account with room and back:
	// Codex's requests then go straight to OpenAI, never through the
	// gateway for account failover, however many of its accounts are on
	// (#1907). On Claude's subscription it keeps the accounts to Claude
	// Code's own sign-in, which magpie still moves: the gateway serves no
	// request on them (KeptToAgent; myduso on Discord).
	SwitchOnly bool `json:"switchOnly,omitempty"`
	// RestartApp, on Codex's subscription, has magpie restart the Codex
	// app's own app-server for a change it makes by itself that the app
	// works without: the switch back once the account it moved off has
	// room (SwitchWhenSpent), and giving Codex its account back at the
	// reset. The ChatGPT app shows an ended app-server as an error and
	// relaunches (#4550), so it is off unless the user turns it on
	// (atom0964 on Discord); the app then stays on its account until it
	// is restarted, from the switch notice or by hand. A switch the user
	// makes, a Connect or Disconnect, and whatever leaves the app on a
	// used-up account (a switch off it, becoming its provider for it)
	// restart it either way: the app greys Send there (8b0132b3d).
	RestartApp bool `json:"restartApp,omitempty"`
	// KeepSelf, on a Remote magpie that turned out to be this magpie
	// (SelfAnswered), keeps it in routing anyway: left alone, such a
	// provider is left out (SelfLeftOut). It is this computer's own, as
	// sync's copy of the provider on the other computer points at a
	// magpie that is not that one (hanslin1666 on Discord).
	KeepSelf bool `json:"keepSelf,omitempty"`
	// ThisDevice keeps the provider on this computer: sync never sends it
	// out, and what another computer's sync brings neither replaces nor
	// removes it. For a local model that exists only here (treydtw on X).
	ThisDevice bool `json:"thisDevice,omitempty"`

	// MaxConcurrency is how many requests may be out at the vendor at once
	// on each of its keys or accounts (Discord, Lemon: a Codex account is
	// risk-controlled past five or six at once); the rest wait their turn,
	// in the order they came (see Concurrency). nil follows what a
	// plugin's provider says it takes, else none; 0 is no limit.
	MaxConcurrency *int `json:"maxConcurrency,omitempty"`
	// MaxAccounts is how many of its accounts or keys take requests at
	// the same time (01huadalang on Discord: ZCode's firewall blocks the
	// address that three of its accounts ask from at once, and two are
	// fine). Routing goes over the first that many it would ask, in its
	// order and not resting; the others wait as reserves until one of
	// those rests (out of quota, rate limited, failing). nil follows what
	// a plugin's provider says, else none; 0 is no limit (see AtOnce).
	MaxAccounts *int `json:"maxAccounts,omitempty"`
	// AccountConcurrency is, for one account or key, its own limit over
	// MaxConcurrency (#892): an account by its name in lower case, a key
	// by its KeyID; 0 there is no limit for it. One not in it takes the
	// provider's (see LaneLimit).
	AccountConcurrency map[string]int `json:"accountConcurrency,omitempty"`
	// AccountWeights is, for a subscription, each account's weight under
	// Weighted routing, by its name in lower case (rubbzha on X: a Max
	// account and a Pro one shared by how much more one allows); one not
	// in it weighs 1. A key's weight is its own (KeyAccount.Weight).
	AccountWeights map[string]int `json:"accountWeights,omitempty"`
	// QueueLimit is how many requests may wait for a slot of each key or
	// account at once (#892); one more is turned away as the queue being
	// full. 0 is no bound.
	QueueLimit int `json:"queueLimit,omitempty"`
	// QueueWait is how long, in seconds, a request waits for a slot before
	// it is turned away as having waited too long (#892). 0 waits as long
	// as it takes.
	QueueWait int `json:"queueWait,omitempty"`
	// MaxRPM is how many requests a minute each of its keys or accounts
	// sends the vendor, over a rolling 60 seconds (coeo91 on Discord:
	// OpenRouter's free models take 20 a minute, which a limit at once
	// can't keep to); one more waits for room (see RPMLimit). 0 is no
	// limit.
	MaxRPM int `json:"maxRPM,omitempty"`
	// MaxImages is the most images one request to it may carry, by the
	// user's word: by model id, "*" for all its models (100milionseek's
	// and Coarena's APIs take 8 a request and refuse the ninth with 400,
	// #6849). The count is over the whole conversation, tool results
	// included. Past it the oldest images are left out, each replaced by
	// a line of text saying so, the latest user message's kept whole
	// (gateway.withinImageCap). None set leaves it to what a refusal that
	// names its cap teaches (gateway.imageCaps). See ImageCapOf.
	MaxImages map[string]int `json:"maxImages,omitempty"`
	// QuotaRest is how many minutes one of its keys sits out once the
	// vendor says it is out of its allowance without saying when it is
	// back (#1772: Ollama Cloud's weekly limit); 0 is the gateway's own
	// quarter of an hour. A time the vendor names stands over it.
	QuotaRest int `json:"quotaRest,omitempty"`
	// QuotaResetAt is the time of day a key of it out of its allowance is
	// back, when its vendor refuses for a day's allowance without saying
	// when (#2008: a free tier's "today's free-model token quota"): "08:00"
	// on this computer's clock, or "00:00+08:00" on the vendor's. Set, it
	// stands over QuotaRest; a time the vendor names stands over both.
	QuotaResetAt string `json:"quotaResetAt,omitempty"`
	// RestCap is the most, in minutes, one of its keys or accounts sits
	// out while it keeps failing or keeps being rate limited as soon as
	// its rest is over (#2008); 0 is the gateway's own, 10 minutes for a
	// failure and 30 for a rate limit. The vendor's own "try again in"
	// still stands over it. RestCapOff (-1): no rest at all after a
	// failure that says nothing of why, a rate limit's as the gateway's own.
	RestCap int `json:"restCap,omitempty"`
	// LimitRestOff keeps its keys and accounts asked when the vendor says
	// they are out of quota or answers 429 (zoecats on Discord: a local
	// aggregator says "quota exhausted" for a moment while it switches
	// upstreams, and a rest of half an hour held every request back until
	// magpie restarted). Off by default: such a refusal rests it as ever.
	LimitRestOff bool `json:"limitRestOff,omitempty"`

	// PriceRate is what the provider charges against the official price
	// (ITea312, #819): a relay that bills 0.8× or 1.5× of it. It scales the
	// provider's list price, else its maker's, wherever a cost is counted;
	// a price the user set for one of its models stands as set. 0 is the
	// price as listed; at most three decimals (PriceRateOK).
	PriceRate float64 `json:"priceRate,omitempty"`
	// CountFree is the user's word that the provider costs them nothing
	// (jiabubu on Discord: ModelScope's free daily quota): every model of
	// it counts as free where routing weighs that, as a model its vendor
	// lists free does (FreeModel: Free first spends it first, Cheapest
	// weighs it at nothing). Prices and the costs Usage counts stay as
	// listed: it says what to spend first, not what a call cost.
	CountFree bool `json:"countFree,omitempty"`
	// Billing is the user's word on how the provider bills: BillingPlan
	// or BillingPAYG (EV_John_Liu on X); "" has magpie read it
	// (BillingKind). It only marks the provider on Providers and Routing.
	Billing string `json:"billing,omitempty"`
	// RateWindows are the time-of-day windows it bills at its own rate
	// (#2463): a peak at 2× or 3×, a discount off peak. The first window
	// that holds a call's time multiplies the price again, on top of
	// PriceRate; outside every window the price rate alone counts. At
	// most RateWindowsMax of them (CheckRateWindows).
	RateWindows []RateWindow `json:"rateWindows,omitempty"`

	// Headers are extra HTTP request headers sent to the vendor, as the user
	// typed them but for ${sessionId} and ${threadId} in a value, the
	// request's conversation ids (SentHeaders, conversation.go). They ride on every request magpie makes to a plain
	// key+URL provider — forwarded calls, connectivity tests, and model-list
	// fetches — applied after the auth headers, so the user can override those
	// when a gateway insists on a private scheme. Signed-in agent accounts
	// ignore them: their auth is the agent's own.
	Headers map[string]string `json:"headers,omitempty"`

	// ExtraBody are JSON fields added to the body of every request to the
	// vendor (#1604), filling in what the body lacks, or replacing it for a
	// name written "!name"; ${sessionId} and ${threadId} in a value are the
	// conversation's ids (extrabody.go, conversation.go). Signed-in agent accounts ignore it, as Headers.
	ExtraBody ExtraBody `json:"extraBody,omitempty"`

	// ReplyHeaders are headers of the vendor's reply passed on to the
	// agent, beside DefaultReplyHeaders, whatever their case (#4145): a
	// relay's own request id (X-Oneapi-Request-Id), for the agent's side
	// to match with the relay's logs. Streamed or whole, an error too, on
	// every API, translated or not; only the reply the agent is given
	// has its headers passed on. One magpie writes itself, or that would
	// act on magpie's address, never is (ReplyHeaderPassable).
	ReplyHeaders []string `json:"replyHeaders,omitempty"`

	// PassHeaders are headers of the agent's request passed on to the
	// vendor as it sent them, whatever their case (3jRzfF52Qx on X): a
	// value that changes per request or per client, which a fixed Header
	// can't give. The client's stands over a Header of the same name;
	// with none sent the Header goes. Every API, count_tokens, a group's
	// member, a plugin's fetch; a signed-in account's signing has the
	// last word. One that carries magpie's key or the connection's own
	// never is (RequestHeaderPassable).
	PassHeaders []string `json:"passHeaders,omitempty"`

	// Searches says the vendor answers a web search tool offered on its
	// Anthropic or Responses API by itself (web_search_20250305,
	// web_search): a relay in front of Anthropic's or OpenAI's API, which
	// magpie can't tell from its host. A request offering one then goes to
	// it as the client sent it, rather than given magpie's search (#359).
	Searches bool `json:"searches,omitempty"`

	// CodexAsSent has a request Codex sends on the Responses API go to it
	// as Codex sent it, its model name alone swapped: a relay that checks
	// it is Codex's own (#1758: "Codex 客户端请求特征无效", 10014), which
	// the shape magpie fits it to for another backend (Responses Lite's
	// additional_tools lifted into tools, the tool search as a function,
	// OpenAI-only fields left out) fails. Off, the default, keeps that
	// fitting, which a backend that isn't OpenAI's needs (#350).
	CodexAsSent bool `json:"codexAsSent,omitempty"`

	// ImageFilesOff, `image-files=off`, has DeepSeek's own API sent an
	// agent's inline images inline on every turn. By default each goes up
	// once through DeepSeek's Files API, for a day, and the turns name it
	// by its file id (gateway's deepseek_files.go, #5407).
	ImageFilesOff bool `json:"imageFilesOff,omitempty"`

	// UpstreamProviders, on a Remote magpie, `upstream-providers=on`, names each
	// of its models in the agents' lists by the provider serving it on
	// the other magpie, the first in a chain of them: "Claude Sonnet 5 ·
	// Office › RelayA", whatever that magpie's own Provider in model names
	// is, so one model from two of its providers is told apart here
	// (lcc580 on X). Off, the default, names each as that magpie's list
	// does. The ids stay as they are: office/relaya/claude-sonnet-5.
	UpstreamProviders bool `json:"upstreamProviders,omitempty"`

	// PromptAsWritten, on Antigravity's subscription, has the system prompt
	// go to Google exactly as the agent wrote it. By default the few lines
	// Google answers with a 429 "Resource has been exhausted" whatever
	// quota is left (Claude Code's billing line, the Claude Agent SDK's
	// identity line, Codex's GPT-5 identity lines, Hermes Agent's earlier
	// default persona, oh-my-pi's RFC 2119 line) go reworded with the same
	// meaning, the billing line left out, which Google lets through and the
	// model reads the same (gateway's antigravityCloak). Set with `magpie provider set antigravity
	// prompt=as-written`; prompt=default turns it back.
	PromptAsWritten bool `json:"promptAsWritten,omitempty"`

	// AdditionalTools says the provider's Responses API takes an
	// additional_tools input item, as OpenAI's does: a deferred tool an
	// Anthropic client's tool search loaded goes to it in such an item
	// where the search loaded it, not in the top-level tools, which keeps
	// the prompt's cached prefix (#2660). OpenAI's own API and a ChatGPT
	// (Codex) account are sent one without it (#4738: the ChatGPT backend
	// takes the item where it was loaded, and its cache is kept); another
	// vendor isn't unless this is set, since xAI's turns the item away
	// (#350).
	AdditionalTools bool `json:"additionalTools,omitempty"`
	// AdditionalToolsOff, `additional-tools=off`, sends a loaded tool in
	// the top-level tools even where magpie's default would send the item.
	AdditionalToolsOff bool `json:"additionalToolsOff,omitempty"`

	// PassErrors, `errors=pass`, is the user's word that the client, not
	// magpie, deals with what the provider's errors say (ne9ko9 on
	// Discord): a request to it is asked once, its error goes to the
	// agent as it came (its status, and its body as written where the
	// agent's API is the provider's own, else in the agent's shape with
	// the vendor's type, code and words), nothing about it is inferred
	// (a prompt too long, a busy relay), it is not asked again in place
	// or of a fallback or a group's next member, and none of its keys
	// rests for it. Off, the default, magpie handles them. Only a provider
	// of a key takes it (TakesPassErrors).
	PassErrors bool `json:"passErrors,omitempty"`

	// Patience is how many seconds more a request to this provider alone,
	// not through a group, may be kept once it has failed in a way that
	// passes (overloaded, unavailable, rate limited for a moment) and the
	// same-one retries are spent, as a group's Patience is (zoecats on
	// Discord): 0 keeps it PatienceDefault, PatienceOff hands the agent
	// the error at once, and it is at most PatienceLongest. Set with
	// `magpie provider set <id> patience=`; a group it is in keeps the
	// group's own.
	Patience int `json:"patience,omitempty"`

	// Socket has a Responses API provider's turns go over the Responses
	// WebSocket magpie speaks to chatgpt.com (#5781, matrix0487 on
	// Discord): SocketAuto tries it and falls back to HTTP, and leaves the
	// host to HTTP for a while once it refuses the handshake, as
	// chatgpt.com is; SocketOn tries it every time and falls back without
	// that; SocketOff is HTTP alone. "", the default, is auto on OpenAI's
	// own API and HTTP alone elsewhere (SocketMode). Only a provider of a
	// key with a Responses URL takes it (TakesSocket). Set with `magpie
	// provider set <id> socket=`.
	Socket string `json:"socket,omitempty"`

	// NativeCompaction has Codex's compaction_trigger go to the provider
	// as Codex sent it, and the compaction the provider writes back go to
	// Codex as it came (#1099), where magpie otherwise asks the model for
	// a summary and hands Codex that (its "magpie1:" compaction). Only a
	// provider whose wire carries it takes it (CarriesCompaction): a
	// Responses API (Sub2API, a remote magpie), a ChatGPT account, GitHub
	// Copilot's GPT models. Such a compaction is sealed by the key or
	// account that wrote it, so its conversation stays there, or is
	// refused, never sent elsewhere to be dropped. Off, the default,
	// keeps magpie's summary.
	NativeCompaction bool `json:"nativeCompaction,omitempty"`

	// MagpieUserAgent has every request go to the vendor with magpie's own
	// User-Agent (magpie/<version>). Off, the default, a key+URL provider is
	// sent the User-Agent the agent gave (pi, opencode, Claude Code…) as it
	// gave it (#1851, nb5p on Discord): a coding plan that serves only
	// agents it names, or the user's own gateway behind magpie, knows them
	// by it. One the agent didn't give, and magpie's own requests, go as
	// magpie either way. A signed-in account, a plugin's and one that goes
	// as a client of its vendor's own keep the identity their signing
	// gives (see PassesUserAgent). The opt-in "passUserAgent" it replaces
	// is the default now, so a file that still says it reads the same.
	MagpieUserAgent bool `json:"magpieUserAgent,omitempty"`

	// PinUpstream, on the Cline API, has its DeepSeek models answered only
	// by DeepSeek's own API (White Immortal on Discord) and its GLM models
	// only by Z.ai's (sdytman on Discord): Cline routes a model through an
	// AI gateway that may serve it from any host, and the maker's own
	// keeps its prompt cache. Since 2026-11-06 Cline refuses the
	// providerOptions field that pinned all but glm-5.3-flash, so only
	// that model is pinned now (#5442); the saved value is kept as set.
	// See ClinePin.
	PinUpstream bool `json:"pinUpstream,omitempty"`

	// AuthHeader is which header the key goes in on a third-party
	// Anthropic API, which is sent both x-api-key and Authorization:
	// Bearer by default (AuthBoth). A vendor that refuses the two together
	// (Aloha on Discord: "x-api-key 和 Authorization 不可以同时存在") is
	// sent one, AuthXAPIKey or AuthBearer: picked in the editor, or
	// learned from that refusal (RetryOneAuth). Anthropic's, Bedrock's and
	// Azure's own APIs, which take x-api-key alone, ignore it.
	AuthHeader string `json:"authHeader,omitempty"`

	// Unredacted has requests to a provider go as the agent wrote them,
	// unmasked by Settings' redaction, which keeps secrets from vendors:
	// for a model on this machine or the local network (Ollama, LM Studio,
	// a vLLM box; lc on Discord). It is the user's word, not the
	// address's (AcMilan on Discord), on a subscription or a plugin's
	// provider too (isee1_1 on Discord): the editor cautions while it is
	// on for one not local, and a relay run locally, or Ollama's cloud
	// models, pass a request on to a vendor whatever the address. A
	// signed-in account keeps it with its model picks (withPicks). See
	// SkipsRedaction.
	Unredacted bool `json:"unredacted,omitempty"`

	// InsecureTLS has magpie take the certificate of the provider's own
	// HTTPS host as it is, unchecked (#2383, fangzhengjin: a vLLM on the
	// LAN, Ollama behind a self-signed cert). Only a provider the user
	// added takes it (TakesInsecureTLS), and only for the hosts of its own
	// base URLs (UncheckedHosts); see Via.
	InsecureTLS bool `json:"insecureTLS,omitempty"`

	// HTTP1 has magpie speak HTTP/1.1 to the provider's own hosts, never
	// HTTP/2 (kepner_53726 on Discord: a company gateway whose HTTP/2
	// connections broke mid-reply with "tls: bad record MAC" while
	// HTTP/1.1 to it held). Only a provider the user added takes it
	// (TakesInsecureTLS), for the hosts of its own base URLs
	// (UncheckedHosts); see Via.
	HTTP1 bool `json:"http1,omitempty"`

	// ClientCert and ClientKey are the PEM files of a client certificate
	// magpie shows the provider's own HTTPS hosts when they ask for one,
	// and ServerCA a PEM CA their certificate may be signed by beside the
	// system's roots (#5596, clxsh, and hhdaxia on X: Remote magpie to a
	// magpie at home behind an Nginx that requires a client certificate,
	// or one with `magpie mtls` on). Only a provider the user added, and
	// Remote magpie, takes them (TakesClientCert), for the hosts of its
	// own base URLs (UncheckedHosts), on every request made for it:
	// models, the connection test, requests, quotas; see Via.
	ClientCert string `json:"clientCert,omitempty"`
	ClientKey  string `json:"clientKey,omitempty"`
	ServerCA   string `json:"serverCA,omitempty"`

	// ServerPin is the SHA-256 (lower-case hex) of the one server
	// certificate its own HTTPS hosts are taken with, trusted as it is
	// (Zhangzhangi on X: a magpie at home on a domain of its own with a
	// self-signed certificate, which macOS calls not standards
	// compliant): the certificate's chain, name and dates aren't checked
	// there, and any other certificate is refused. "" checks them as
	// usual. Taken where TakesClientCert is; see Via and PeekServerCert.
	ServerPin string `json:"serverPin,omitempty"`

	// Resolve connects a host name of the provider's own base URLs to
	// the places listed, as curl's --resolve does (quantum_lsfc on X: a
	// managed network sends some domains to an internal L4 SNI gateway,
	// an IP in the base URL fails, and /etc/hosts can't be edited): only
	// the TCP connection moves, the URL's name stays for TLS and Host. A
	// place is an IP address (with a port if it has its own) or
	// "dns:<name>", looked up at each connection; they are tried in
	// order, and when none connects the name is dialled as usual. Not
	// used through a proxy, which connects to the name itself. Taken where
	// TakesResolve is; a plugin's requests are made by its host, which has
	// no way to be told. See netproxy.WithResolve and CheckResolve.
	Resolve map[string][]string `json:"resolve,omitempty"`

	// Proxy is the proxy magpie's requests to this provider go through
	// (#237: Codex through one, a vendor at home without): "" follows
	// the global one (Settings' Proxy, the environment's, the system's),
	// "direct" none, anything else the proxy's address (http://, https://,
	// socks5://; host:port means http). Signed-in accounts keep it too.
	Proxy string `json:"proxy,omitempty"`
	// AccountProxies is, for a provider holding several accounts or keys
	// (Codex's accounts, a relay's keys…), the proxy of each one that has
	// one of its own, as Proxy takes one: an account by its name in lower
	// case, a key by its KeyID. One not in it follows Proxy (see
	// ProxyChoice).
	AccountProxies map[string]string `json:"accountProxies,omitempty"`
	// AccountModels is, for a provider holding several accounts or keys,
	// the models each one the user narrowed serves, and no others (#474):
	// an account by its name in lower case, a key by its KeyID. One not in
	// it serves every model the provider does (see account_models.go).
	AccountModels map[string][]string `json:"accountModels,omitempty"`
	// AccountModelsAll is the keys, by KeyID, the user set back to every
	// model (All models, or `accountmodels` with none): a Fetch models
	// that ticks a key's own list for it (key_models_refresh.go) leaves
	// these as the user set them.
	AccountModelsAll map[string]bool `json:"accountModelsAll,omitempty"`
	// AccountCaps is, for a subscription, the share (1–99) of its usage
	// windows each account the user capped is used to at most, by its name
	// in lower case: past it, routing takes the account for used up until
	// the window renews (see account_caps.go). One not in it has no cap.
	AccountCaps map[string]int `json:"accountCaps,omitempty"`
	// AccountWindowCaps is, for a subscription, the share of each usage
	// window an account is used to at most where the user set one for that
	// window apart (willz on Discord), by the account's name in lower case
	// and then the window's WindowCapID: 1–99, or 100 for none on it. A
	// window not in it takes the account's AccountCaps.
	AccountWindowCaps map[string]map[string]int `json:"accountWindowCaps,omitempty"`
	// AccountWindowAmounts is, for a subscription, the fixed amount of a
	// window's own unit (credits, requests, tokens) an account is used to
	// at most where the user set one in place of a share (9won_25273 on
	// Discord), by account and window as AccountWindowCaps. A window has
	// one or the other.
	AccountWindowAmounts map[string]map[string]float64 `json:"accountWindowAmounts,omitempty"`
	// CapStop, for a subscription whose accounts are capped, ends there
	// (plugins#349): while every account is held at its cap, a request is
	// answered 429, as the vendor would, rather than sent on to Fallback.
	// Off, the default, a fallback takes it. See gateway.Server.plan.
	CapStop bool `json:"capStop,omitempty"`
	// CapCareful is a capped account's usage read again before a request
	// is sent near its cap, and the account held while its usage can't be
	// told (plugins#349): unknown is not spent. Off, the default, routing
	// goes by the last reading, read again each minute. See
	// gateway.carefulDoubt.
	CapCareful bool `json:"capCareful,omitempty"`
	// AccountNames is, for a subscription, the name the user gave each
	// account they named (#1515: a team's seats told apart by who holds
	// them, not by a masked email), by the account's name in lower case.
	// It is magpie's own: the vendor's or plugin's sign-in never sees it
	// (see account_names.go).
	AccountNames map[string]string `json:"accountNames,omitempty"`
	// KeySpendCaps is, for a provider of API keys, how much each key the
	// user capped may spend, in USD as the Usage page prices its calls,
	// a day, a month or in all, by its KeyID: past it, routing takes the
	// key for used up until the period renews (see key_spend.go).
	KeySpendCaps map[string]SpendCap `json:"keySpendCaps,omitempty"`
	// KeyOwnBalances is, for a provider of API keys whose vendor tells no
	// balance, what the user typed is left on each key, by its KeyID: the
	// key's card shows it less what magpie priced its calls at since
	// (see key_balance_own.go).
	KeyOwnBalances map[string]OwnBalance `json:"keyOwnBalances,omitempty"`
	// KeyPriceRates is, for a provider of API keys, the price rate of each
	// key that bills at its own (@tnt12231 on X: one relay, keys in groups
	// at 0.5× and 1.2×), by its KeyID. A key not in it bills at PriceRate
	// (see key_rate.go).
	KeyPriceRates map[string]float64 `json:"keyPriceRates,omitempty"`
	// TopUpRate is, for a relay built on sub2api, what one of its dollars
	// cost the user (@YIXIE233 on X: ¥7 for $100 is 0.07): each key's
	// group rate is read from the relay (key_rate_read.go) and the key
	// bills at that times this, unless it has a rate in KeyPriceRates.
	// 0 is none: no group rate is read.
	TopUpRate float64 `json:"topUpRate,omitempty"`

	// BalanceURL, when set, is where the vendor tells what is left on a
	// key, asked with the key the way a chat request carries it; BalancePath
	// picks the amount out of the JSON reply (see balance.go). The vendors
	// magpie knows need neither.
	BalanceURL  string `json:"balanceURL,omitempty"`
	BalancePath string `json:"balancePath,omitempty"`
	// BalanceMethod is how BalanceURL is asked: "" (or GET), or POST with
	// no body, for an endpoint that answers only a POST (#2368). Any other
	// is refused when the balance is read (balanceMethodOf).
	BalanceMethod string `json:"balanceMethod,omitempty"`
	// NoBalanceProbe turns off the look for a balance query on a relay
	// added with no Balance URL (balance_probe.go).
	NoBalanceProbe bool `json:"noBalanceProbe,omitempty"`
	// BalanceToken is what a vendor tells the whole account's balance to,
	// where a key is told only what is left on itself: AiHubMix's system
	// access token, or a new-api relay's for its /api/user/self named in
	// BalanceURL (see TakesBalanceToken). It is asked with nothing else but
	// the provider's headers, when the endpoint is one named.
	BalanceToken string `json:"balanceToken,omitempty"`
	// ZhipuTeam, for a Zhipu or Z.ai key on a team's GLM Coding Plan, is
	// the team's organization and project, from the BigModel console: the
	// team's windows are told to the key only with them (see
	// zhipuKeyTeamWindows). nil for a key of the user's own plan.
	ZhipuTeam *ZhipuTeam `json:"zhipuTeam,omitempty"`
	// Vertex, for a Google Vertex AI provider, is the project and location
	// its requests go to and the Google credentials that sign them, in
	// place of a key (see vertex.go).
	Vertex *Vertex `json:"vertex,omitempty"`

	// ModelsURL, when set, is where the vendor lists its models, for one
	// that lists them away from the base URL requests go to (Xiaomi MiMo's
	// plans are served at their own hosts, the list at api.xiaomimimo.com).
	ModelsURL string `json:"modelsURL,omitempty"`
	// ListOff is the editor's Fetch the model list unticked (axelburks on
	// Discord): the vendor's list is never asked for, by a Fetch, a
	// Refresh, a test or a schedule, and the models served are the ids the
	// user added alone, not models.dev's nor a list fetched before. For a
	// vendor whose list names models by ids that can't be asked for
	// (Volcengine Ark's, where each is asked by an endpoint id the user
	// made). A key's provider only (ListsOff).
	ListOff bool `json:"listOff,omitempty"`

	// Models the user chose to expose. Empty means "the preset's picks, or
	// everything the vendor lists when that list is short" — unless NoModels.
	Models []string `json:"models,omitempty"`
	// NoModels is the user's Select none (#1818): with no Models picked,
	// none of its models are served — not to agents, not to any routing
	// group, not by a "provider/model" id — while its balance and usage
	// are still read and shown. Without it, no picks is the vendor's list
	// as ever, so a file saved before it reads as it did. A pick clears it.
	NoModels bool `json:"noModels,omitempty"`
	// BestInFamily is the editor's Best in family (Steven on Discord): with
	// no Models picked, of the vendor's list only the newest model of each
	// family is served (catalog.BestInFamily), so Opus 5.6, once listed,
	// takes Opus 5.5's place by itself. A request that names another of its
	// models is still served, as one that names a model left unpicked is. A
	// pick or Select none clears it (normalize); a file without it reads as
	// the vendor's list, as before.
	BestInFamily bool `json:"bestInFamily,omitempty"`
	// PickedFrom are the models the vendor listed when Models were saved: one
	// listed since is served beside picks that held every one listed then
	// (withNewlyListed), and one listed then and left unpicked stays out.
	PickedFrom []string `json:"pickedFrom,omitempty"`
	// Delisted are picks the provider's list stopped listing (dropGonePicks):
	// out of Models, so not served, until a list has them again, when they
	// go back among the picks (relistPicks). A plugin's list shrinks for a
	// while and comes back (多喝热水 on Discord: Our Free Model lists its
	// account channels' models only once its service has read them after a
	// restart, and a free pool it finds down leaves its list until it is
	// up), and the user's picks came back with it no more. Every save keeps
	// it but for what it picks again; Select none clears it.
	Delisted []string `json:"delisted,omitempty"`
	// DelistedAt is when the list left out the last pick still in Models,
	// so that every pick is in Delisted: none is served until then and
	// pickWait after it (waitsForPicks), and the list is served as if none
	// were picked from then on. A vendor takes a model off for good too:
	// WorkBuddy AI's free deepseek-v4.1-flash, a Free plan account's one
	// pick, left its list for hy3, and the account was served none
	// (maxleebeta on Discord). Zero, while some pick is still in Models, or
	// for picks set aside before it was kept.
	DelistedAt time.Time `json:"delistedAt,omitzero"`
	// RefreshEvery, for a provider of the user's own, is how often the
	// gateway fetches its model list by itself ("6h", "1d"; none, only when
	// asked), as Fetch models does (#2135). See autolist.go.
	RefreshEvery string `json:"refreshEvery,omitempty"`
	// AutoInclude are patterns over a model's id (a glob with *, or a
	// regular expression after "re:"): a model a fetch newly lists that one
	// matches joins Models, beside the picks already there (#2135).
	AutoInclude []string `json:"autoInclude,omitempty"`
	// Unlisted keeps the provider's own models out of the list agents see:
	// it serves only through the routing groups it is in, and by its
	// "provider/model" ids.
	Unlisted bool `json:"unlisted,omitempty"`
	// HiddenDrawers are the provider's image models the user unticked in
	// its editor (321sssrt on X: an OpenAI key lists a dozen): left out of
	// every list one is picked from (Settings › Models › Images, another magpie's
	// list, Aside's) and of Automatic's choice, as an unticked chat model
	// is left out of the agents' lists. A deny list beside Models, not in
	// it: Models is what agents chat with, empty meaning the vendor's list,
	// so an image model put there would be offered to chat with, and
	// hiding one would mean picking every chat model. A request that names
	// one still draws with it, and so does the one Settings › Models › Images
	// names: a hidden pick is shown as picked, and said to be hidden.
	HiddenDrawers []string `json:"hiddenDrawers,omitempty"`
	// HiddenVideomakers are its video models unticked in its editor, as
	// HiddenDrawers are its image models (axelburks on Discord: a
	// Volcengine Ark key lists a dozen Seedance models): left out of
	// what lists video models to pick from (generate_video's, another
	// magpie's, /v1/models' ?kind=video) and of Automatic's choice. A
	// request that names one still makes its video.
	HiddenVideomakers []string `json:"hiddenVideomakers,omitempty"`
	// Off switches the provider off without removing it: its keys and
	// settings stay, but agents aren't given its models, no request,
	// routing group or fallback goes to it, and its balance isn't asked,
	// until it is switched on again (#163) — for a key out of quota.
	Off bool `json:"off,omitempty"`
	// Contexts is how long a request the user says a model takes, in
	// tokens, over what the vendor or models.dev says: by model id, "*"
	// for all the provider's models. Agents are told it.
	Contexts map[string]int `json:"contexts,omitempty"`
	// Family is a tag the provider's models go by in which agents are
	// shown them (settings' Visible), with the provider's id.
	Family string `json:"family,omitempty"`

	Catalog string `json:"catalog,omitempty"` // models.dev id, for names and reasoning levels
	Website string `json:"website,omitempty"`
	KeysURL string `json:"keysUrl,omitempty"`

	// IconURL is a picture the vendor named in an import link, to be fetched
	// once the user confirms. It is only a carrier between parsing and that
	// fetch: Save drops it, so it never reaches providers.json.
	IconURL string `json:"iconUrl,omitempty"`

	// Hidden is set on an account the user removed from magpie; the
	// agent stays signed in, magpie just leaves it alone.
	Hidden bool `json:"hidden,omitempty"`
	// Quiet is set on a removed account whose "Add it back" line the user
	// dismissed: it is offered again only from the Add sheet (#116).
	Quiet bool `json:"quiet,omitempty"`
	// Tucked is set on a quiet one the user hid from the Add sheet too:
	// it is listed there only behind "Show N hidden", or when searched
	// for by name (#116).
	Tucked bool `json:"tucked,omitempty"`
	// Forgot is set on a removed account the user signed out of magpie
	// while its agent stays signed in, which magpie never signs out
	// (Claude Code): it is no longer listed among the removed, and stays
	// hidden until it is added back by a new sign-in (ikunbots on X).
	Forgot bool `json:"forgot,omitempty"`

	// Account is set when the provider is an agent the user signed in to
	// (see account.go); it is derived, never stored.
	Account *Account `json:"-"`
	// contains filtered or unexported fields
}

Provider is one configured vendor.

func Accounts

func Accounts() []Provider

Accounts lists the signed-in agents as providers.

func All

func All() []Provider

All lists the configured providers in the order they were added, then the signed-in agents. An entry in the file with no URL is only the model picks for one of those accounts. A request that holds the catalog (Hold) builds it once: each build reads every agent's sign-in, a keychain item or a CLI's among them, and Codex's /models asked for it seven times over, past the 5 s Codex waits for the list (#746).

func Find

func Find(id string) (*Provider, error)

Find looks a provider up by id (or name, case-insensitively).

func FromPreset

func FromPreset(id string) (Provider, error)

FromPreset builds a provider from a preset; the caller adds the key. An id the preset carried before builds it at the region that id was.

func Hidden added in v0.1.9

func Hidden() []Provider

Hidden lists the signed-in accounts the user removed from magpie. The file is read once, as parsed until it changes: a parse of it for each account was 68 MB of the Providers page's 1.4 GB in twenty loads.

func KeepSecrets added in v0.1.1214

func KeepSecrets(in, here Provider, keyless bool) Provider

KeepSecrets is in, as sync or a restore brings it over here, with the secrets that didn't come along kept from here (#1821). keyless is that in came from a copy without keys: its keys and its secret headers are here's then. An AccessKey ID and Secret, or a balance token, that in hasn't at all are kept when it came without keys or with the key here has, the same account: a magpie from before access keys were synced (v0.1.1142), or one the key was never given on, sends a provider with its key and nothing else, and taking that whole wiped the Volcengine and Tencent plan cards' access keys on this computer. A key of its own is another account's, whose access key this one's isn't.

func MoveToKeyPlace

func MoveToKeyPlace(ctx context.Context, p Provider, listErr error) (Provider, string)

MoveToKeyPlace moves a provider whose model list refused its key (a 401, listErr from its Fetch) to the other place of its preset whose list takes the key, and saves it there: a Sidrune AI key of China's typed into a provider at Global (Axo, 11-20). It says the name of the region moved to, or "" when none takes the key, and the provider as saved.

func ParseImport added in v0.1.8

func ParseImport(link string) (Provider, error)

ParseImport reads an import link into the provider it describes.

func PluginAtForTest

func PluginAtForTest(id, pluginID, api string) Provider

PluginAtForTest is PluginForTest for a plugin whose provider says its requests go to api and whose models speak Code Assist.

func PluginForTest added in v0.1.2547

func PluginForTest(id, pluginID string) Provider

PluginForTest is the provider id served by the plugin's provider pluginID, for a test to build a candidate of.

func Readdressed

func Readdressed(p Provider) (Provider, bool)

Readdressed is p, a Remote magpie, at the address it is saved at now, when that is another than p's: the user typed the new one in, or a look (seekMoved) found it there, while a request held p as it read it (le13ure on X: a request asked the old address again and again, through its retries and its patience, after the new one was saved). Only the addresses are taken; a key's view of p stays as it was.

func Resolve

func Resolve(id string) (Provider, string, bool)

Resolve maps an id an agent sent to a provider and the vendor's model id. It accepts catalog ids, "provider/model" for any model (exposed or not), and a bare model id: the first provider in the Providers order (All) that exposes it, else the one provider that lists it unexposed. The gateway asks GroupFor first, so with found groups on a bare id several providers serve is that group, its members in the same order (MOMO on Discord: glm-5.3 under opencode-go and a6api). magpie writes only provider/model ids into agents' configs, so a bare one is the user's. A group's id resolves to its first member.

func ResolveRoute added in v0.1.1869

func ResolveRoute(id string) (Provider, string, bool)

ResolveRoute is Resolve for a model a route names, a routing group's member or a provider's fallback, as routing reaches it: not one the user unchecked (unpicked). A request naming the model itself goes by Resolve, which still takes it.

func RouteDecider added in v0.1.411

func RouteDecider(model string) (Provider, string, error)

RouteDecider is the decision provider a System One model names, and the model that provider is asked with. The name's prefix is the provider (gptload-jev/jev-latest, vercel-jev/typesafe-ai/jev). A bare Jev id goes to the only provider that can answer it, as that provider names Jev.

func SearchSignIn added in v0.1.2949

func SearchSignIn(v SearchVendor) (name string, p *Provider)

SearchSignIn is what a search API that signs in searches as: the name of the provider it signs in to, and that provider as All lists it (its first account; AlsoOn the others on), nil while it isn't signed in or another plugin serves the id (the user picked another plugin for it).

func SeekMoved added in v0.1.3150

func SeekMoved(ctx context.Context, p Provider, err error) (Provider, bool)

SeekMoved is p, a Remote magpie a request found no one at (err), at the address it was found at on this computer's network, saved there: the request is made again at it. Requests failing at once wait for one look, and one is made at most every seekEvery.

func Stored added in v0.1.28

func Stored() ([]Provider, error)

Stored is the providers as providers.json keeps them: keys included, signed-in accounts only as the model picks the user made for them. A file that can't be read is an error, never none: a backup or a sync carrying none would take every provider away where it is put back.

func SwitchedOff added in v0.1.346

func SwitchedOff(id string) (Provider, bool)

SwitchedOff is the provider switched off in magpie that a model id names: as "provider/model", or a model only switched-off providers list. A request for it is refused as that, not as a model magpie doesn't know.

func SyncedOnly

func SyncedOnly(ps []Provider, order []string) ([]Provider, []string)

SyncedOnly is the providers and their order without those kept on this computer (ThisDevice): what sync sends out.

func ZhipuSearchKeys added in v0.1.3014

func ZhipuSearchKeys(p Provider) []Provider

ZhipuSearchKeys are p with each of its keys in use that is on a GLM Coding Plan (ZhipuCodingSearch of p with that key), in the order requests try them; none for a provider with no plan's key.

func (Provider) AIStudioPair added in v0.1.2743

func (p Provider) AIStudioPair() bool

AIStudioPair is a provider at both of AI Studio's APIs: its models are the OpenAI-compatible list's, which is the Gemini API's list again.

func (Provider) APIs added in v0.1.40

func (p Provider) APIs(model string) []Protocol

APIs lists the APIs model is served on, as the provider's last model list said: Copilot serves its GPT models on Responses alone and its Claude models on Chat and Anthropic's. nil is not known, and every API the provider speaks may be tried. One the user set for the model (SetModelAPI) is the only one.

func (Provider) AccountCap added in v0.1.809

func (p Provider) AccountCap(user string) int

AccountCap is the share (1–99) of its windows the account user of p is used to at most, 0 when it has no cap. An account not had from All or AlsoOn (made afresh by its sign-in) carries none of the provider's settings: they are read from providers.json then.

func (Provider) AccountConcurrencyOf added in v0.1.1009

func (p Provider) AccountConcurrencyOf(ref string) (int, bool)

AccountConcurrencyOf is the account's or key's own limit, and whether it has one (else it takes the provider's).

func (Provider) AccountID added in v0.1.1076

func (p Provider) AccountID() string

AccountID is the stable id of p's account or key as a gateway key's account list knows it (#905): the account's, kept through renames, or a key's fingerprint.

func (Provider) AccountIDs added in v0.1.1076

func (p Provider) AccountIDs() []AccountRef

AccountIDs are the provider's accounts and keys as a gateway key's account list knows them (#905): an account by its stable id, a key by its fingerprint, with the name and plan each is shown by.

func (Provider) AccountName added in v0.1.1172

func (p Provider) AccountName(user string) string

AccountName is the name the user gave the account user of p, "" when none. As with AccountCap, an account made afresh beside the agent's own reads it from providers.json.

func (Provider) AccountRefOf added in v0.1.1009

func (p Provider) AccountRefOf(ref string) (string, bool)

AccountRefOf is the account or key of p that ref names, as its limit is kept: an account's name, a key's KeyID (by its id or name).

func (Provider) AccountRefs added in v0.1.610

func (p Provider) AccountRefs() []string

AccountRefs are the provider's accounts, or keys, as AccountModels knows them: a signed-in account's name, a key's KeyID.

func (Provider) AccountServes added in v0.1.610

func (p Provider) AccountServes(ref, model string) bool

AccountServes says whether the account or key ref (a signed-in account's name, a key's KeyID) is let serve model: true when it has no list of its own, and for a model Codex calls by itself that no list can hold (codexOwnHidden).

A model the user lists by an id of theirs (SetModelID) is in the list by that id, or by the vendor's own one a list kept from before has.

func (Provider) AccountShown added in v0.1.1326

func (p Provider) AccountShown(user string) string

AccountShown is how the account user of p is shown: by the name the user gave it, else by the name its plugin's usage gives it (PluginUserOf), else as its vendor names it. Records and lists keep the vendor's name, the key the user's name is kept by, and look this up as they are shown, so a rename reaches what came before it too (magpie-community/plugins#310: a renamed Kiro account read by its old name on the requests after).

func (Provider) AccountWeight added in v0.1.2316

func (p Provider) AccountWeight(user string) int

AccountWeight is the weight of the account user of p under Weighted routing, 1 when it has none. The accounts All and AlsoOn give carry it, as the gateway routes them; it is read from p alone, with no file read, as it is asked for every account of every request weighed.

func (Provider) AccountsFor added in v0.1.3223

func (p Provider) AccountsFor(model string, held func(AccountOn) bool) (out, left, barred []AccountOn)

AccountsFor are p's accounts on (AccountsOn) as routing takes them for model: out, those it goes over; left, those whose own list (their plan) leaves the model out, tried only after them; barred, those the user set not to serve it (AccountModels, #474), then those held reports held back (the gateway's usage caps; nil holds none). An account whose list lacks the model would only answer 400, so it is in out only when no account lists it (by the vendor's own id: an account's list names its models by theirs, not by one the user lists one by). A list older than the model, as magpie knows it (Account.listLags), is unknown, not a plan without it: that account is in out.

func (Provider) AccountsOn added in v0.1.3223

func (p Provider) AccountsOn() []AccountOn

AccountsOn are the accounts of p (signed in: p.Account) a request may take, in the user's order: the one signed in to, unless the user paused it for the others on (#263), then the others on; kept signed in to an account of the user's choosing, the one signed in to stands at its own place in the order, not first (#524).

func (Provider) AddedByAddress added in v0.1.1191

func (p Provider) AddedByAddress() bool

AddedByAddress reports whether the user added the provider by its address: no preset, no account, no plugin. The tier an agent asks for goes to it as it was asked (the gateway's OwnTier).

func (Provider) AlsoOn added in v0.1.14

func (p Provider) AlsoOn() []Provider

AlsoOn is a signed-in agent's other accounts that are on, each as a provider of its own, in the order they were saved. Each keeps what the user set on the provider, as p has it from All: its queue, limits, routing and models (withPicks). A Claude or Codex account is p with another sign-in, and had them always; one a sign-in of its own makes afresh had none, and a second WorkBuddy AI account queued 62s with the wait set to 1s (#1899).

func (Provider) AnonymousKey added in v0.1.1214

func (p Provider) AnonymousKey() string

AnonymousKey is the key the provider is asked with when the user has none of their own, "" when it has no such key: OpenCode Zen's public, which its free models answer (normalize gives it to a Zen provider saved with no key).

func (Provider) AskSystemOne added in v0.1.723

func (p Provider) AskSystemOne(ctx context.Context, model string) error

AskSystemOne sends model the smallest System One question at p's decision API, and says why it wasn't answered.

func (Provider) AsksDecideModels added in v0.1.838

func (p Provider) AsksDecideModels() bool

AsksDecideModels reports whether each of p's decision models can be sent a System One question of its own (TestModels): where the API is System One's, TypeSafe's or a gateway's that serves it as it is (Vercel's TypeSafe API, OpenRouter's), or Workers AI's, which DecideAsk wraps it for (ARNO on Discord: cloudflare-jev's models couldn't be tested from their right-click); not Vercel's evaluation models, which name the model in headers of their own. Google's Decisions API, which DecideAsk asks as it takes it, can be too.

func (Provider) AsksThread added in v0.1.2058

func (p Provider) AsksThread(ctx context.Context) bool

AsksThread says p's headers or extraBody name ${threadId}, which the gateway reads out of the request only then. A header the user gave the model ctx says is asked counts (headersFor).

func (*Provider) AtAddress added in v0.1.1224

func (p *Provider) AtAddress(addr string) error

AtAddress moves the provider's URLs to addr as the package's AtAddress does; a refused address leaves them as they were.

func (Provider) AtOnce added in v0.1.2502

func (p Provider) AtOnce() int

AtOnce is how many of the provider's accounts or keys take requests at the same time, 0 for no limit: the user's MaxAccounts when they set one, else what the plugin giving the provider says (its auth hook's maxAccounts, or its package.json's magpie.maxAccounts), else none. An account not had from All or AlsoOn carries none of the provider's settings: they are read from providers.json then.

func (Provider) AutoNext added in v0.1.914

func (p Provider) AutoNext(ctx context.Context) string

AutoNext is the model Copilot's Auto picks now for a request ctx resolved for it (ResolveAuto), "" for any other: once Retry has said a refused pick is worth sending again, the one it goes as.

func (Provider) Available

func (p Provider) Available() []catalog.Model

Available lists every model the vendor is known to serve: the list fetched from the vendor itself when there is one, over the models.dev catalog (or, for an account, whatever the agent's own sign-in can see).

func (Provider) Base

func (p Provider) Base(proto Protocol) string

Base returns the base URL for a protocol, or "" when the vendor lacks it.

func (Provider) BillingKind

func (p Provider) BillingKind() string

BillingKind is how p bills: the user's word, else what magpie reads of it (BillingPlan, BillingPAYG, BillingMixed), "" when it can't say.

func (Provider) BothAuth added in v0.1.1211

func (p Provider) BothAuth() bool

BothAuth says p's Anthropic requests carry its key in both x-api-key and Authorization, as they do by default to a third-party Anthropic API: the ones AuthHeader can narrow to one. Anthropic's, Bedrock's, Azure's and Vertex AI's never do, nor a signed-in account's.

func (Provider) CapsOf added in v0.1.1134

func (p Provider) CapsOf(user string) WindowCaps

CapsOf is the caps of the account user of p: its usage cap and its windows' own. As with AccountCap, an account made afresh beside the agent's own reads them from providers.json.

func (Provider) CarriesCompaction added in v0.1.1243

func (p Provider) CarriesCompaction() bool

CarriesCompaction says whether p's wire can carry Codex's own compaction (NativeCompaction, #1099): a compaction_trigger asked and a sealed compaction item given back, on the Responses API, as Codex sent them. A provider of no sign-in with a Responses API does (Sub2API and other relays of OpenAI's, OpenAI's own, a remote magpie), as do a ChatGPT account and GitHub Copilot, whose GPT models answer on Responses. Another signed-in agent's, or a plugin's, is asked in its own client's format, which has no such item.

func (Provider) Catalogs added in v0.1.13

func (p Provider) Catalogs() []string

Catalogs are the models.dev ids the provider's models are looked up in, first match wins: a gateway that resells several vendors names them all ("openai, deepseek").

func (Provider) Chosen

func (p Provider) Chosen(id string) bool

Chosen reports whether a model is exposed.

func (Provider) ClinePassAsked added in v0.1.1389

func (p Provider) ClinePassAsked(model string) string

ClinePassAsked is the upstream a request for model asked the Cline API to serve it from on p, "" when it asked for none: what magpie wrote into it (ClinePin). The Routing page says it beside a reply that names no provider, so a route ClinePass picked reads as asked for an upstream or not (zRain on Discord, 10-24). The Cline plugin's own pinUpstream option is not counted: 0.1.13 pins nothing without it, and a pin it writes (0.1.12 by default, or the option on) is providerOptions, which Cline refuses with a 403, so no reply is ever served on it.

func (Provider) ClinePin added in v0.1.934

func (p Provider) ClinePin(model string) (upstream string, openRouter bool)

ClinePin is the upstream a request for model is pinned to on p (PinUpstream), and whether Cline sends the model through OpenRouter: "z-ai" through OpenRouter for glm-5.3-flash, "" for anything else. Since 2026-11-06 the Cline API answers a request carrying providerOptions with 403 "client-supplied \"providerOptions\" model routing is not supported" (#5442: the same request, the same key, 403 with the field and 200 without), so a model Cline sends through Vercel's AI Gateway (DeepSeek's, GLM's but glm-5.3-flash), which only providerOptions.gateway.only could pin, goes unpinned whatever the tick says: the tick would fail every such request. OpenRouter's top-level provider.only is still taken, so glm-5.3-flash keeps it. Cline's free models are served where Cline puts them, so they never are.

func (Provider) ClinePinnable added in v0.1.959

func (p Provider) ClinePinnable() bool

ClinePinnable reports whether p's requests reach Cline's API and can be pinned to an upstream (PinUpstream): the ClinePass provider, one on cline.bot, or the Cline plugin's (@magpie-community/opencode-cline-auth), whose requests magpie writes before the plugin sends them on.

func (Provider) CompactsOn added in v0.1.1243

func (p Provider) CompactsOn(model string) bool

CompactsOn says whether a Codex compaction for model at p goes to it as Codex sent it: the user turned NativeCompaction on, its wire carries it, and model is asked on Responses there (Copilot's Claude models are not). The gateway also asks whether the model fits Responses as it has seen it answer (Server.compactsNatively).

func (Provider) Concurrency added in v0.1.633

func (p Provider) Concurrency() int

Concurrency is how many requests the gateway lets be out at the vendor at once on each of the provider's keys or accounts, 0 for no limit: the user's MaxConcurrency when they set one, else what the plugin giving the provider says it takes (its auth hook's maxConcurrency, or its package.json's magpie.maxConcurrency), else none.

func (Provider) ContextOf added in v0.1.107

func (p Provider) ContextOf(model string) int

ContextOf is the context the user set for the provider's model: its own, else the provider's "*"; 0 when none is set.

func (Provider) DecideAPIKind added in v0.1.3300

func (p Provider) DecideAPIKind() bool

DecideAPIKind reports whether p is a provider whose models could be set to be asked on System One once it has a URL for it there.

func (Provider) DecideHeaders added in v0.1.2551

func (p Provider) DecideHeaders(h http.Header)

DecideHeaders sets on h what p's decision API needs besides its key: Ark's beta switch (ArkSystemOneHeader) on Ark's host.

func (Provider) DecideModelURL added in v0.1.859

func (p Provider) DecideModelURL(ctx context.Context, model string) (string, error)

DecideModelURL is where a question for model is posted: DecideURL, or, for a Clef on Workers AI, its own run under it.

func (Provider) DecideOnly added in v0.1.686

func (p Provider) DecideOnly() bool

DecideOnly reports whether the provider has no conversation endpoint.

func (Provider) DecideProtocol

func (p Provider) DecideProtocol() Protocol

DecideProtocol is the protocol p's decision API is signed as: Google's as its Gemini API (x-goog-api-key, where a key as a Bearer token is turned away, "Expected OAuth 2 access token"), every other as chat completions.

func (Provider) DecideURL added in v0.1.218

func (p Provider) DecideURL(ctx context.Context) (string, error)

DecideURL is where a question for p's decision API is posted. Workers AI's is under an account: the one its base names, else the one the token belongs to, looked up once.

func (Provider) DecideVia added in v0.1.218

func (p Provider) DecideVia() string

DecideVia is the way p's decision API is asked, known by its host or by the gateway's own path (Vercel's /typesafe or /v4/ai, Cloudflare's /client/v4).

func (Provider) Decides added in v0.1.142

func (p Provider) Decides() bool

Decides reports whether the provider is a decision API.

func (Provider) DecidesModel added in v0.1.686

func (p Provider) DecidesModel(model string) bool

DecidesModel distinguishes Jev from the conversation models a gateway also serves. A dedicated decision API may use any model name, and a plugin's are the ones it marks besides Jev's (#1514).

func (Provider) DecisionModels added in v0.1.928

func (p Provider) DecisionModels() []catalog.Model

DecisionModels are the decision models listed separately from a provider's conversations: OpenRouter's own list, a Bailian Token Plan's decision model, or a remote magpie's or a plugin's marked models.

func (Provider) Detect added in v0.1.663

func (p Provider) Detect(ctx context.Context, base, model string, picked ...string) ([]Detection, error)

Detect asks each of Chat, Responses, Anthropic and Gemini at the URL p has for it, else at base as it takes it (DetectBase), the smallest request, and says what each answered, in that order. model is asked on all three; with none, one is picked for each — a Claude model on Anthropic's, an OpenAI one on Responses — from picked, the models the editor's form has and hasn't saved yet (#1545: a relay with no model list is asked for the models typed in the form, not only after a Save), else from p's list, and with no list the vendor is asked for one first (a GET of its models, which costs nothing). Only those URLs are asked, and only a key's provider: a sign-in's API is its agent's.

func (Provider) DetectDecide added in v0.1.723

func (p Provider) DetectDecide(ctx context.Context, model string) Detection

DetectDecide asks the System One API at p's decision URL (…/systemone pasted whole is cut to its root) the smallest question for model, or the one p is asked with when none is given, and says how it answered.

func (Provider) DetectModels added in v0.1.671

func (p Provider) DetectModels(ctx context.Context, base string, models []string) ([]ModelDetection, []Detection, error)

DetectModels asks each of models (the first DetectMax, an image model left out: it is asked on the images API) on each of Chat, Responses, Anthropic and Gemini at the URL p has for it, else at base as it takes it, and says what each answered, model by model; and, by API, the first answer from a model it served, else the first model's — what Detect says for one. A probe not started before ctx ends says so, unasked.

func (Provider) Do added in v0.1.479

func (p Provider) Do(client *http.Client, req *http.Request) (*http.Response, error)

Do sends req, through the account's own transport when it has one (a plugin's), the client the account asks for this request when it asks for one (ZCode's Start Plan: zcodeStartClient), and client otherwise, following a redirect only to the request's own origin (Keyed).

A request sent for magpie's own test (probelog.With) is written into the request log here, whichever way it goes: a plugin's fetch and a client of the account's own pass no transport that would.

func (Provider) DrawerHidden added in v0.1.2016

func (p Provider) DrawerHidden(model string) bool

DrawerHidden is whether the user unticked p's image model in its editor (HiddenDrawers): it is left out of the lists an image model is picked from and of Automatic's choice, and still draws when named.

func (Provider) Efforts added in v0.1.59

func (p Provider) Efforts(model string) []string

Efforts are the reasoning levels the model takes, when known: its own, or those the user gave it when it has none known (magpie model spec --reasoning on a custom provider's model). The gateway fits a request to these. Levels the user kept of a model's own only narrow what is offered (#92): the vendor is still asked at any level it has.

func (Provider) EndpointCatalog added in v0.1.1231

func (p Provider) EndpointCatalog() string

EndpointCatalog is the models.dev catalog a provider the user added by its endpoint alone is priced from: the one models.dev says serves its models at that address, when exactly one does (#2052, mengyianx: a provider at AMD's own https://developer.amd.com.cn/radeon/api/v1 had no price for Qwen3.8-27B, which models.dev's amd lists at $0 there, while its maker sells no such model). Only a key's provider with no catalog named counts: a catalog the user or a preset gave stands, and a subscription's account is priced as its own code says. A plan's catalog is never one: it lists what its membership charges per token, $0, not what the model costs (membershipCatalogs).

func (Provider) Explain added in v0.1.447

func (p Provider) Explain(msg string, status int, body []byte) string

Explain is the error a refusal is passed on as: msg, with what the user can do about it when the account knows.

func (Provider) Exposed

func (p Provider) Exposed() []catalog.Model

Exposed lists the models magpie offers to agents for this provider: the user's picks; else the preset's; else everything, when that is few, the newest of each family only under Best in family; none after Select none (ServesNone).

func (Provider) ExposedOf added in v0.1.2447

func (p Provider) ExposedOf(avail []catalog.Model) []catalog.Model

ExposedOf is Exposed of avail, p.Available() as the caller has already read it: an editor's look at a provider read the vendor's list four times over, each built afresh with its names and levels.

func (Provider) ExtraTier

func (p Provider) ExtraTier() (tier string, forced bool)

ExtraTier is the service_tier the provider's extra body asks for, and whether it is forced ("!service_tier"); "" when it names none, or not as a string. A group's member, or an agent's pick, sent fast on the provider is sent at it when it is Ultrafast: fast is never sent slower than the user asked of the provider (the gateway's member tries).

func (Provider) FactoryGemini added in v0.1.1125

func (p Provider) FactoryGemini() bool

FactoryGemini is Factory's sign-in, whose Gemini models are asked on its own generate route (…/generate, the model in the body), not at models/{model}:streamGenerateContent as Google's Gemini API asks them.

func (Provider) Fetch

func (p Provider) Fetch(ctx context.Context) ([]catalog.Model, error)

Fetch asks the vendor which models it serves and remembers the answer.

func (Provider) Fetched

func (p Provider) Fetched() (time.Time, bool)

Fetched reports when the vendor's own list was last fetched.

func (Provider) FreeModel added in v0.1.1297

func (p Provider) FreeModel(model string) bool

FreeModel says model costs nothing on p: its vendor serves it at no cost to the subscription's allowance or credits (catalog.Model's Free: WorkBuddy's "x0.00", Qoder's is_free, Cline's free models, an OpenCode Zen free one), or, with no such word from the vendor, it is listed at $0 on every count — a vendor's free model a catalog prices at 0, as mimo-v2.6-flash-free is, and a key's free model, which has no allowance to draw on and so is judged by its price alone.

A model neither listed free nor priced is not free: nothing says it costs nothing, and the routes that go by this put it with the paid ones, so a pool without free models behaves as In order. The user's word is something: every model of a provider they count free is (CountFree).

func (Provider) HasKey added in v0.1.1214

func (p Provider) HasKey(key string) bool

HasKey reports whether key is one of the provider's, on or off.

func (Provider) HasKeyID added in v0.1.2674

func (p Provider) HasKeyID(id string) bool

HasKeyID reports whether the key of fingerprint id is one of the provider's, on or off.

func (Provider) Host

func (p Provider) Host() string

Host is the vendor's API host, for display.

func (Provider) ImageCapOf

func (p Provider) ImageCapOf(model string) int

ImageCapOf is the most images one request to model may carry, as the user set it on p: the model's own, else the one for all its models, 0 for none.

func (Provider) ImageFilesAt added in v0.1.3079

func (p Provider) ImageFilesAt(to Protocol) bool

ImageFilesAt says whether p's requests on to reach DeepSeek's own API with a key of the user's, where an agent's inline images can go up once through DeepSeek's Files API and be named by file id (gateway's deepseek_files.go, #5407). ImageFilesOff turns that off; this says only where it can apply.

func (Provider) IsAzure added in v0.1.419

func (p Provider) IsAzure() bool

IsAzure reports whether the provider is Azure OpenAI: made from its preset, or at a resource's host.

func (Provider) IsBedrock added in v0.1.364

func (p Provider) IsBedrock() bool

IsBedrock reports whether the provider is Amazon Bedrock: its runtime (bedrock-runtime.{region}.amazonaws.com) or its Mantle endpoint (bedrock-mantle.{region}.api.aws), made from either's preset or at either's host. The two take the same Bedrock API key and share what Bedrock asks of a request: x-api-key alone on Messages, its own names for Anthropic's betas, no metadata.user_id, max_completion_tokens on chat completions, Claude on Messages and OpenAI's GPT models on Responses first. What only the runtime does (no list of models) is the preset's; what only Mantle does is IsBedrockMantle's.

func (Provider) IsBedrockMantle added in v0.1.1270

func (p Provider) IsBedrockMantle() bool

IsBedrockMantle reports whether the provider is Amazon Bedrock's Mantle endpoint (@marktoown on X): made from its preset, or added by its address at bedrock-mantle.{region}.api.aws.

func (Provider) IsCline added in v0.1.630

func (p Provider) IsCline() bool

IsCline reports whether the provider is the Cline API: made from the ClinePass preset, or at Cline's host.

func (Provider) IsKilo added in v0.1.635

func (p Provider) IsKilo() bool

IsKilo reports whether the provider is the Kilo Gateway: made from its preset, or at Kilo's API host.

func (Provider) IsOpenCode added in v0.1.7

func (p Provider) IsOpenCode() bool

IsOpenCode reports whether the provider is OpenCode's gateway (Zen or Go), which routes and caches by conversation and turns away requests that do not name one in x-opencode-session.

func (Provider) IsPlugin added in v0.1.479

func (p Provider) IsPlugin() bool

IsPlugin is whether the provider is a plugin's.

func (Provider) IsRemoteMagpie added in v0.1.527

func (p Provider) IsRemoteMagpie() bool

IsRemoteMagpie reports whether the provider is another magpie.

func (Provider) IsVertex added in v0.1.1162

func (p Provider) IsVertex() bool

IsVertex reports whether the provider is Google Vertex AI.

func (Provider) Jev added in v0.1.218

func (p Provider) Jev() string

Jev is the model a decision provider is asked with when the user picked none: TypeSafe's latest stable one, or the one Jev a gateway serves.

func (Provider) KeptToAgent added in v0.1.1954

func (p Provider) KeptToAgent() bool

KeptToAgent is whether the provider is Claude's subscription with SwitchOnly on: its accounts are Claude Code's own sign-in alone, which magpie moves to the next account with room and back, and the gateway sends no request to them, so none goes through Claude Code's SDK run, which spends more of the allowance than Claude Code's own sessions (myduso on Discord). Codex's SwitchOnly only keeps failover out of its config.

func (Provider) KeyAccountOf

func (p Provider) KeyAccountOf(ref string) (KeyAccount, bool)

KeyAccountOf is the key of p with the id ref (KeyInfo.ID), and whether p has it.

func (Provider) KeyCapHeld

func (p Provider) KeyCapHeld(k KeyAccount, model string, now time.Time, read func(Provider) (Allowance, bool)) *CapHold

KeyCapHeld is how the key k of p is held at the usage cap set on it for model at now, by the windows read gives of it (KeyAllowance, or a test's): nil when it has no cap, its windows aren't known (not read yet, or the read failed: unknown is not spent) or each is below its share.

func (Provider) KeyGroupRate

func (p Provider) KeyGroupRate(keyID string) (float64, bool)

KeyGroupRate is the group rate read from the relay for the key keyID, and whether one is known, for a page to show; any provider's.

func (Provider) KeyList added in v0.1.14

func (p Provider) KeyList() []KeyInfo

KeyList is a provider's keys, in the order requests try them.

func (Provider) KeyOwnBalance added in v0.1.3281

func (p Provider) KeyOwnBalance(keyID string) (OwnBalance, bool)

KeyOwnBalance is the balance typed for p's key keyID, and whether it has one.

func (Provider) KeyPriceRate

func (p Provider) KeyPriceRate(keyID string) (rate float64, own bool)

KeyPriceRate is the price rate the key keyID bills at: its own when the user gave it one; else, on a provider with a top-up rate, its group's rate read from the relay times that (key_rate_read.go) once one is read; else the provider's (0: the price as listed). own says the user gave the key its rate.

func (Provider) KeySpendCap added in v0.1.2819

func (p Provider) KeySpendCap(keyID string) (SpendCap, bool)

KeySpendCap is the spend cap of p's key keyID, and whether it has one.

func (Provider) KeysFor added in v0.1.3223

func (p Provider) KeysFor(model string, held func(KeyOn) bool) (out, unlisted, barred []KeyOn, noURL Protocol)

KeysFor are p's keys on as routing takes them for model: out, those it goes over; unlisted, those the vendor lists the model to no key of (tried after out, or as out when no key lists it); barred, those the user set not to serve it (AccountModels, #474) and those held reports held back (the gateway's spend caps; nil holds none). A key on a plan of its own whose models leave this one out (KeyAccount.Plan) is never asked while another can be: only when no key's plan has it, a model the vendor added since, are they out. A key made for a protocol p has no endpoint for is in none of them; noURL is the first such key's.

func (Provider) KeysOn added in v0.1.14

func (p Provider) KeysOn() []KeyAccount

KeysOn is the keys in use, first to last: the first key, then every saved one that's on. A key listed twice — providers.json's "keys" naming the first key again, as #1772's did — is one key, asked once.

func (Provider) KindModels added in v0.1.1225

func (p Provider) KindModels(kind string) []string

KindModels are the ids of p's models the user said make kind, those it still serves, sorted (a provider's id has no "/", so a model's may: OpenRouter's).

func (Provider) Known added in v0.1.161

func (p Provider) Known(model string) []string

Known are the model's own reasoning levels, when known.

func (Provider) KnownBorrowed

func (p Provider) KnownBorrowed(model string) bool

KnownBorrowed reports whether the model's levels (Known) are not its provider's word but borrowed for its id (borrowedEfforts): its list names none for it — a relay's /v1/models with reasoning_levels: [] or no levels at all — and models.dev has none for that vendor, so it is asked at the levels its maker, or the others serving it, give it (@czhhcz on X: `magpie model efforts` listed five for a relay's Claude model whose list said none, and didn't say where they came from).

func (Provider) LaneLimit added in v0.1.1009

func (p Provider) LaneLimit() int

LaneLimit is how many requests may be out at once on p's key or account, 0 for no limit: its own (AccountConcurrency), else the provider's (Concurrency). An account not had from All or AlsoOn (made afresh by its sign-in) carries none of the provider's settings: they are read from providers.json then.

func (Provider) Levelless added in v0.1.404

func (p Provider) Levelless(model string) bool

Levelless reports whether the model is known to have no reasoning levels to pick from, as against not known to have any: its vendor or its maker lists it with a thinking switch alone, or nothing (Xiaomi's mimo-v2.6-flash), and the user gave it none.

func (Provider) List added in v0.1.673

func (p Provider) List(ctx context.Context) ([]catalog.Model, error)

List asks the vendor which models it serves, as Fetch does, and keeps nothing: a provider still being added (#578, the add form's Fetch models) is shown its vendor's list to pick from before it is saved.

func (Provider) ListAll added in v0.1.3073

func (p Provider) ListAll(ctx context.Context) ([]catalog.Model, error)

ListAll is List with the models served on an API of their own kept: embedding and rerank models, tagged Serves.

func (Provider) ListAsks added in v0.1.1961

func (p Provider) ListAsks() bool

ListAsks says List asks a vendor over the network, with p's own key, what p serves: a key's provider, not a subscription's account, a plugin's or a decision API, nor a preset with no list to ask, whose List answers the preset's models without asking anyone. The gateway asks it of a key resting after an outage, to tell whether it is back (gateway/rest_probe.go).

func (Provider) ListError added in v0.1.1001

func (p Provider) ListError() string

ListError is why a plugin's account lists only the plugin's defaults, "" for any other provider.

func (Provider) ListPrice added in v0.1.411

func (p Provider) ListPrice(model string) (catalog.Price, bool)

ListPrice is a model's list price as its vendor's models.dev entry gives it, else as its maker's does (#224): a subscription (Codex's ChatGPT account, Copilot) or a relay with no models.dev id of its own is priced at gpt-6-astra's or gemini-3.8-flash's maker's price, as a Claude account is at Anthropic's. A remote magpie's is what that magpie counts the model at, as its list says (remotePrice). A model no catalog prices is at its vendor's own list price where a moved built-in's plugin serves it (vendorListPrice), else at the price its plugin lists it at (pluginListPrice), else, when the plugin says the plan serves it free, costs nothing (pluginFree). Codex's auto-review through the Codex subscription costs nothing too, as OpenAI serves it a ChatGPT sign-in (codexReviewFree).

func (Provider) Listed added in v0.1.552

func (p Provider) Listed() (time.Time, bool)

Listed is when the models listed now were had from the vendor: fetched for a built-in, listed by its plugin for a plugin's.

func (Provider) ListedAPIs added in v0.1.731

func (p Provider) ListedAPIs(model string) []Protocol

ListedAPIs are the APIs model is served on as its vendor says, whatever the user set: what APIs gives with nothing set (the editor's Auto).

func (Provider) ListedModelID added in v0.1.2345

func (p Provider) ListedModelID(own string) string

ListedModelID is the id p lists its model of its own id own by: the one the user gave it, else own.

func (Provider) Listing added in v0.1.2463

func (p Provider) Listing() Listing

Listing is p's Listing, built afresh.

func (Provider) ListsOff added in v0.1.3300

func (p Provider) ListsOff() bool

ListsOff is ListOff on a key's provider: a subscription's account and a plugin's provider list their models as their sign-in does.

func (Provider) LoginRanks added in v0.1.672

func (p Provider) LoginRanks() map[string]int

LoginRanks is, for the account Codex or Claude Code is signed in to while it is kept signed in to one of the user's choosing (KeepLoginAs), each of the agent's accounts' place in the order the gateway tries them, the one signed in to at its own place among them; nil otherwise, when the one signed in to is the first.

func (Provider) MarksKinds added in v0.1.1225

func (p Provider) MarksKinds() bool

MarksKinds is whether p's models can be said to make images or videos: a provider set up with a base URL, which magpie asks at the OpenAI-shaped images and videos APIs under it. A subscription's account, another magpie (whose own list says) and a decision API's can't.

func (Provider) MessagesFirst added in v0.1.1081

func (p Provider) MessagesFirst(model string) bool

MessagesFirst: a Claude model where the provider has Anthropic's Messages API, which is best asked there though its Chat or Responses API serves it too — a relay that serves both drops cache_control on Chat, so every turn was billed uncached (#997; ReturnTrue on Discord: 0% cache hits until the relay's OpenAI URL was left empty), and thinking with it.

func (Provider) ModelAPI added in v0.1.663

func (p Provider) ModelAPI(model string) (Protocol, bool)

ModelAPI is the API the user said p's model is asked on, when p has a URL for it still.

The Providers page asks it of each model of every provider's list, and most have no API set: that is looked up first, and the protocols p speaks are counted, not listed (a list made for each model was 12 MB of what forty polls allocated with real accounts).

func (Provider) ModelEfforts added in v0.1.137

func (p Provider) ModelEfforts() map[string][]string

ModelEfforts are the reasoning levels the user kept of the provider's models, by model id.

func (Provider) ModelIDs added in v0.1.2345

func (p Provider) ModelIDs() map[string]string

ModelIDs are the ids the user lists p's models by, from each one to the provider's own id of it.

func (Provider) ModelKind added in v0.1.1225

func (p Provider) ModelKind(model string) string

ModelKind is what the user said p's model makes: KindImage, KindVideo, or "" when they said nothing, or p can't be told (MarksKinds).

func (Provider) ModelNames added in v0.1.137

func (p Provider) ModelNames() map[string]string

ModelNames are the names the user gave the provider's models, by model id.

func (Provider) ModelTest added in v0.1.636

func (p Provider) ModelTest() string

ModelTest says why p's models can't each be sent a test request ("" when they can): "decide" for a decision API whose models can't each be sent a System One question (AsksDecideModels), whose endpoint Test asks it for them; "own-api" for a sign-in reached through its agent's own API (Cursor, Devin, Kiro, Zed, Qoder, a Google sign-in), which the gateway translates every request for, so a probe has no endpoint to go to. A Google sign-in's are asked through the gateway's translator (testsTranslated). Vertex AI's generateContent is asked as it is.

func (Provider) NamedOnlyOn added in v0.1.1237

func (p Provider) NamedOnlyOn(proto Protocol) bool

NamedOnlyOn is whether p serves on proto only the models its list names that API for, so that one it names none for isn't asked there: OpenCode's Gemini API, which serves the Gemini models alone (each of OpenCode's models is served on one API family, its inference docs say). The rest are asked on chat, Responses or Messages, as before it had a Gemini URL (#2168).

func (Provider) Native added in v0.1.300

func (p Provider) Native(model string) Protocol

Native is the API model is best asked on at this provider: one it serves the model on itself, so a request on it is relayed as it is rather than translated — Responses for a ChatGPT sign-in, or an OpenAI model on OpenAI's API or Copilot's; Anthropic's Messages for a Claude model where that is served; the API a custom provider's Base URL was given as (BaseAPI); Chat where that is served. "" when every request is translated anyway: a sign-in served through its agent's own API (Claude Code's binary, Devin, Code Assist).

func (Provider) NewestInFamily added in v0.1.2110

func (p Provider) NewestInFamily(avail []catalog.Model) []catalog.Model

NewestInFamily is the models Best in family would serve of avail, the vendor's list (Available), before the first 24 are taken: the newest of each family among those it can be asked for (catalog.BestInFamily), whichever mode is on, so the editor can draw them before it is saved.

func (Provider) NoAPI added in v0.1.2471

func (p Provider) NoAPI() func(model string) bool

NoAPI is NoAPIFor for each model of a list: the APIs the provider has a URL for are found once for the list, not once for each model (they were most of what NoAPIFor allocated, 16 MB of twenty window polls).

func (Provider) NoAPIFor added in v0.1.1234

func (p Provider) NoAPIFor(model string) bool

NoAPIFor says the provider has a URL for none of the APIs the vendor's list serves model on (or the one the user set for it): a relay's Claude listed on /messages alone, at a provider given only a chat URL. Agents aren't offered it, as no request for it could be answered (#2094). Only a provider of keys, whose URLs the user typed: a sign-in's APIs are magpie's own. A model whose list says no API, and a provider with no URL at all, are never left out here.

func (Provider) NoFailRest added in v0.1.1236

func (p Provider) NoFailRest() bool

NoFailRest says p's keys and accounts don't rest after an unknown failure (RestCapOff).

func (Provider) On added in v0.1.346

func (p Provider) On() bool

On is whether the provider takes requests: ready, not switched off, not kept to its agent's own sign-in (KeptToAgent) and not a Remote magpie that is this magpie (SelfLeftOut).

func (Provider) OnMessages added in v0.1.1083

func (p Provider) OnMessages(model string) bool

OnMessages: a Claude model MessagesFirst asks on Messages whatever API the client spoke, not only when the client's isn't served — unless the user set the API it is asked on, or the vendor's list names the APIs it serves it on (Copilot's Claude on Chat and Messages), where a request is relayed on the client's own API as before.

func (Provider) OpenAIBase added in v0.1.2076

func (p Provider) OpenAIBase() string

OpenAIBase is where p takes the OpenAI-shaped requests that are no chat (embeddings, rerank, speech, transcriptions): its Chat base, and a plugin's fetch under plugin://<id>/v1 whatever API its chat models are spoken on, for the plugin to answer or put in its vendor's shape (XYenon's Google AI Studio plugin: Gemini's embedContent, its TTS).

func (Provider) OpenCodeFree added in v0.1.616

func (p Provider) OpenCodeFree(model string) bool

OpenCodeFree says whether model is one of OpenCode Zen's free ones on p, which Zen serves only to what looks like OpenCode: besides the headers OpenCodeClient sets, a streamed request offering OpenCode's core tools (OpenCodeTools, OpenCodeToolSchemas) with OpenCode's environment block in its system prompt (OpenCodeEnvironment), at the paths OpenCode 2 asks (OpenCodeFreeURL), as checked against Zen in October 2026. The gateway asks them so whoever the client is (gateway/zenfree.go), and the Test button's probe so (zenFreeProbe). A free model is one whose id ends in -free, or one models.dev's opencode prices at nothing, as big-pickle, whose id doesn't say so (361 on Discord: it answered 403 "OpenCode's free tier can only be used from within OpenCode"); openCodeFreeIDs are such ones known without the catalog.

On OpenCode Go's gateway a model Go lists itself (models.dev's opencode-go: beam-free and cat-jam-free among them) is none of these. Go serves its models, the free ones too, to a Go key from any client its docs validate (Claude Code, Codex, Hermes, Pi, Raycast), so they are asked as the client asked them, with nothing of OpenCode's added. Asked as Zen's, Go's free models got the environment block's "Prefer /tmp/opencode over generic system temporary directories" in Claude Code's prompt and said it back (withtee on X). A Zen free model Go doesn't list stays one, for Zen's free tier asks it when Go refuses it (RetryOpenCodeFreeOnZen).

func (Provider) Origin added in v0.1.755

func (p Provider) Origin(ctx context.Context) string

Origin is the scheme and host p's requests go to, for a URL of the vendor's own outside its API (WorkBuddy's /v3/config beside its /v2): a plugin's where its loader sends them, which p.Do then takes there through the plugin; any other's its API's. "" when it has none.

func (Provider) OwnBalanceEstimate added in v0.1.3295

func (p Provider) OwnBalanceEstimate(keyID string) (BalanceEstimate, bool)

OwnBalanceEstimate is what is left of the balance typed for p's key keyID, and whether it has one.

func (Provider) OwnClient added in v0.1.1217

func (p Provider) OwnClient() bool

OwnClient says magpie's requests to p go as a client the vendor serves, whatever agent sent them: OpenCode's gateway is sent OpenCode's User-Agent, Cline's Cline's, Kilo's the Kilo CLI's, and another magpie magpie's.

func (Provider) OwnModelID added in v0.1.2345

func (p Provider) OwnModelID(model string) string

OwnModelID is the provider's own id of its model listed as model: the id the vendor is asked for it by, the same as model unless the user lists it by another (SetModelID).

func (Provider) OwnPaused added in v0.1.455

func (p Provider) OwnPaused() bool

OwnPaused says the provider is the account a Claude Code or Codex agent is signed in to, paused while another of its accounts is on (#263): the gateway passes over it, the agent staying signed in to it. A request's plan asks it of every account provider, each ask its own read of logins.json under its lock: listed once a request, as Logins is (#5104), and a write lists it anew.

func (Provider) OwnQuotaRest added in v0.1.1230

func (p Provider) OwnQuotaRest(now time.Time) time.Duration

OwnQuotaRest is how long, from now, one of p's keys sits out of quota when the vendor doesn't say when it is back: until the next QuotaResetAt when one is set, else QuotaRest; 0 for the gateway's own.

func (Provider) PaidBesideFree added in v0.1.1214

func (p Provider) PaidBesideFree(model string) bool

PaidBesideFree says model costs its subscription's credits while the subscription serves other models at no cost to them (catalog.Model's Free: WorkBuddy's "x0.00", Qoder's is_free, Cline's free models). Its credits running out then says nothing of those: they draw on none (Creat.wu on Discord). False for a model not on the list, or where no model is free.

func (Provider) ParseLevels added in v0.1.1360

func (p Provider) ParseLevels(model, v string) (levels []string, off bool, err error)

ParseLevels is a typed reasoning answer for p's model: the levels to keep in their order, and off for no reasoning ask. "auto" is no levels and not off. Levels are the model's own when its list gives them, else any of Levels; a range runs from one to the other in that order, both included.

func (Provider) PassedReplyHeaders added in v0.1.2028

func (p Provider) PassedReplyHeaders(h http.Header) http.Header

PassedReplyHeaders are the headers of the vendor's reply h that go on to the agent: the defaults and the ones the user listed for the provider, matched whatever their case, never one ReplyHeaderPassable refuses. nil when there are none.

func (Provider) PassesErrors added in v0.1.3190

func (p Provider) PassesErrors() bool

PassesErrors says the gateway hands p's errors to the agent as they came and asks it nothing again (PassErrors).

func (Provider) PassesUserAgent added in v0.1.1217

func (p Provider) PassesUserAgent() bool

PassesUserAgent says a request to p goes with the User-Agent of the agent that sent it (#1851): p is a key+URL provider, and the user didn't set it to go as magpie (MagpieUserAgent). A signed-in account and a plugin's provider sign as their own client; OpenCode's, Cline's and Kilo's gateways are sent the client they serve (OwnClient), and another magpie is told magpie by it: none of them takes the agent's in its place.

func (Provider) PeakOf added in v0.1.2173

func (p Provider) PeakOf(model string) catalog.Peak

PeakOf is the hours a call to model at p is billed double in, by the vendor p sends it to: its base URLs say which, and only a provider with none is told by its preset or id. A plugin's base (plugin://) names no vendor, so the Command Code plan its plugin serves is told by its id (treeman on Discord: its DeepSeek models showed no peak hours). Empty for any other provider or model.

func (Provider) PeekServerCert

func (p Provider) PeekServerCert(ctx context.Context) (ServerCertSeen, error)

PeekServerCert is the certificate p's first HTTPS base URL shows, asked through p's own proxy (and with its client certificate, when the server asks for one) with the certificate taken unchecked, so the user can see its fingerprint before trusting it (trust on first use). Its pin, if it has one, plays no part.

func (Provider) Picks added in v0.1.1162

func (p Provider) Picks() []string

Picks are the models the user picked, with those the vendor has listed since beside them (withNewlyListed): what agents are served of the picks, and what an editor starts its picks from. None when nothing is picked.

func (Provider) PicksOf added in v0.1.2447

func (p Provider) PicksOf(avail []catalog.Model) []string

PicksOf is Picks of avail, p.Available() as the caller has already read it (ExposedOf).

func (Provider) PinHosts

func (p Provider) PinHosts() []string

PinHosts are the base URLs a trusted server certificate (ServerPin) is taken at: every endpoint of a provider that takes a client certificate (TakesClientCert), and of a preset's only the https:// addresses the user gave it at a host of their own (Ollama on another computer, an Azure resource), never the vendor's own hosts (Zhangzhangi on X). None for a subscription's or a plugin's account.

func (Provider) PlanDrawers added in v0.1.1117

func (p Provider) PlanDrawers() []catalog.Model

PlanDrawers are the image-generation models explicitly included in the preset region's plan. They are separate from its chat models.

func (Provider) PlanEmbeddings added in v0.1.1117

func (p Provider) PlanEmbeddings() []catalog.Model

PlanEmbeddings are the embedding models explicitly included in the preset region's plan. They are resolved by the embeddings API but kept out of agents' chat-model lists.

func (Provider) PlanRerankers added in v0.1.3097

func (p Provider) PlanRerankers() []catalog.Model

PlanRerankers are the rerank models the preset names, as PlanEmbeddings are its embedding models.

func (Provider) PlanRetrieval added in v0.1.3097

func (p Provider) PlanRetrieval(kind string) []catalog.Model

PlanRetrieval are the preset's models of kind's (catalog.ServesEmbedding, ServesRerank, ServesSpeech or ServesTranscription), or its embedding and rerank models for "".

func (Provider) PlanServing added in v0.1.1600

func (p Provider) PlanServing(model string) func(KeyAccount) bool

PlanServing is, for each of p's keys, whether the plan that key is for can serve model: false only when p's keys are on different plans (KeyAccount.Plan) and the key's plan names its models and leaves this one out — a pay-as-you-go model id sent to the Agent Plan's endpoint only answers 404. A model the user set the key to serve (AccountModels) it serves. Every key serves when p's keys are on one plan, as before.

func (Provider) PlanSpeakers

func (p Provider) PlanSpeakers() []catalog.Model

PlanSpeakers are the text-to-speech models the preset names, served on /v1/audio/speech.

func (Provider) PlanTranscribers

func (p Provider) PlanTranscribers() []catalog.Model

PlanTranscribers are the speech-to-text models the preset names, served on /v1/audio/transcriptions.

func (Provider) PlanVideos added in v0.1.1117

func (p Provider) PlanVideos() []catalog.Model

PlanVideos are the video-generation models explicitly included in the preset region's plan.

func (Provider) PlansMixed added in v0.1.1600

func (p Provider) PlansMixed() bool

PlansMixed reports whether p's keys in use are on more than one of its preset's plans (KeyAccount.Plan).

func (Provider) PluginAPI

func (p Provider) PluginAPI() string

PluginAPI is the base URL the plugin's provider says p's requests go to (its `api`): https://api.mistral.ai/v1 behind a Mistral Vibe plugin. "" for a provider that isn't a plugin's.

func (Provider) PluginAccountKey added in v0.1.2949

func (p Provider) PluginAccountKey() string

PluginAccountKey is the account's key in the plugin host's sign-ins (provider or provider#slot), "" for a provider not a plugin's.

func (Provider) PluginAtOnce added in v0.1.2502

func (p Provider) PluginAtOnce() int

PluginAtOnce is how many of its accounts the plugin giving the provider says may take requests at the same time, as it lists it now; 0 for none, or for a provider no plugin gives.

func (Provider) PluginConcurrency added in v0.1.633

func (p Provider) PluginConcurrency() int

PluginConcurrency is what the plugin giving the provider says it takes at once, as it lists it now; 0 for none, or for a provider no plugin gives.

func (Provider) PluginOpenAICompatible added in v0.1.1747

func (p Provider) PluginOpenAICompatible(model string) bool

PluginOpenAICompatible is whether p is a plugin's provider that speaks model on an OpenAI-compatible API (@ai-sdk/openai-compatible), whose other routes, the images API among them, its fetch sends under the same base: SenseNova's plugin at token.sensenova.cn/v1. A plugin of a vendor with an API of its own (Cursor's, Kiro's) speaks another package.

func (Provider) PluginProvider added in v0.1.584

func (p Provider) PluginProvider() string

PluginProvider is the id OpenCode knows the plugin's provider p is by (grok, kiro), whatever magpie names it; "" for one no plugin gives.

func (Provider) PluginUser added in v0.1.2247

func (p Provider) PluginUser(user string) string

PluginUser is PluginUserOf the account user of p, "" for a provider no plugin gives.

func (Provider) Prepare

func (p Provider) Prepare(body []byte) []byte

Prepare adjusts a request body the way the backend wants it.

func (Provider) PriceAt added in v0.1.2235

func (p Provider) PriceAt(s settings.Settings, model string, at time.Time) (catalog.Price, bool)

PriceAt is what a call to model at p costs when made at at, as Usage counts one made then: EffectivePriceAt for p as the caller holds it (a routing group's member, at the rate of the key it holds), its Peak still set, for the caller to apply with Price.In and tell whether it did. A model served at no cost there (FreeModel) costs nothing.

func (Provider) PricedFree added in v0.1.2880

func (p Provider) PricedFree(s settings.Settings, model string) bool

PricedFree says model is listed at $0 on p (ListPrice) on every count and at every size: a free model a catalog prices at 0 there, as OpenRouter's foo:free, OpenCode Zen's -free ones or NVIDIA NIM's. The pickers say free beside it (jiangguochao666 on X), where catalog.Model's Free has only the vendor's own word. It is p's price alone: the same id on another provider is that one's, and its maker's (makerListPrice) or a plan's catalog's says nothing of p's. A model nothing prices is not free, nor one the user set a price for that isn't 0: their word is the price Usage counts.

func (Provider) Pricer

func (p Provider) Pricer() Pricer

Pricer is p's Pricer.

func (Provider) PricesInYuan

func (p Provider) PricesInYuan() bool

PricesInYuan is whether p sells in China's yuan, for Settings' currency "provider", which shows each provider's costs in what it prices in. A preset's provider at the preset's own site does when it is a yuan preset (yuanPresets, or an id ending in -cn: Kimi (China), MiniMax (China)…) or in its China region (a first catalog ending in -cn: Xiaomi's); one moved to another site (a relay made from DeepSeek's preset) is not that vendor. Any provider on a .cn host does, and so does a plugin's id ending in -cn (Qoder CN). A provider of its own (no preset) does with a yuan catalog (catalog.PricedInYuan) served at that catalog's own site. Everything else is in dollars.

func (Provider) ProxyChoice added in v0.1.427

func (p Provider) ProxyChoice() string

ProxyChoice is the proxy requests made on the provider's behalf go through, as netproxy.With takes it: for one account of a subscription that holds several, or one key of a provider that holds several (Beyfish_Wang on X: 不同 key 走不同的代理), its own (AccountProxies), else the provider's (Proxy); "" follows the global one. An account in use beside the agent's own is made afresh by some agents (AlsoOn), without the provider's settings: those are read from providers.json.

func (Provider) QuotaRestFor added in v0.1.1214

func (p Provider) QuotaRestFor() time.Duration

QuotaRestFor is how long one of p's keys sits out of quota when the vendor doesn't say when it is back, 0 for the gateway's own.

func (Provider) RPMLimit added in v0.1.1119

func (p Provider) RPMLimit() int

RPMLimit is how many requests a minute each of p's keys or accounts may send the vendor, 0 for no limit: the provider's MaxRPM. An account not had from All or AlsoOn (made afresh by its sign-in) carries none of the provider's settings: it is read from providers.json then.

func (Provider) RateAt added in v0.1.2200

func (p Provider) RateAt(t time.Time) float64

RateAt is the rate the provider's windows bill at at t, 0 for none.

func (Provider) Ready

func (p Provider) Ready() bool

Ready reports whether the provider can be used: it has a key, needs none, is a signed-in agent, or is Vertex AI at a project (whose credentials are read when a request is signed).

func (Provider) Refetch added in v0.1.769

func (p Provider) Refetch(ctx context.Context) ([]catalog.Model, []string, error)

Refetch is Fetch, and says which of the user's picks it dropped: those the list fetched before had and the one fetched now doesn't. The new list replaces the old one, and a pick made from the old list goes with it — kept, it stayed among the models agents see, as if typed in by hand, though the vendor serves it no more (akic404 on Discord: a remote magpie offering far fewer models, and one of its providers renamed, still listed every old "ws-ba5my…/qwen3.6-max" here after a Refresh). A pick the old list didn't have was typed in by hand, and stays; a fetch that fails, or that answers no model at all, changes nothing.

func (Provider) RefetchTaking added in v0.1.1234

func (p Provider) RefetchTaking(ctx context.Context) (ms []catalog.Model, dropped, taken []string, err error)

RefetchTaking is Refetch, and says which models the provider's AutoInclude rules took into its picks: those the list fetched now has, the one before didn't, and a rule matches (takeMatching, #2135).

func (Provider) RefreshInterval added in v0.1.1234

func (p Provider) RefreshInterval() time.Duration

RefreshInterval is how often the gateway fetches the provider's list by itself: 0 for only when asked, and for one RefreshEvery can't be read. A Remote magpie with none set is fetched every RemoteMagpieEvery.

func (Provider) RefreshSchedule added in v0.1.1506

func (p Provider) RefreshSchedule() string

RefreshSchedule is the schedule the provider's list is fetched on, as written: its user's, or a Remote magpie's default (RemoteMagpieEvery) when its user set none; "" for only when asked.

func (Provider) RejectsTemperature

func (p Provider) RejectsTemperature(model string) bool

RejectsTemperature reports whether the model is known to refuse temperature and top_p. The answer comes from the catalog — models.dev plus the vendor's own list — so a model released after this binary was built is handled without a code change.

func (Provider) RemotePrefers

func (p Provider) RemotePrefers(model string) Protocol

RemotePrefers is the API a remote magpie's list says it asks the model on best (magpie_prefers, PreferredEndpoint there); "" for another provider's model, or one from a magpie from before it said.

func (Provider) RemotePriced added in v0.1.1131

func (p Provider) RemotePriced(model string) bool

RemotePriced reports whether the model's list price is the one a remote magpie's list gave, for the editor to say whose it is.

func (Provider) RemoteVia added in v0.1.3007

func (p Provider) RemoteVia(model string) []string

RemoteVia is the magpies a remote magpie's model passes through to its vendor, as its list said, that magpie last (catalog's magpie_via.go); nil for another provider's, or a list from a magpie from before.

func (Provider) ReplyLimit added in v0.1.916

func (p Provider) ReplyLimit(m catalog.Model) int

outputOf is the most a reply of a model may hold, as the user said it: the model's own, else the one given for every model of its provider, else 0 for the vendor's own list and models.dev to answer. It mirrors ContextOf, which the user sets on the provider itself. ReplyLimit is the most a reply of the provider's model may hold, in tokens, as agents are told it and the Gateway's model list shows it: the user's Max output, else the vendor's list's, else models.dev's.

func (Provider) ReplyLimitIn added in v0.1.1093

func (p Provider) ReplyLimitIn(m catalog.Model, s settings.Settings) int

ReplyLimitIn is ReplyLimit from settings s already read.

func (Provider) ResolveAuto added in v0.1.444

func (p Provider) ResolveAuto(ctx context.Context, model string) (context.Context, string, error)

ResolveAuto turns a request for a model the account picks itself (Copilot's Auto) into one for the model it picked: ctx then carries what the request is signed with. Any other model comes back as it was.

func (Provider) ResponsesFirst added in v0.1.300

func (p Provider) ResponsesFirst(model string) bool

ResponsesFirst: an OpenAI model on OpenAI's API, Copilot's, PipeLLM's or Bedrock's, which is best asked on the Responses API though Chat serves it too; and every model where only the Responses API tells what the vendor's cache answered (ResponsesTellsCache).

func (Provider) ResponsesTellsCache added in v0.1.1183

func (p Provider) ResponsesTellsCache() bool

ResponsesTellsCache is a provider whose Responses API says how much of the prompt its cache answered (input_tokens_details.cached_tokens) and what the model reasoned, while its Chat API, served by the same cache, says neither: ModelScope's API-Inference, by its preset or its host (#1578, sparrowbits: Claude Desktop, translated to Chat, read 0 of 34.9M tokens from cache; Codex on Responses, 94%). A translated request goes there on Responses, and an agent that asks each model on one API is wired to it. Other vendors with both URLs keep Chat: their Chat reports its cache (Groq, Volcengine Ark), their Claude-format requests go to their Anthropic URL as they are, or nothing is known of their Responses API (a relay the user added).

func (Provider) RestCapOr added in v0.1.1230

func (p Provider) RestCapOr(def time.Duration) time.Duration

RestCapOr is the most one of p's keys or accounts sits out while it keeps failing: the user's RestCap, else the gateway's own def (RestCapOff included: it says nothing of a rate limit's rest).

func (Provider) RestKey added in v0.1.930

func (p Provider) RestKey(k KeyInfo) string

RestKey is what the gateway rests the key k of a provider by: the provider's id while it has one key on, else the id and the key's.

func (Provider) RestKeys added in v0.1.1265

func (p Provider) RestKeys() func(KeyInfo) string

RestKeys is RestKey for each of a provider's keys in turn, whether it has more than one on found once: found again for every key, a list of a thousand keys was read a thousand times over, and the Providers page took seconds to draw it, minutes for five thousand (@NetRozee on X).

func (Provider) Retries added in v0.1.438

func (p Provider) Retries() bool

Retries is whether the account can mend a refusal (Retry), so the refusal's body is worth reading before it is passed on.

func (Provider) Retry added in v0.1.438

func (p Provider) Retry(ctx context.Context, sent []byte, status int, body []byte) bool

Retry is whether a request (sent) the backend refused with status and body is worth sending once more, the account having mended what it named.

func (Provider) SelfAnswered added in v0.1.3021

func (p Provider) SelfAnswered() bool

SelfAnswered says this Remote magpie was found to be this magpie, at the address it has now.

func (Provider) SelfLeftOut added in v0.1.3021

func (p Provider) SelfLeftOut() bool

SelfLeftOut is whether the provider is left out of routing and lists as a Remote magpie that is this magpie, which the user didn't keep.

func (Provider) SentHeaders added in v0.1.2058

func (p Provider) SentHeaders(ctx context.Context) map[string]string

SentHeaders are p's Headers, with those the user gave the model ctx says is asked after them (WithModel, headersFor), as they go out on a request of ctx's conversation (conversationOf): the placeholders in their values as its ids, without control characters. p.Headers itself when the model has none and no value has one.

func (Provider) SentIDAt

func (p Provider) SentIDAt(model, effort string) string

SentIDAt is the id a request for model at effort goes to p under: for a family of a relay's effort ids offered as one model, the id of the effort asked (Provider.relayFamily.at: that level, else the nearest the relay lists, else with none asked the model's own id when listed, else medium); any other id as it is, an id of one of the family's members too, at whatever effort, as it went before the family was one model. The user's name for the model upstream (UpstreamNameAs) is put on after.

func (Provider) Serves added in v0.1.38

func (p Provider) Serves(k KeyAccount, model string) bool

Serves reports whether key k can be asked for model: false only when the vendor's lists say another of the provider's keys sees it and k doesn't. A key no list marks — its own wasn't answered, or it was added since — is unknown, and serves: a failed list is not an empty one (#1598, the first of five keys left out of every request). The lists are read whole, the models that draw or make videos among them: a text key never says it serves an image model only another key lists (#1657).

func (Provider) ServesNone added in v0.1.1214

func (p Provider) ServesNone() bool

ServesNone is the user's Select none (NoModels) with nothing picked: none of its models are served, its balance and usage still read.

func (Provider) Serving added in v0.1.1265

func (p Provider) Serving(model string) func(KeyAccount) bool

Serving is Serves for model, for each of the provider's keys in turn: the lists are read once, not once a key. Read for every key of every request, a provider of a thousand keys had its list's file looked at a thousand times, and each model's thousand keys looked along, before a request went out: a tenth of a second a request, seconds for five thousand keys (@NetRozee on X).

func (Provider) Sign

func (p Provider) Sign(ctx context.Context, req *http.Request, proto Protocol, body []byte) error

Sign authenticates a request to the provider, refreshing what needs it. Plain providers get their key; accounts get the agent's tokens.

func (Provider) SignInNeeded

func (p Provider) SignInNeeded() bool

SignInNeeded says every account of p in use has to be signed in again, as the Providers page shows it (needsSignIn): a model of p is asked of none of them, each refused for its sign-in. False when one is usable, or none is in use or known.

func (Provider) SignedOut added in v0.1.1310

func (p Provider) SignedOut() bool

SignedOut says that p is a signed-in account whose every account in use (on, or the one the agent is signed in to) has had its sign-in refused: listed, so it can be signed in again, but not "signed in". It is what the app's Providers row says as "{user} is signed out", for magpie providers and the TUI to say the same (LeeHom on Discord: Claude Code listed on two lapsed accounts).

func (Provider) SkipsRedaction added in v0.1.1091

func (p Provider) SkipsRedaction() bool

SkipsRedaction says requests to p go unmasked: the user set Unredacted ("Send requests unmasked") and p has somewhere they go. It is the user's word for each provider whatever the address (AcMilan on Discord), a subscription's and a plugin's too (isee1_1 on Discord: a plugin's provider never had the switch): the editor cautions while it is on for one not on this computer or the local network, which a signed-in account's or a plugin's vendor never is, and nothing here looks one up. Another magpie (a Remote magpie) set so is sent the request as written, with no X-Magpie-Masked-As, so it masks by its own Settings › Privacy and its own providers' switches before anything reaches a vendor (CrazyMouse_TT on X: a model of the user's own behind that magpie); left off, it is sent the request masked here, as before.

func (Provider) SocketByDefault

func (p Provider) SocketByDefault() bool

SocketByDefault says p's turns go over the Responses WebSocket with Socket unset (SocketMode).

func (Provider) SocketMode

func (p Provider) SocketMode() string

SocketMode is how p's Responses turns go: SocketAuto, SocketOn, or "" for HTTP alone. A Socket the user set is kept; unset, OpenAI's own API (an https Responses URL at api.openai.com) is auto, as Codex's built-in OpenAI provider speaks its WebSocket mode to it (supports_websockets in codex-rs's create_openai_provider). There a conversation's next turn goes as its new input after previous_response_id, even with store false, where HTTP sends the whole conversation every turn (KawaiiZapic on X). Any other address is HTTP alone unless set.

func (Provider) Speaks

func (p Provider) Speaks() []Protocol

Speaks lists the protocols the vendor serves natively, preferred first.

func (Provider) TakesClientCert

func (p Provider) TakesClientCert() bool

TakesClientCert is whether the provider may show a client certificate of its own, or trust a server CA of its own (ClientCert, #5596): one the user added with a base URL of its own, as TakesInsecureTLS, and Remote magpie, whose other magpie may ask for one (`magpie mtls`).

func (Provider) TakesDecideAPI added in v0.1.3300

func (p Provider) TakesDecideAPI() bool

TakesDecideAPI reports whether p's models can be set to be asked on its System One URL: a key's provider with one beside a conversation URL. A provider with a System One URL alone asks every model there already; a signed-in account, a plugin and a remote magpie say which of theirs decide themselves.

func (Provider) TakesImageFiles added in v0.1.3079

func (p Provider) TakesImageFiles() bool

TakesImageFiles says whether ImageFilesOff has any effect on p: one of its Chat, Responses or Anthropic URLs is DeepSeek's own API. The editor offers image-files only then.

func (Provider) TakesInsecureTLS added in v0.1.1258

func (p Provider) TakesInsecureTLS() bool

TakesInsecureTLS is whether the provider may have its certificate left unchecked (InsecureTLS, #2383): only one the user added with a base URL of their own. A subscription's or a plugin's account, a preset's (whose vendor serves a certificate that checks) and a built-in's never do, whatever providers.json says.

func (Provider) TakesModelIDs added in v0.1.2345

func (p Provider) TakesModelIDs() bool

TakesModelIDs is whether p's models can be listed by ids the user gives them (SetModelID).

func (Provider) TakesOwnBalance added in v0.1.3281

func (p Provider) TakesOwnBalance() bool

TakesOwnBalance says p's keys may have a balance typed by hand: keys whose vendor tells none magpie knows where to ask. A relay whose query is looked for (probesBalance) takes one too: when none is found, the typed balance is shown.

func (Provider) TakesPassErrors added in v0.1.3190

func (p Provider) TakesPassErrors() bool

TakesPassErrors says PassErrors can be set for p: a provider of an API key, a preset vendor's or one the user added. A signed-in account and a plugin's provider never take it: magpie reads their errors to keep the account well (a sign-in to renew, a plan's window to wait out).

func (Provider) TakesResolve

func (p Provider) TakesResolve() bool

TakesResolve is whether the provider may have its hosts connected to addresses of the user's choosing (Resolve): one the user added with a base URL of its own, as TakesInsecureTLS, and a preset's at a host of its own (PinHosts' rule, never the vendor's), so a managed network's gateway can stand in for a company's relay. A subscription's or a plugin's account never does: a plugin's requests are made by its host, which has no way to be told where to connect.

func (Provider) TakesServerPin

func (p Provider) TakesServerPin() bool

TakesServerPin is whether the provider may trust a server certificate of its own by fingerprint (ServerPin): it has an address PinHosts takes.

func (Provider) TakesSocket added in v0.1.3397

func (p Provider) TakesSocket() bool

TakesSocket says p can have its turns go over the Responses WebSocket (Socket): a provider of a key with a Responses URL. A signed-in account or a plugin's provider has its own way there.

func (Provider) TakesUsageCap

func (p Provider) TakesUsageCap() bool

TakesUsageCap says whether p has usage windows a cap can hold it at: a subscription's accounts, or the keys of a vendor whose keys tell their plan's windows (an OpenCode Go key's 5 hours, week and month, a sub2api key's limits: key_allowance.go). A key's cap is set and kept as an account's, by the key's id, and read from the key's windows as last read.

func (Provider) Test

func (p Provider) Test(ctx context.Context) []Result

Test sends the smallest possible request to each endpoint the vendor serves, signed with a key made for it and asking for a model that key sees, and reports what came back.

func (Provider) TestClients added in v0.1.1158

func (p Provider) TestClients() map[string]string

TestClients is the clients p's models can be tested as, each with why it can't be yet ("" when it can): those whose API p has, of a provider reached with a key; Claude Code only of a relay.

func (Provider) TestModels added in v0.1.163

func (p Provider) TestModels(ctx context.Context, models []string) []Result

TestModels sends each of models the smallest request, a few at a time, on the endpoint it's served on and with a key that sees it: whether each answers, not only whether the vendor does. Results are in models' order.

func (Provider) TestPicks

func (p Provider) TestPicks() []TestPick

TestPicks are the accounts or keys of p that are on, to pick one from for a test; none when p has fewer than two.

func (Provider) TestsAs added in v0.1.1158

func (p Provider) TestsAs(client string) string

TestsAs says why p can't be tested as client asks ("" when it can).

func (Provider) Thinks added in v0.1.1084

func (p Provider) Thinks(model string) bool

Thinks reports whether the model reasons: it has levels, its list says it thinks, or models.dev says most of those serving it do (Entry's Reasoning).

func (Provider) UncheckedHosts added in v0.1.1258

func (p Provider) UncheckedHosts() []string

UncheckedHosts are the base URLs whose host's certificate is taken as it is when the provider has InsecureTLS: its own endpoints, never a models, balance or image URL elsewhere.

func (Provider) UpstreamNames added in v0.1.560

func (p Provider) UpstreamNames() map[string]string

UpstreamProviders are the names the user gave the provider's models, by model id, with the one given for all of them under "*" — each as it will be sent, trimmed, "*" and all, which is what a list of them shows. A name that is only whitespace is none, and is not listed.

func (Provider) VendorHost

func (p Provider) VendorHost() string

VendorHost is the host of the vendor's API p's requests are shaped for: Host(), and for a plugin's provider in front of a vendor magpie has a preset for, that vendor's API host (api.mistral.ai), where Host() is the plugin's id. The gateway's checks of whose API a request goes to read this; Host() stays where calls are kept and shown.

func (Provider) VendorPreset

func (p Provider) VendorPreset() string

VendorPreset is the preset of the vendor p's requests are shaped for: p.Preset, and for a plugin's provider in front of a vendor magpie has a preset for, that preset (mistral).

func (Provider) VertexExpress

func (p Provider) VertexExpress() bool

VertexExpress is whether the provider is asked as Vertex AI's express mode is: an API key and no project, which serves Gemini models alone.

func (Provider) Via added in v0.1.418

func (p Provider) Via(ctx context.Context) context.Context

Via is ctx for requests made on the provider's behalf: they go through its own proxy (ProxyChoice), or the global one when it has none. A provider the user added and asked not to have its certificate checked (InsecureTLS) has its own hosts' taken as they are, no other host's, and one whose server certificate the user trusted (ServerPin) has them taken with that certificate alone; one with connect addresses (Resolve) has its hosts' connections made there; one asked to be spoken HTTP/1.1 to (HTTP1) is, at its own hosts alone; one whose turns go over the Responses WebSocket (Socket) has them go there, at its Responses URL alone (SocketTurn).

func (Provider) VideomakerHidden added in v0.1.2845

func (p Provider) VideomakerHidden(model string) bool

VideomakerHidden is whether the user unticked p's video model in its editor (HiddenVideomakers): it is left out of the lists a video model is picked from and of Automatic's choice, and still makes videos when named.

func (Provider) Where added in v0.1.122

func (p Provider) Where() string

Where is what the provider's calls go to, as usage keeps it: the API's host, and for a subscription who is signed in there too. The id alone can't tell: it can be given to another vendor or account later.

func (Provider) WindowIn

func (p Provider) WindowIn(m catalog.Model, s settings.Settings) int

WindowIn is WindowOf with the settings s already read.

func (Provider) WindowOf added in v0.1.816

func (p Provider) WindowOf(m catalog.Model) int

WindowOf is the window one of the provider's models takes, as agents are told it and requests are routed on it: the one the user set for the model over ListedWindow. The one set for all of the provider's models ("*") is no larger than a model's own, where the provider says it (the window its list or its models.dev catalog gives, or the most it may be asked for, MaxContext): set to 512K to spend less, it told opencode-go's cat-jam-free, which takes 262K, 512K (#2112). The window models.dev gives the id under other vendors (catalog.ContextOf) is not the provider's word but magpie's guess, and never caps what the user set: a custom OpenAI-compatible relay set to 1M told its claude-sonnet-4-5 200K (MisakaNatsuxun on Discord, 10-23). One set for the model itself is the user's word on it, larger or not. The catalog's entries and the Providers page's model lists both read it, so the page shows the window agents are told.

func (Provider) WithExtraBody added in v0.1.1191

func (p Provider) WithExtraBody(body []byte, c Conversation) []byte

WithExtraBody is body with the provider's extra fields merged in, as the package's comment says; c is the conversation for ${sessionId} and ${threadId}, its Subagent for ${subagentId}. A body that isn't a JSON object goes as it came.

func (Provider) WithKey added in v0.1.15

func (p Provider) WithKey(k KeyAccount) Provider

WithKey is p using key k: at k's plan's endpoints when k is for a plan of its own (KeyAccount.Plan), and its endpoints narrowed to k's protocol when k has one. It has none left when p doesn't serve that protocol.

type ProxyUse

type ProxyUse struct {
	Provider string `json:"provider"`
	Account  string `json:"account,omitempty"`
}

ProxyUse is a place a saved proxy is chosen: a provider (Account empty), or an account or key of one.

func ProxyUses

func ProxyUses(id string) []ProxyUse

ProxyUses lists where the saved proxy id is chosen among the providers, so that deleting it can say what would lose it. Settings' own two (global, plugin downloads) are the caller's.

type Quota added in v0.1.114

type Quota struct {
	Provider string      `json:"provider"`
	Name     string      `json:"name"`
	Kind     string      `json:"kind"` // subscription, plan (bought with a key) or balance (a key's money)
	Plan     string      `json:"plan,omitempty"`
	User     string      `json:"user,omitempty"`
	Windows  []QuotaSpan `json:"windows"`
	Balance  string      `json:"balance,omitempty"`
	// BalanceSplit is what the Balance is made of, when the vendor tells
	// it (SubscriptionQuota's)
	BalanceSplit []BalancePart `json:"balanceSplit,omitempty"`
	// SharedBalance is the first of the keys whose Balance is this key's
	// account's too (SubscriptionQuota's)
	SharedBalance string     `json:"sharedBalance,omitempty"`
	Error         string     `json:"error,omitempty"`
	AsOf          *time.Time `json:"asOf,omitempty"` // the cached reading's time, nil for a new one
	// ReadDeferred says no request was made this time, rather than one failed.
	ReadDeferred bool `json:"readDeferred,omitempty"`
	// ReadError is why the reading AsOf stands in for failed.
	ReadError string `json:"readError,omitempty"`
	// ReadAt is when the windows or balance shown were read, nil when not
	// known; a Claude account's can be well before now (claudeReadAt).
	ReadAt *time.Time `json:"readAt,omitempty"`
	// Until is when the plan's paid time ends, renewed then when Renew is
	// "auto", over when "off", either when "".
	Until *time.Time `json:"until,omitempty"`
	Renew string     `json:"renew,omitempty"`
	// Resets are a Codex account's rate-limit resets, when it holds any.
	Resets *ResetCredits `json:"resets,omitempty"`
	// ResetsUsed are the Codex account's resets magpie spent, newest
	// first, by itself or by hand (codex_resets_used.go)
	ResetsUsed []ResetUse `json:"resetsUsed,omitempty"`
	// LastServedAt is when the account, plan or key last answered a
	// request through the gateway, nil when it hasn't in the last 30 days
	// (served.go); Last is on the latest of them (#570).
	LastServedAt *time.Time `json:"lastServedAt,omitempty"`
	Last         bool       `json:"last,omitempty"`
	// From is the remote magpie whose account this is, by its name here
	// (remote_quotas.go); "" for this computer's own.
	From string `json:"from,omitempty"`
	// Alias is the account's name of the user's own, else Seat: the name
	// of the key plan whose card this account's stands in for (#1515).
	Alias string `json:"alias,omitempty"`
	Seat  string `json:"seat,omitempty"`
}

Quota is one account's or key's allowance as magpie quota --json and the gateway's GET /v1/magpie/quotas tell it, for an agent choosing where to send its work: Provider is the first part of the models' ids (provider/model) for a key's plan or balance, the agent for a subscription.

func CodexStatuslineCards

func CodexStatuslineCards(model string, qs []Quota) []Quota

CodexStatuslineCards are the accounts a Codex thread's footer shows (lyj1115 on X: the quota of the account in use, or the relay's balance, under Codex's chat box): those of the provider the thread's latest turn went to (model is provider/model), the one that answered last of them, a key's balance as well as a subscription's windows; with no such account, the one that answered last of all.

func KeptQuotaReport added in v0.1.1231

func KeptQuotaReport(now time.Time) []Quota

KeptQuotaReport is QuotaReport from what was last read (CachedCards), asking no vendor: for a status line, which Claude Code runs again on every message (#1997), so it must neither wait for a read nor start one.

func QuotaReport added in v0.1.114

func QuotaReport(ctx context.Context, now time.Time) []Quota

QuotaReport is Quotas as Quota, the reset times made absolute from now.

func RefreshReport added in v0.1.1233

func RefreshReport(ctx context.Context, provider, user string, now time.Time) []Quota

RefreshReport is RefreshUsage answering the cards it read, as QuotaReport tells them: magpie quota refresh (#2104), which reads the card the Usage page's refresh button does and shows only it. A process that has read no other card yet (the CLI) has nothing to merge it into, so the cards come from the read itself, not from the caches.

func StatuslineCards added in v0.1.2883

func StatuslineCards(qs []Quota, only []string) []Quota

StatuslineCards are the subscriptions and plans with windows to show: those named, else those that answered through magpie lately, else all.

type QuotaAlert added in v0.1.540

type QuotaAlert struct {
	Provider string
	Name     string // the card's name, as the Usage page shows it
	User     string // the account or key, when the provider has several
	Window   string // the window's name
	Used     float64
	ResetsAt *time.Time
	Balance  string // the balance as the vendor tells it
	// Kind is "" for the alerts above; "renews" for a long window renewing
	// within the reminder's hours with much of it left, "expires" for
	// reset credits running out by then, Credits of them (#720)
	Kind    string
	Credits int
}

QuotaAlert is one thing to tell the user: a window used past the share (Window set) or a balance at or under the amount (Balance set).

func NearLimits

func NearLimits(qs []SubscriptionQuota, pct int, bal float64, now time.Time) []QuotaAlert

NearLimits is what the readings qs show now at or past the alert's share of a window (pct, 0 is none) or at or under its balance (bal, 0 is none), said or not: the daily summary's (EV_John_Liu on X), where the alerts themselves go once, by their marks. A reading that failed, or is one kept from before, says nothing.

type QuotaHistory added in v0.1.722

type QuotaHistory struct {
	Provider string      `json:"provider"`
	User     string      `json:"user"`
	Lines    []QuotaLine `json:"lines"`
}

QuotaHistory is one account's windows over time. User is lowercased.

func QuotaHistories added in v0.1.722

func QuotaHistories(since time.Time, provider, user string) []QuotaHistory

QuotaHistories is every account's windows' points since since, the accounts and windows in name order; provider and user, when given, pick one provider's, or one account's.

func RemoteQuotaHistories added in v0.1.1078

func RemoteQuotaHistories(ctx context.Context, days string) []QuotaHistory

RemoteQuotaHistories is every remote magpie's quota history since days ago, as its own GET /v1/magpie/quotas/history has it (read from its disk, no vendor asked), the providers named as RemoteCards names them.

type QuotaLine added in v0.1.722

type QuotaLine struct {
	Name   string       `json:"name"`
	Points []QuotaPoint `json:"points"`
}

QuotaLine is one window's points, oldest first.

type QuotaPoint added in v0.1.722

type QuotaPoint struct {
	At       time.Time  `json:"at"`
	Left     float64    `json:"left"`
	Start    *time.Time `json:"start,omitempty"`
	ResetsAt *time.Time `json:"resetsAt,omitempty"`
}

QuotaPoint is one reading of a window: at At, Left percent was left; the window began at Start and starts again at ResetsAt, when told.

func (QuotaPoint) StartsCycleAfter added in v0.1.1258

func (p QuotaPoint) StartsCycleAfter(previous QuotaPoint) bool

StartsCycleAfter uses the same observed reset boundaries that history sampling preserves, including refills with an unchanged deadline.

type QuotaSpan added in v0.1.114

type QuotaSpan struct {
	Unlimited bool       `json:"unlimited,omitempty"`
	Name      string     `json:"name"`
	Used      float64    `json:"used"`
	Remaining float64    `json:"remaining"`
	ResetsAt  *time.Time `json:"resetsAt,omitempty"`
	Display   string     `json:"display,omitempty"` // the vendor's own count, "1.2k / 3k"
	// Text: the window is its Display alone, Used and Remaining no
	// reading (QuotaWindow.Text)
	Text bool `json:"text,omitempty"`
	// Lane names an allowance apart from the account's own (QuotaWindow.Lane)
	Lane string `json:"lane,omitempty"`
	// Amount of Limit in Unit: the window's count, used, when the vendor
	// counts it so ("credits")
	Amount float64 `json:"amount,omitempty"`
	Limit  float64 `json:"limit,omitempty"`
	Unit   string  `json:"unit,omitempty"`
	Pool   string  `json:"pool,omitempty"` // the shared pool the window draws on ("Gemini")
	// RunsOutAt is when the soonest of what is left is lost, apart from
	// the reset, and RunsOut how much (QuotaWindow.RunsOutAt): WorkBuddy's
	// credits come in packages that each end on their own day, and a free
	// account's have no reset at all (#3762).
	RunsOutAt *time.Time `json:"runsOutAt,omitempty"`
	RunsOut   float64    `json:"runsOut,omitempty"`
	// Balance is how much is left in Unit, a prepaid wallet's reading
	// (QuotaWindow.Balance, #3950): Used and Remaining are then no share.
	Balance *float64 `json:"balance,omitempty"`
	// Spent is what magpie counted such a wallet spending since
	// SpentSince, its period's first reading (QuotaWindow.Spent, #5770).
	Spent      *float64   `json:"spent,omitempty"`
	SpentSince *time.Time `json:"spentSince,omitempty"`
	// Holds and HoldsWhy are the window's whole as the Usage page's card
	// tells it (QuotaWindow.Holds, #2333): reckoned when ReckonHolds is
	// set, else left out.
	Holds    *WindowHolds `json:"holds,omitempty"`
	HoldsWhy string       `json:"holdsWhy,omitempty"`
}

QuotaSpan is one window of an allowance: how much of it is used and left, in percent, and when it starts again.

type QuotaWindow

type QuotaWindow struct {
	Unlimited bool       `json:"unlimited,omitempty"`
	Name      string     `json:"name"`
	Used      float64    `json:"used"`
	ResetsAt  *time.Time `json:"resetsAt,omitempty"`
	ResetSecs int64      `json:"resetSecs,omitempty"`
	Display   string     `json:"display,omitempty"`
	// Text is set on a window that is its Display alone, with no share
	// to tell: a plugin's row of what an account holds or has done
	// (AutoClaw's 积分余额 and 每日签到, Cursor's on-demand spend, ZCode's
	// gift to claim), which plugins send set aside with used 0 and no
	// count. Its Used is no reading, so it is told as its text, never as
	// "100% left". Claude's "Extra usage" row (claudeOveragesWindow) is
	// the one Text window with Used 100: the account counts as spent.
	Text bool `json:"text,omitempty"`
	// Lane names a window of an allowance apart from the account's own
	// ("images", ImageLane): its row is Text, and says only when it comes
	// back, if known. Added as cards are handed out (WithImageLane), never
	// cached.
	Lane string `json:"lane,omitempty"`
	// Amount of Limit is the window's own count in Unit, when the vendor
	// counts it so (WorkBuddy's credits): Used is Amount as a share of
	// Limit. The GUI says it as used or left, as it says the share (#659).
	Amount float64 `json:"amount,omitempty"`
	Limit  float64 `json:"limit,omitempty"`
	Unit   string  `json:"unit,omitempty"`
	// RunsOutAt is when the soonest of what is left is lost, and RunsOut
	// how much (in Unit), when it runs out apart from the window's reset:
	// WorkBuddy's credits come in packages that each end on their own
	// day. Smart routing takes it for the window's renewal (cdredfox on X).
	RunsOutAt *time.Time `json:"runsOutAt,omitempty"`
	RunsOut   float64    `json:"runsOut,omitempty"`
	// Balance is how much is left of the window in Unit, when the vendor
	// tells only that: a prepaid wallet, with no total to take a share of
	// (SuperMagic's points, #3950). Used is then no reading (0); the GUI
	// says the figure left, and routing knows the account by it and puts
	// the one with the most left first among a provider's accounts in the
	// same unit (Allowance.Left). nil when not told. On an account with a
	// usage cap, Amount of Limit and Used are what the wallet spent in the
	// cap's period instead (wallet_spend.go, #5770), for the cap to hold.
	Balance *float64 `json:"balance,omitempty"`
	// Spent is, on a wallet's window (Balance), how much of it magpie saw
	// go since SpentSince, the first reading of the period a cap counts it
	// over: the window's own until its reset, else the local day
	// (wallet_spend.go). nil when not counted.
	Spent      *float64   `json:"spent,omitempty"`
	SpentSince *time.Time `json:"spentSince,omitempty"`
	// Family is the model family a per-model window belongs to (Antigravity's
	// "Gemini 3.1 Pro (High)" is Gemini's), for the GUI to show one figure a
	// family, the tightest; each window is still here, and routing reads
	// them one by one.
	Family string `json:"family,omitempty"`
	// Pool is the group of models that share one allowance (Antigravity's
	// "Gemini", "Claude & GPT"): on the group's own windows, a 5-hour and
	// a weekly, which name no Model, and on each per-model window drawing
	// on it, for the GUI to show the group's windows in place of its
	// models'.
	Pool string `json:"pool,omitempty"`

	// For routing (see Allowances): how long the window runs, zero when
	// not known; the only models it counts, by a word in their ids
	// ("opus"), when it doesn't count them all; and Aside when using it up
	// doesn't stop the account — on-demand spending past the allowance,
	// or Copilot's code completions, which no request here makes.
	Span  time.Duration `json:"-"`
	Model string        `json:"-"`
	Aside bool          `json:"-"`
	// Credits is set on each window of a ChatGPT account that holds
	// credits (has_credits with a balance left, or unlimited): using the
	// window up doesn't stop it, the vendor spends the credits instead
	// (codexGoesOnCredits); and on each of a Kimi Code key's while its
	// booster holds money (kimiBooster). Routing reads it
	// (Allowance.OnCredits); kept
	// with the reading, so one shown from before still says it.
	Credits bool `json:"credits,omitempty"`
	// Extra is set on a Claude account's "Usage credits" window
	// (claudeExtraWindow): the extra usage Anthropic bills past the plan,
	// set aside. A cap the user sets on it holds the account at 100% of a
	// plan window once reached (Allowance.extraCapped), never outright.
	Extra bool `json:"extra,omitempty"`
	// Capped is set, for the GUI only (WithCapped), on a window an
	// account's usage cap counts: neither Aside nor unlimited. One model's
	// own counts for that model (CapHeld), so it is marked like the rest.
	Capped bool `json:"capped,omitempty"`
	// CapsSome is set beside Capped on a window that counts some models
	// only — one model's own, or a pool's — so the cap holds the account
	// for those alone, and the GUI says which.
	CapsSome bool `json:"capsSome,omitempty"`
	// CapID is, beside Capped, how the window is known to a cap of its
	// own (WindowCapID), for the GUI to set and show one.
	CapID string `json:"capId,omitempty"`
	// OwnCap is set beside Capped on a window set aside: only a cap the
	// user set on it itself holds the account there (WindowCaps.own),
	// never the account's, and the GUI offers none new.
	OwnCap bool `json:"ownCap,omitempty"`
	// Holds is what the whole window holds, reckoned from magpie's own
	// calls through the account (usage.WithWindowHolds), for the GUI and,
	// through ReckonHolds, magpie quota --json and /v1/magpie/quotas
	// (#2333); nil where that can't be told honestly.
	Holds *WindowHolds `json:"holds,omitempty"`
	// HoldsWhy is, where Holds is nil on a window of an account's own card
	// that runs out and starts again, why its whole isn't told (#2045):
	// HoldsLow, HoldsNoClock, HoldsBeforeLog, HoldsNoneRouted or
	// HoldsCredits. Empty where no whole is ever told (a pool, a family,
	// money aside, another magpie's card).
	HoldsWhy string `json:"holdsWhy,omitempty"`
	// StartsAt is when the window began (Bounds), for the GUI only
	// (WithWindowStarts): with ResetsAt it places an even pace through the
	// window, which the card's Pace number is measured from (fflake33).
	StartsAt *time.Time `json:"startsAt,omitempty"`
	// TrayKind is, for the GUI only, how Settings names the window among
	// those the menu bar can show (gui.withTrayKinds): "5h", "7d",
	// "month", "7d:grok bot"; empty on one the menu bar can't say as a
	// percent.
	TrayKind string `json:"trayKind,omitempty"`
	// TrayExtra is, for the GUI only, set on a window with a TrayKind that
	// the menu bar shows only when picked (gui.trayChoices): money aside,
	// one model's window, Cursor's Grok Bot.
	TrayExtra bool `json:"trayExtra,omitempty"`
	// HeldBy is, for the GUI only (WithHeldWindows), the name of another
	// window of the account that is used up and stops it for every model
	// ("7 days"): what is left of this one can't be used until that one
	// starts again, so a sum over accounts counts it as nothing left
	// (#4791).
	HeldBy string `json:"heldBy,omitempty"`
	// contains filtered or unexported fields
}

QuotaWindow is one rolling allowance reported by a subscription provider.

func PoolMembers added in v0.1.1729

func PoolMembers(ws []QuotaWindow, w QuotaWindow) []QuotaWindow

PoolMembers are the per-model windows among ws whose models draw on pool window w's allowance: the ones its pool's name was given to (googleAccount.pools), else, when none was (a pool read with only its 7 days, as an Antigravity Starter plan's), the ones of a family its name says ("Claude & GPT": Claude, GPT-OSS) and no other pool took. A pool named for one model ("Gemini 4 Argon") has only the models it was given.

func PooledWindows added in v0.1.613

func PooledWindows(ws []QuotaWindow) []QuotaWindow

PooledWindows are ws as a page of text shows them: a pool's own windows, named with their pool ("Gemini · 7 days"), in place of the per-model windows drawing on it; ws as it is when it has no pool. A model's window goes only for a pool window of its span: one whose pool has only its 7 days stays, the 5 hours it reads being the only ones to be had (#745).

func (QuotaWindow) Bounds added in v0.1.1120

func (w QuotaWindow) Bounds(readAt time.Time) (start, end time.Time, ok bool)

Bounds is when w, read at readAt, began and ends: its reset, and that less how long it runs; a month's window began on the same day a month before. ok is false when either isn't known.

func (QuotaWindow) Count added in v0.1.738

func (w QuotaWindow) Count(left bool) string

Count is the window's own count as the GUI says it, beside its share: "355 / 500 credits" used, or what is left of it when left (#659); the vendor's Display when it doesn't count in amounts.

func (QuotaWindow) Counts added in v0.1.1120

func (w QuotaWindow) Counts(model string) bool

Counts is whether a call to model counts against w: every model, or only the ones its scope names ("opus", a plugin's list).

func (QuotaWindow) CountsIn added in v0.1.1729

func (w QuotaWindow) CountsIn(ws []QuotaWindow, model string) bool

CountsIn is whether a call to model counts against w, one of ws, the windows of its account's card: a pool's window counts its models' calls (PoolMembers), by the model's own id or the one its effort word is a level of (gemini-3.8-flash is gemini-3.8-flash-medium's); any other as Counts says.

func (QuotaWindow) LineName added in v0.1.1729

func (w QuotaWindow) LineName() string

LineName is the name w's readings are kept under (quota-history.json) and its line drawn by: a pool's window with its pool's name before its own ("Gemini · 5 hours"), as every pool has a "5 hours".

func (QuotaWindow) Pace added in v0.1.1232

func (w QuotaWindow) Pace(readAt, now time.Time) (pace float64, ok bool)

Pace is how far w's use, read at readAt, is from an even pace through the window at now, in points of the window (fflake33 on Discord): what is used less the share of the window gone by. +12 is twelve points more used than an even pace would have used by now, so at this rate the window runs out before it resets; -8 is eight points to spare. ok is false for a window with no limit, or whose start or reset isn't known, or when now is outside it.

func (QuotaWindow) PoolWindow added in v0.1.1729

func (w QuotaWindow) PoolWindow() bool

PoolWindow is whether w is one of an Antigravity pool's own windows ("Gemini" · 5 hours, · 7 days), the allowance its models share, not a model's own window drawing on it.

type RateWindow added in v0.1.2200

type RateWindow struct {
	Days  []int   `json:"days,omitempty"`
	Start string  `json:"start"`
	End   string  `json:"end"`
	Rate  float64 `json:"rate"`
}

RateWindow is a time-of-day window a provider bills at its own rate (#2463): a relay that charges 2× or 3× at peak and a discount off peak. Start and End are "HH:MM" on this computer's clock, End may be "24:00"; Start after End crosses midnight, and the window then belongs to the day it starts on, its Days among them. Days are time.Weekday's numbers (Sunday 0), empty for every day. Rate is what the provider bills against the official price inside the window, on top of PriceRate: from just over 0 to 1000, at most three decimals. The first window that holds a call's time wins; outside every window the price rate alone counts. The window's rate scales a price the user set for a model too, which the price rate alone leaves as set.

func BaseKeyPriceIn

func BaseKeyPriceIn(s settings.Settings, providerID, keyID, model string) (catalog.Price, bool, []RateWindow)

BaseKeyPriceIn is BasePriceIn for a call the provider's key keyID sent: at the key's own price rate when it has one (KeyPriceRates, @tnt12231 on X), else the provider's. An empty keyID, or one the provider doesn't rate apart, is BasePriceIn.

func BasePriceIn added in v0.1.2200

func BasePriceIn(s settings.Settings, providerID, model string) (catalog.Price, bool, []RateWindow)

BasePriceIn is EffectivePriceAt without a rate window's rate: what the provider bills outside every window, and the third return is its windows, for RateAt to read each record's time against. A caller pricing many records holds both and multiplies the rates itself, as the usage ledger's Pricer does, so one read serves every time of day.

func RateWindowsOf added in v0.1.2200

func RateWindowsOf(id string) []RateWindow

RateWindowsOf is the rate windows of the provider with id, or of the one renamed from it, none for a provider not known: for a caller holding a base price to read each call's time against (#2463).

func UserBasePriceIn added in v0.1.3086

func UserBasePriceIn(s settings.Settings, providerID, model string) (catalog.Price, bool, []RateWindow)

UserBasePriceIn is BasePriceIn without the catalogs' word: the price the user set for a provider's model themselves, a zero included — the model's own, else every model of that provider's, else every model's (settings' ModelPrices) — with the peak a vendor bills by the hour marked on it and the provider's windows as the third return, as BasePriceIn hands them. It is the first place BasePriceIn looks, alone for a caller that asks for the user's word before the catalogs' (#5340).

type Refill added in v0.1.3295

type Refill struct {
	Every string `json:"every"`
	Day   int    `json:"day"`
}

Refill is when a balance typed is whole again: at midnight, local time, on Day of each month (1–31, a month without that day on its last) or of each week (1 Monday to 7 Sunday), or each day (Day 0).

func ParseRefill added in v0.1.3295

func ParseRefill(s string) (*Refill, error)

ParseRefill reads a refill as the CLI takes it: monthly (on the 1st), monthly:15, weekly (on Monday), weekly:fri or weekly:5, daily (each midnight); off or never for none (nil).

func (Refill) Last added in v0.1.3295

func (r Refill) Last(now time.Time) time.Time

Last is the last refill at or before now, in now's location.

func (Refill) Next added in v0.1.3295

func (r Refill) Next(now time.Time) time.Time

Next is the first refill after now, in now's location.

func (Refill) String added in v0.1.3295

func (r Refill) String() string

String is r as the CLI takes and shows it: monthly:1, weekly:mon, daily.

type Region

type Region struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Chat      string `json:"chat,omitempty"`
	Responses string `json:"responses,omitempty"`
	Anthropic string `json:"anthropic,omitempty"`
	// Lists is set on a region that serves a model list although the
	// preset as a whole has none to ask for (NoList): a provider at its
	// endpoints is asked for it. KeysURL, when the region's keys are made
	// on another page than the preset's, is where its Get-a-key link goes.
	Lists   bool   `json:"lists,omitempty"`
	KeysURL string `json:"keysUrl,omitempty"`
	// Website, when the region's docs are another page than the preset's,
	// is where the editor's link goes.
	Website  string `json:"website,omitempty"`
	SiteHost string `json:"siteHost,omitempty"` // as PresetDef's
	// Catalog, for a region whose models another models.dev entry names
	// than the preset's (Tencent Cloud's pay as you go, beside its plan's
	// none), is that entry's id.
	Catalog string `json:"catalog,omitempty"`
	// Models are a plan's text models, for a region that is one beside
	// another plan or pay as you go (PresetDef.Models, for the region alone).
	// Embeddings, Rerankers, Drawers and Videos are its non-chat models, kept apart from
	// agents' model pickers.
	Models     []string `json:"models,omitempty"`
	Embeddings []string `json:"embeddings,omitempty"`
	Rerankers  []string `json:"rerankers,omitempty"`
	Drawers    []string `json:"drawers,omitempty"`
	Videos     []string `json:"videos,omitempty"`
	// Speakers and Transcribers are its text-to-speech and speech-to-text
	// models, as PresetDef's.
	Speakers     []string `json:"speakers,omitempty"`
	Transcribers []string `json:"transcribers,omitempty"`
	// Images says which of Models take images, as the vendor's own list
	// says, for a plan whose /models doesn't list its models: a model
	// it leaves out is judged as before (models.dev, the user's say).
	Images map[string]bool `json:"-"`
	// Decide is the region's decision API, for a preset that routes groups
	Decide string `json:"decide,omitempty"`
}

Region is one base-URL option of a preset that offers several. The first is the default; picking another in the editor swaps the endpoints.

type RemoteHub added in v0.1.3127

type RemoteHub struct {
	ID, Name, Root, Key string
	Was                 []string
}

RemoteHub is a Remote magpie as its router's server is made: its address (the gateway's root) and its key, and the ids it had before it was renamed (Provider.Was), which its server follows.

func RemoteHubs added in v0.1.3127

func RemoteHubs() ([]RemoteHub, error)

RemoteHubs are the Remote magpies in providers.json, turned off or not, but one found to be this magpie, and one without an address or a key. An error is providers.json unreadable: which there are is unknown.

type RemotePicks

type RemotePicks struct {
	Provider string
	Agents   map[string]map[string]string
}

RemotePicks is one Remote magpie's AgentModels, under its provider id here: a ref there is Provider+"/"+ref in this magpie's catalog.

func RemoteAgentPicks

func RemoteAgentPicks(ctx context.Context) (out []RemotePicks, errs map[string]error)

RemoteAgentPicks asks every Remote magpie, in the order they were added, the models its agents are on. One that can't tell (unreachable, older, a held key) is left out, its error in errs by provider id.

type RemoteUpdate added in v0.1.3285

type RemoteUpdate struct {
	// updating: it is being put in, and magpie restarts into it once
	// idle; current: nothing newer to put in; off: automatic updates are
	// turned off there; unsupported: it can't update itself (Why);
	// old: a magpie from before RemoteUpdatePath; refused: the key isn't
	// one of full access there
	State string `json:"state"`
	// Version is what the remote runs (as answered), or is updating to,
	// or can't update itself to (kept here)
	Version string `json:"version,omitempty"`
	// Why it can't: container, package, not-writable, source
	Why string `json:"why,omitempty"`
	// Manager and Command, a package manager's copy: its name and what
	// updates it
	Manager string `json:"manager,omitempty"`
	Command string `json:"command,omitempty"`
}

RemoteUpdate is RemoteUpdatePath's answer, and what is kept here of a remote's last ask.

func AskRemoteUpdate added in v0.1.3285

func AskRemoteUpdate(ctx context.Context, p Provider, version string) RemoteUpdate

AskRemoteUpdate asks the Remote magpie p to update itself, this magpie running version.

func RemoteUpdateOf added in v0.1.3285

func RemoteUpdateOf(id string, now time.Time) (RemoteUpdate, bool)

RemoteUpdateOf is what the Remote magpie id last answered an ask to update, when the row should say something of it: updating (for a while), or why it didn't.

type Renames added in v0.1.1478

type Renames struct {
	// contains filtered or unexported fields
}

Renames say which provider a call recorded under a provider id was made to, as its id is now: a provider renamed takes the calls recorded under the ids it had (Was), and an id another provider took since (Gave) is that one's only from then on (cybercaius on Discord: a renamed provider's usage was shown under its old id and its new one).

func RenamesOf added in v0.1.1478

func RenamesOf(now map[string]string) Renames

RenamesOf are renames of ids to the ones they are now, none given away (for a test).

func UsageRenames added in v0.1.1478

func UsageRenames() Renames

UsageRenames are the renames of providers.json as it is now, worked out once each time the file changes and shared, so read only: each profile's in-use check on every state poll parsed the whole file again for them, 5 MB of forty polls with real accounts.

func (Renames) Both added in v0.1.1807

func (r Renames) Both(id string, at time.Time) (shown, own string)

Both is Of, and Own beside it: the provider a call is shown under and the one it is priced as. They differ only for a deleted provider merged into another, whose calls cost what they did before the merge.

func (Renames) Each added in v0.1.1478

func (r Renames) Each(id string) []string

Each is every id a call recorded under id can go to (Of), by when it was made.

func (Renames) Empty added in v0.1.1478

func (r Renames) Empty() bool

Empty is whether no id is renamed.

func (Renames) Gone added in v0.1.1776

func (r Renames) Gone(id string) (Deleted, bool)

Gone is the deleted provider whose calls are counted under id: its own id while no provider has it, or its UsageID.

func (Renames) Key added in v0.1.1478

func (r Renames) Key() string

Key is r as text, for a cache of what was worked out with it.

func (Renames) Merged added in v0.1.1807

func (r Renames) Merged(id string) []string

Merged are the deleted providers merged into id, by the ids Gone knows them by, oldest deleted first.

func (Renames) Of added in v0.1.1478

func (r Renames) Of(id string, at time.Time) string

Of is the id the provider a call recorded under id at the time at has now; id itself when it was not renamed. A zero at is before every hand-over. A deleted provider the user merged into another is that one (Deleted.Into); Own is the id without the merge, which the call is priced by.

func (Renames) OnHost added in v0.1.1726

func (r Renames) OnHost(host string) bool

OnHost is whether a provider saved now is on host, one or more.

func (Renames) OnSite added in v0.1.1751

func (r Renames) OnSite(host string) (id string, on bool)

OnSite is the provider saved now on a host of host's site (SiteOf), for a probe recorded under a host no provider is on: CyberCaius on Discord, Leee's model list was asked at leee.baby before it was saved on another host of that site, and the Usage page listed leee.baby beside it. on is whether any provider is on that site; id is "" when two are, or host has no site.

func (Renames) Own added in v0.1.1807

func (r Renames) Own(id string, at time.Time) string

Own is Of without merges: the provider the call was made to, by the id it has now, a deleted one by its own (UsageID). What it cost is worked out under it, and what decides by who answered (the gateway's loggedAnswers, window holds) goes by it.

func (Renames) ProbeOf added in v0.1.1697

func (r Renames) ProbeOf(id string, at time.Time) string

ProbeOf is Of for one of magpie's own requests (probelog): one sent while a provider was being added, its Detect or Test before it had an id, is recorded under its host, and is the provider's on that host now. yyddbds on Discord: 大灰狼, on dahuilang.best, was listed twice in the Requests page's providers, once as dahuilang.best for the model lists asked while adding it. A host two providers are on, or none, stays as it is.

func (Renames) Same

func (r Renames) Same(o Renames) bool

Same is whether o is r itself, the one read UsageRenames hands back while providers.json is unchanged: the same maps, not equal ones. A reader that keeps what it made from r asks it to know r is unchanged.

func (Renames) Timed added in v0.1.1478

func (r Renames) Timed(id string) bool

Timed is whether the id's calls go to more than one provider by when they were made, so Of needs each call's time.

type Renewal added in v0.1.75

type Renewal struct {
	Agent string `json:"agent"`
	User  string `json:"user"`
	// Renewed is false when it wasn't due; Err is why it failed, and Lapsed
	// whether the sign-in is gone (the vendor refused it) or may yet renew.
	Renewed bool   `json:"renewed"`
	Err     string `json:"error,omitempty"`
	Lapsed  bool   `json:"lapsed,omitempty"`
}

Renewal is what came of renewing one saved account.

func RenewLogins added in v0.1.75

func RenewLogins(ctx context.Context, every time.Duration) []Renewal

RenewLogins renews the saved ChatGPT and Claude sign-ins not in the agent's hands that have gone every or longer without it; every 0 renews all of them, one that failed lately too.

type ResetAt added in v0.1.1230

type ResetAt struct {
	Hour, Minute int
	Loc          *time.Location
}

ResetAt is a time of day an allowance comes back: an hour and minute, on this computer's clock (Loc nil) or at a fixed offset from UTC.

func ParseResetAt added in v0.1.1230

func ParseResetAt(s string) (*ResetAt, error)

ParseResetAt reads a time of day as QuotaResetAt keeps it: "08:00", "8:30", "00:00+08:00", "16:00Z". "" is none, with no error.

type ResetCard added in v0.1.1076

type ResetCard struct {
	Until  *time.Time `json:"until,omitempty"`
	Window string     `json:"window,omitempty"`
	ID     string     `json:"id,omitempty"`
}

ResetCard is one reset: when it runs out (nil: it never does) and, of resets counted by window, which one's ("fiveHour", "weekly"). ID is a Codex reset's own credit id, which a use by hand names to spend that one rather than the one that runs out first (UseCodexResetCard).

type ResetCredits added in v0.1.282

type ResetCredits struct {
	Count int        `json:"count"`
	Until *time.Time `json:"until,omitempty"`
	// ByWindow: each reset is for one window, FiveHour of the five hours'
	// and Weekly of the week's, and is spent on the vendor's own page (a
	// GLM Coding team plan's, zcode_team.go), not from magpie
	ByWindow bool `json:"byWindow,omitempty"`
	FiveHour int  `json:"fiveHour,omitempty"`
	Weekly   int  `json:"weekly,omitempty"`
	// Team: the resets are a GLM Coding team plan's, not the person's own
	Team bool `json:"team,omitempty"`
	// Each is every reset still to be used and when it runs out, the
	// soonest first, one that never does last (#960: the card's tooltip
	// lists them, where it only said the first). Empty when the vendor
	// didn't say.
	Each []ResetCard `json:"each,omitempty"`
	// contains filtered or unexported fields
}

ResetCredits is how many rate-limit resets an account holds and the soonest one of them runs out; Until is nil when none does, or when that couldn't be read (untilUnread then).

func (ResetCredits) Words added in v0.1.425

func (r ResetCredits) Words() string

Words are the resets counted: "2 resets", or by window, "2 five-hour resets · 1 weekly reset".

type ResetOutcome added in v0.1.282

type ResetOutcome struct {
	Code    string `json:"code"`
	Windows int    `json:"windows"`
}

ResetOutcome is what spending a reset did: Code is the vendor's word for it (reset, nothing_to_reset, no_credit, already_redeemed) and Windows how many windows started again. Claude's resets are gone (9bf6d4352, #1972); "already_used" below was their word and no longer comes.

func AutoUseCodexReset added in v0.1.507

func AutoUseCodexReset(ctx context.Context, user string) (ResetOutcome, error)

AutoUseCodexReset spends one of the Codex account user's resets (the one Codex is signed in to when "") if the user turned that on for it, its weekly window is used up, it holds one, and none was spent by itself in this week yet. Code is "" when none was tried; the caller asks again only on "reset".

func SpendCodexReset added in v0.1.2834

func SpendCodexReset(ctx context.Context, user, credit string) (ResetOutcome, error)

SpendCodexReset is a reset used by hand wherever it is asked: the Usage page's "Use a reset" and the gateway's RemoteCodexResetPath, for another magpie's card or an app holding a gateway key (#3850, prgrmrwy). It is UseCodexResetCard, then, when the windows started again, a wait of up to 10s for routing and the Providers page to know so (#1491).

func UseCodexReset added in v0.1.282

func UseCodexReset(ctx context.Context, user string) (ResetOutcome, error)

UseCodexReset spends one of the rate-limit resets of the Codex account user (the one Codex is signed in to when ""), starting its current usage windows again: the one that runs out first, so none that would last longer goes before it. It can't be undone: callers ask first. The account's usage is read afresh after, and the use is kept as one made by hand (ResetsUsed).

func UseCodexResetCard added in v0.1.2474

func UseCodexResetCard(ctx context.Context, user, credit string) (ResetOutcome, error)

UseCodexResetCard is UseCodexReset spending the reset credit the user chose, of those ResetCredits.Each lists (01huadalang on Discord: one that lasts longer, kept for later, may be the one they want gone first). The account's resets are read again first: a credit no longer among those still to be used is never spent, nor any other in its place. credit "" is the one that runs out first.

func UseRemoteCodexReset added in v0.1.2834

func UseRemoteCodexReset(ctx context.Context, id, user, credit string) (ResetOutcome, error)

UseRemoteCodexReset has the remote magpie whose card id is (its Codex card, "office/codex") spend one of user's resets there, as its own Usage page would (#3850, prgrmrwy: the card here said "1 reset", and using it took a walk to the other computer). credit is one of the card's resets.each, "" for the one that runs out first. The account is always named: which one the remote is signed in to isn't known here, and a reset can't be undone. The remote's cards are read afresh after, so the card shows its windows started again.

func (ResetOutcome) Text added in v0.1.282

func (o ResetOutcome) Text() string

Text says an outcome in words.

type ResetUse added in v0.1.1227

type ResetUse struct {
	User    string    `json:"user"`
	At      time.Time `json:"at"`
	Why     string    `json:"why"`
	Windows int       `json:"windows,omitempty"` // how many windows started again
}

ResetUse is one reset magpie spent on an account.

func ResetsUsed added in v0.1.1227

func ResetsUsed(user string) []ResetUse

ResetsUsed is what magpie spent of the Codex account user's resets, newest first, resetsUsedShown at most; nil when none, or when the file can't be read.

type Result

type Result struct {
	Account  string   `json:"account,omitempty"`
	Protocol Protocol `json:"protocol"`
	OK       bool     `json:"ok"`
	Status   int      `json:"status,omitempty"`
	Millis   int64    `json:"ms"`
	Model    string   `json:"model,omitempty"`
	Error    string   `json:"error,omitempty"`

	// Queued is the vendor's queue message when a plugin's model was
	// queued instead of answered (Qoder's "queued the request for ...").
	// The model is served, so the test is OK: it waits where an agent's
	// turn waits it out.
	Queued string `json:"queued,omitempty"`
	// V1 is the base the request was answered at once the /v1 it was
	// typed without was added (missingV1): the editor's URL takes it
	V1 string `json:"v1,omitempty"`
	// Unserved: the vendor serves this key nothing on this API, whatever
	// the model (catalog.APIRefused: sub2api's "This group does not allow
	// /v1/messages dispatch"). Not a failure of the key: the gateway asks
	// its models on its other APIs.
	Unserved bool `json:"unserved,omitempty"`
	// Region is the region of the provider's preset the key was taken
	// at, once refused at the one it was tested at (testOtherPlace): the
	// editor moves the provider there.
	Region string `json:"region,omitempty"`
	// contains filtered or unexported fields
}

Result is what a probe of one endpoint came back with.

type Rule added in v0.1.94

type Rule struct {
	Use string `json:"use"` // the member, as the group names it: "provider/model"
	// More: the members the rule sends to after Use, in order, each tried
	// when the ones before it can't take the request (monkeyin_92 on X: one
	// rule for several models, not a rule each). They go before the
	// members the matching rules after it name, and the group's others.
	// Use stays the first, so a magpie from before More still sends the
	// rule's requests to it, and has the others behind it as group members.
	// A pause names one model and has none.
	More []string `json:"more,omitempty"`
	// UseEffort: the reasoning the member is asked for on the requests the
	// rule sends it (one of Efforts), in place of what the agent asked —
	// an intent picks the model and its effort as a pair (#2633). Like a
	// member fixed at an effort, it is fitted to the model's own levels,
	// and a model whose levels aren't known is asked as the agent asked.
	// It is an output, as Use is; Effort below is a condition.
	UseEffort string `json:"useEffort,omitempty"`
	// Tokens: the request is at least this long, in tokens — the larger of
	// an estimate from its size and what the vendor counted for the
	// conversation's last request.
	Tokens int `json:"tokens,omitempty"`
	// Images: the request carries an image, in this turn or before.
	Images bool `json:"images,omitempty"`
	// Effort: the agent asked for reasoning at least this level (one of
	// Efforts), or "on" for any reasoning at all.
	Effort string `json:"effort,omitempty"`
	// Agents: the request is from one of these agents (usage.AgentOf ids).
	Agents []string `json:"agents,omitempty"`
	// Intent: the user's message at the turn's start is of this kind, as
	// the group's Classifier judges it — "writing or fixing tests",
	// "a quick question". When the classifier can't say, it doesn't match.
	Intent string `json:"intent,omitempty"`
	// Compact: the agent is compacting its conversation — asking a model to
	// summarize it so it can go on in less room (Claude Code's /compact,
	// Codex's, OpenCode's, Pi's…) — which a cheaper, faster model can do
	// in place of the one the conversation is on.
	Compact bool `json:"compact,omitempty"`
	// Time: the turn begins within these hours of the day, in the window's
	// zone (TimeWindow.Zone) — a vendor's peak-price hours sent to another,
	// say.
	Time *TimeWindow `json:"time,omitempty"`
	// Folders: the request's working folder, as the agent states it in
	// the request, is one of these or inside one — a project, or every
	// project under a folder (Cario0x on X). "~/work", "/Users/me/x",
	// "C:\work"; WSL's /mnt/c/work is C:\work. When the agent doesn't
	// say its folder, it doesn't match.
	Folders []string `json:"folders,omitempty"`
	// ExceptFolders: the request's working folder is none of these nor
	// inside one, as Folders reads them. A request whose agent doesn't say
	// its folder is not known to be in one, so it holds for it: a pause
	// "except in ~/big-task" keeps the model for requests known to come
	// from there (#1606), never for one that may come from elsewhere.
	ExceptFolders []string `json:"exceptFolders,omitempty"`
	// Where: conditions as a field, a way to compare and a value
	// (rulecond.go) — "effort is not off", "tokens < 20000", "agent is
	// not codex", "subagent", "message contains …" — for what the fields
	// above can't say. A magpie from before them doesn't read them, and a
	// rule of them alone has no condition there, so it matches nothing.
	Where []Cond `json:"where,omitempty"`
	// Pause: rather than sending to Use first, the rule leaves Use out of
	// the group while it holds (John on Discord: a model paused in a
	// vendor's peak hours). Only Time, Agents, Folders and ExceptFolders
	// (and Where's agent conditions) can be its conditions: the request's
	// clock, its agent and the folder it says, never what it asks for — a pause keeps the model out of the
	// request whatever it is.
	Pause bool `json:"pause,omitempty"`
}

Rule sends the requests it matches to one of its group's members first, and then to the others it names, in order. Every condition set must hold; a rule sets at least one.

func ParseRule added in v0.1.136

func ParseRule(g Group, words []string) (r Rule, at int, classifier string, err error)

ParseRule makes a rule of k=v words; the model is resolved among the group's members. classifier is the group's classifier when one was given, at the place asked for (from 1) when one was.

func (Rule) ByFolder added in v0.1.1191

func (r Rule) ByFolder() bool

ByFolder reports whether the rule holds by the folder the agent works in, in some or outside them: the request's folder is then read for it.

func (Rule) Conditions added in v0.1.94

func (r Rule) Conditions() []string

Conditions says what a rule matches, for a list or a trace.

func (*Rule) InZoneHere added in v0.1.1524

func (r *Rule) InZoneHere()

InZoneHere puts a rule's window typed with no time zone in this computer's (LocalZone), as magpie group rule and the TUI read it: the hours are the ones the person typing them means. It stays without one when this computer's zone has no IANA name.

func (Rule) Line added in v0.1.136

func (r Rule) Line() string

Line is the rule as ParseRule reads it back.

func (*Rule) MapUses added in v0.1.1486

func (r *Rule) MapUses(f func(string) string)

MapUses has each member the rule sends to go by what f makes of it: a member renamed, cleaned or taken out ("").

func (Rule) Matches added in v0.1.94

func (r Rule) Matches(q RuleRequest) bool

Matches reports whether the request is one the rule sends to its member first; a pause rule sends none (see Pauses).

func (Rule) MatchesBesidesIntent added in v0.1.95

func (r Rule) MatchesBesidesIntent(q RuleRequest) bool

MatchesBesidesIntent is Matches but for the rule's intent: whether the classifier's answer is all it waits on.

func (Rule) Names added in v0.1.1486

func (r Rule) Names(m string) bool

Names reports whether the rule sends to m.

func (Rule) Pauses added in v0.1.1155

func (r Rule) Pauses(agent, folder string, at time.Time) bool

Pauses reports whether a pause rule holds for a request from agent at the time given, working in folder ("" when it didn't say).

func (*Rule) SetUses added in v0.1.1486

func (r *Rule) SetUses(uses []string)

SetUses has the rule send to uses, in order, each once and none empty: the first is Use, the rest More.

func (Rule) Uses added in v0.1.1486

func (r Rule) Uses() []string

Uses are the members the rule sends to, in order: Use, then More.

func (Rule) Without added in v0.1.1486

func (r Rule) Without(m string) (Rule, bool)

Without is the rule with m no longer among the members it sends to; false when it names no other, and goes with m.

type RuleRequest added in v0.1.94

type RuleRequest struct {
	Tokens   int
	Images   bool
	Thinking bool   // the agent asked for reasoning
	Effort   string // at what level, when it said
	Agent    string
	// Intent is the one of the rules' intents the classifier said the
	// user's message is; "" when none, or it wasn't asked.
	Intent string
	// Compact: the request is the agent compacting its conversation.
	Compact bool
	// At is when the request came, for a rule's hours; a zero time is in
	// none.
	At time.Time
	// Folder is the working folder the agent says the request is from;
	// "" when it doesn't say, which is in no rule's folders.
	Folder string
	// Off: the agent turned reasoning off (effort none, thinking
	// disabled), which a rule's effort condition reads as off.
	Off bool
	// Subagent: the request is from a subagent the agent started, as the
	// agent tells it (Claude Code's and Codex's do); false when it can't
	// be told.
	Subagent bool
	// Message is the user's own words at the turn's start, read only when
	// a rule has a message condition (RulesRead).
	Message string
	// System is each block of the request's system prompt as the agent
	// sent it, and Last each text of its last user message, read only
	// when a rule has a system or last condition.
	System, Last []string
}

RuleRequest is what a rule looks at in a request.

type SearchAPI added in v0.1.587

type SearchAPI struct {
	Vendor string `json:"vendor"` // one of SearchVendors
	// Key is its key, or several separated by commas (Keys), each tried
	// when the one before is refused (#1477): the keys that are on, so a
	// magpie that knows no KeyList asks just those.
	Key string `json:"key,omitempty"`
	// KeyList is every key in the list's order, those switched off too
	// (辰林鸭~ on Discord: keys added, removed, put in order and switched
	// off one by one). It is kept only while a key is off; Key alone is
	// the list when every key is on (SearchKeys).
	KeyList []SearchKey `json:"keyList,omitempty"`
	// Pick is how a search picks among several keys: "" takes them in
	// turn (SearchPickTurns), each search the next one; SearchPickOrder
	// asks the first until it is refused, then the next (SlouchyQuill on
	// Discord). Either way a key refused lately is asked last.
	Pick string `json:"pick,omitempty"`
	// URL is where it is: a SearXNG's own, or another address for one of
	// the others (a Firecrawl run by the user); empty is the vendor's.
	URL string `json:"url,omitempty"`
	// Off keeps it, key and all, out of every search until it is switched
	// on again (#2286): to try one API alone, or rest one whose credit is
	// nearly spent, without taking its key away.
	Off bool `json:"off,omitempty"`
	// Mix asks it together with the other search APIs marked so, at once,
	// and gives the model their pages merged, a page two of them found
	// once (#2845): no one API was best on every kind of question, and
	// their pages together found more than any alone. With fewer than two
	// such APIs that can be asked, a search goes in order as before.
	Mix bool `json:"mix,omitempty"`
}

SearchAPI is a web search API the user gave magpie a key to.

func SearchAPIs added in v0.1.587

func SearchAPIs() []SearchAPI

SearchAPIs are the search APIs that can be asked, in the order they are tried: ready, and not switched off.

func StoredSearchAPIs added in v0.1.587

func StoredSearchAPIs() []SearchAPI

StoredSearchAPIs are the search APIs as saved, keys and all.

func (SearchAPI) Base added in v0.1.587

func (a SearchAPI) Base() string

Base is the address it is asked at, without a slash at its end, nor the vendor's own path (SearchVendor.Paths) when its URL was given with it: one saved so before is asked right too (#509).

func (SearchAPI) HasKeys added in v0.1.3251

func (a SearchAPI) HasKeys() bool

HasKeys is whether it holds a key, on or off.

func (*SearchAPI) KeepKeysOf added in v0.1.3251

func (a *SearchAPI) KeepKeysOf(b SearchAPI)

KeepKeysOf gives a, which came with no key (WithoutKeys), b's keys.

func (SearchAPI) Keys added in v0.1.1160

func (a SearchAPI) Keys() []string

Keys are the keys in Key: one, or several the user gave separated by commas, spaces or lines, each once, in the order given.

func (SearchAPI) MaskedKey added in v0.1.1160

func (a SearchAPI) MaskedKey() string

MaskedKey is Key as shown: each of its keys masked (MaskSearchKey), so a list of them shows no more of any one than a single key does.

func (SearchAPI) Name added in v0.1.587

func (a SearchAPI) Name() string

Name is the vendor's name.

func (SearchAPI) Ready added in v0.1.587

func (a SearchAPI) Ready() bool

Ready is whether it can be asked: a vendor magpie knows, at an address, with a key where it needs one (a SearXNG, You.com, may not; one that signs in never does: signed out, a search says so and the next API is asked).

func (SearchAPI) SearchKeys added in v0.1.3251

func (a SearchAPI) SearchKeys() []SearchKey

SearchKeys is every key of the API in its list's order, each on or off. KeyList is the list while its keys that are on are Key's; a Key written by something that knows no KeyList (an older magpie, or one it syncs with) wins: its keys are the ones on, in its order, and a key the list has off that Key doesn't name stays, off, after them.

func (SearchAPI) WithoutKeys added in v0.1.3251

func (a SearchAPI) WithoutKeys() SearchAPI

WithoutKeys is the API with no key, on or off: as a backup or a sync that leaves keys out carries it.

type SearchKey added in v0.1.3251

type SearchKey struct {
	Key string `json:"key"`
	Off bool   `json:"off,omitempty"`
}

SearchKey is one key in a search API's list: off, it is kept and never asked.

type SearchVendor added in v0.1.587

type SearchVendor struct {
	ID, Name string
	Base     string // its address, "" for one the user runs
	KeysURL  string // where its keys are made
	// KeyOptional: it answers with no key too (a SearXNG; You.com's free
	// search, YouFreeSearch)
	KeyOptional bool
	// Paths are what magpie puts after its base URL to search (the
	// gateway's askSearchAPI): a base URL given ending in one of them is
	// that base, so the path isn't asked twice (/search/search, #509)
	Paths []string
	// Plugin is the spec of the plugin that gives this API (its search
	// hook), "" for one of magpie's own; PluginID is its id there. The
	// plugin asks it (plugin.RunSearch); ID is plugin.PluginSearch.VendorID.
	Plugin, PluginID string
	// NeedURL: a plugin's API the user gives an address for, as a SearXNG
	NeedURL bool
	// Auth: a plugin's API that signs in as the same plugin's provider of
	// this id (plugin.SearchDef.Auth), taking no key: each search is one
	// of that provider's accounts that are on (SearchSignIn)
	Auth string
}

SearchVendor is a search API magpie can ask.

func AllSearchVendors added in v0.1.2887

func AllSearchVendors() []SearchVendor

AllSearchVendors are SearchVendors and the search APIs the plugins that are on give (their search hook), after them. A plugin note that can't be read adds none.

func SearchVendorOf added in v0.1.587

func SearchVendorOf(id string) (SearchVendor, bool)

SearchVendorOf is the vendor by its id: one of magpie's, or a plugin's.

func (SearchVendor) WantsURL added in v0.1.2887

func (v SearchVendor) WantsURL() bool

WantsURL is whether the user must give its address (a SearXNG's, or a plugin's that asked for one).

type ServerCertSeen

type ServerCertSeen struct {
	// Host is the host:port asked
	Host string `json:"host"`
	// SHA256 is its fingerprint as ServerPin keeps it
	SHA256 string `json:"sha256"`
	// Subject and Issuer are the names it is issued to and by; Names its
	// DNS names and addresses
	Subject string   `json:"subject"`
	Issuer  string   `json:"issuer"`
	Names   []string `json:"names,omitempty"`
	// NotBefore and NotAfter are when it is good from and until
	NotBefore time.Time `json:"notBefore"`
	NotAfter  time.Time `json:"notAfter"`
	// Checks is whether this computer would take it without a pin: then
	// there's nothing to trust; Why is why not
	Checks bool   `json:"checks"`
	Why    string `json:"why,omitempty"`
}

ServerCertSeen is the certificate a provider's HTTPS host shows, as its editor offers it to be trusted (ServerPin).

type SessionIdentity added in v0.1.579

type SessionIdentity struct {
	Agent, AccountID, UserID, OrganizationID, User string
	// OfficialLogin describes this account's recorded login method, not the
	// route or credentials used for any particular historical request.
	OfficialLogin bool
}

SessionIdentity is an account's public identity, without its credentials.

func SessionIdentities added in v0.1.579

func SessionIdentities(codexDir string) []SessionIdentity

SessionIdentities reads the agent's current identity and remembered identities. Callers must match the IDs recorded in a session; presence alone is not evidence that the account served that session's requests.

type ShareError added in v0.1.1181

type ShareError struct {
	Why    string
	Format int
	Models []string
	Err    error
}

ShareError is why a text can't be imported as a group, by Why, for the GUI to say in the reader's language: "not_shared" (no group shared from magpie), "newer" (a format past ShareVersion, in Format), "no_format", "unreadable" (Err), "none_here" (none of its models here, in Models).

func (*ShareError) Error added in v0.1.1181

func (e *ShareError) Error() string

func (*ShareError) Unwrap added in v0.1.1181

func (e *ShareError) Unwrap() error

type SharedGroup added in v0.1.1181

type SharedGroup struct {
	Magpie  string `json:"magpie"`
	Version int    `json:"version"`
	Group   Group  `json:"group"`
}

SharedGroup is the text a group is shared as.

func ReadShared added in v0.1.1181

func ReadShared(text string) (SharedGroup, error)

ReadShared reads a shared group's text, as copied or pasted from a chat: the object may have words or a code fence around it.

type SignInAlert added in v0.1.3309

type SignInAlert struct {
	Provider string // the provider's id: the row a click opens
	Name     string
	User     string
	Kind     string
	EndsAt   *time.Time
}

SignInAlert is a sign-in to tell the user of. Kind is "lapsed" for an account that has to be signed in again, "ending" for one whose sign-in ends at EndsAt.

func SignInAlertsAt

func SignInAlertsAt(path string) []SignInAlert

SignInAlertsAt is one look at the accounts: the sign-in alerts due, as WatchSignIns tells them, with what was told kept in path.

type SignInMoves

type SignInMoves struct {
	// Mode: "kept" (stays on one account, KeepLogin / KeepLoginAs),
	// "gateway" (Claude Code sends its requests to magpie's gateway,
	// which moves each to an account with room, its sign-in left
	// where the user put it), "off" (the subscription is off or hidden:
	// magpie leaves the sign-in alone) or "moves" (moved on once spent).
	Mode string `json:"mode"`
	// Share: the share of a window at which the account it is on counts
	// spent and is moved off (SpentShareOf); 100 is used up. Only "moves".
	Share float64 `json:"share,omitempty"`
	// Back: once the account moved off has room again, the agent is
	// signed back in to it (returnsToFirst). Only "moves".
	Back bool `json:"back,omitempty"`
	// Routed: kept, but Claude Code goes through the gateway, so turning
	// the switch on moves requests, not its sign-in (mode "gateway"
	// then). Only "kept".
	Routed bool `json:"routed,omitempty"`
}

SignInMoves is how magpie moves an agent's own sign-in between its accounts, as NextLogin decides it, for the Providers page to say beside the accounts: a user who left a "keep signed in" tick on, or whose Claude Code went through the gateway, saw no switch and had no way to tell why (the owner, 11-11).

func SignInMovesOf

func SignInMovesOf(agent string) *SignInMoves

SignInMovesOf is SignInMoves for agent; nil for one whose sign-in magpie never moves.

type SignInOptions added in v0.1.1200

type SignInOptions struct {
	Site string // where to sign in, for one with more than one (StartSignInAt)
	// Proxy is the one to sign in through, as netproxy.With takes it ("" the
	// global one, "direct" none, or its address); nil for the one the
	// account's requests would go through. Picked, it is kept as the
	// account's own once the sign-in is done.
	Proxy *string
	// User is the account signed in to again, for the proxy it goes through
	User string
}

SignInOptions are a sign-in's choices beyond its subscription.

type SignInPlan added in v0.1.2835

type SignInPlan struct {
	// contains filtered or unexported fields
}

SignInPlan is what a sync puts in and takes away here (MergeSignIns), made over the sign-ins it read here: a sign-in changed here since is left alone.

func (SignInPlan) Count

func (p SignInPlan) Count() int

Count is how many sign-ins the plan puts in or removes.

func (SignInPlan) Empty added in v0.1.2835

func (p SignInPlan) Empty() bool

Empty says the plan changes nothing.

type SignInState added in v0.1.14

type SignInState struct {
	ID            string `json:"id"`
	Agent         string `json:"agent"`
	URL           string `json:"url"`                     // the vendor's page, to open or copy
	Code          string `json:"code,omitempty"`          // what to type there, for a device code
	State         string `json:"state"`                   // installing, waiting, done, failed or canceled
	PasteCallback bool   `json:"pasteCallback,omitempty"` // a callback URL can also finish this sign-in
	// PasteCode is a plugin's sign-in finished by the code its page shows
	PasteCode bool `json:"pasteCode,omitempty"`
	// PasteKey is a sign-in an API key made on KeysURL also finishes
	// (Command Code's, whose page posts its key where a pasted address
	// can't carry it)
	PasteKey     bool   `json:"pasteKey,omitempty"`
	KeysURL      string `json:"keysURL,omitempty"`
	Instructions string `json:"instructions,omitempty"` // a plugin's words for its page
	// Opened is a page the plugin's own CLI opened already (Grok Build's
	// `grok login`), shown but not opened a second time
	Opened bool `json:"opened,omitempty"`
	// Installing is the CLI being installed before the sign-in can start
	Installing string `json:"installing,omitempty"`
	User       string `json:"user,omitempty"`  // the account, once done
	Plan       string `json:"plan,omitempty"`  //
	Using      bool   `json:"using,omitempty"` // the agent was signed in to it too
	// Again is an account listed already: its sign-in was renewed rather
	// than a new account added (#413)
	Again bool   `json:"again,omitempty"`
	Error string `json:"error,omitempty"`
	// CallbackBlocked says why the port the browser is sent back to
	// couldn't be opened: "reserved" (Windows keeps it for Hyper-V, WSL or
	// Docker) or "busy" (another program has it). The sign-in goes on
	// without it, finished by the address its page ends on, pasted (#1782).
	CallbackBlocked string `json:"callbackBlocked,omitempty"`
	CallbackPort    int    `json:"callbackPort,omitempty"`
	// Proxy is the one the sign-in goes through ("" the global one,
	// "direct" none): the one the account's requests will (#1663)
	Proxy string `json:"proxy,omitempty"`
}

SignInState is where a sign-in stands, for the window to show.

func SignInStatus added in v0.1.14

func SignInStatus(id string) (SignInState, bool)

SignInStatus reports on a sign-in StartSignIn began.

func StartPluginSignIn added in v0.1.479

func StartPluginSignIn(id string, method int, inputs map[string]string) (SignInState, error)

StartPluginSignIn begins signing in to a plugin's provider (OpenCode's id) with its OAuth method, the method's questions answered: the page to open, then either the plugin notices on its own or the code the page shows is pasted back (SubmitSignInCallback). SignInStatus follows it, as it does a built-in sign-in; its Agent is the provider's magpie id. The account goes beside those signed in already, or replaces the one it is. A built-in moved onto its plugin installs the CLI it runs through first, as the built-in's sign-in did.

func StartPluginSignInWith added in v0.1.1200

func StartPluginSignInWith(id string, method int, inputs map[string]string, o SignInOptions) (SignInState, error)

StartPluginSignInWith is StartPluginSignIn through the proxy o picks, else the one the provider's requests go through (#1663).

func StartSignIn added in v0.1.14

func StartSignIn(agent string) (SignInState, error)

StartSignIn begins adding an account to an agent: open the returned URL in a browser and the rest happens on its own; SignInStatus follows it.

An agent signed in with a CLI that isn't installed has it installed first: the sign-in is then "installing", and gets its URL when that is done.

func StartSignInAt added in v0.1.425

func StartSignInAt(agent, site string) (SignInState, error)

StartSignInAt is StartSignIn on one of the sites an agent signs in on: ZCode's "zai" (the default) or "bigmodel".

func StartSignInWith added in v0.1.1200

func StartSignInWith(agent string, o SignInOptions) (SignInState, error)

StartSignInWith is StartSignIn with the sign-in's choices: its site and the proxy it goes through.

func WaitSignIn added in v0.1.14

func WaitSignIn(ctx context.Context, id string) (SignInState, error)

WaitSignIn blocks until a sign-in is over, for the command line.

type SignIns added in v0.1.2835

type SignIns struct {
	// Logins are the subscription accounts magpie keeps, with their
	// credentials: logins.json's records as written there.
	Logins []savedLogin `json:"logins,omitempty"`
	// Plugins are the plugins' sign-ins by key, plugin-auth.json's.
	Plugins map[string]json.RawMessage `json:"plugins,omitempty"`
	// Codex is the record (SignInID) of the account Codex was signed in to
	// where these were collected: put back where Codex is signed out.
	Codex string `json:"codex,omitempty"`
}

SignIns are the sign-ins a backup carries.

func CollectSignIns added in v0.1.2835

func CollectSignIns() (*SignIns, error)

CollectSignIns gathers the sign-ins to carry. Codex's own sign-in here is taken from its auth.json, fresher than magpie's copy of it. A file that can't be read is an error: carried as no sign-ins, a sync would take them away elsewhere.

func (*SignIns) Except

func (s *SignIns) Except(except []string) (kept, held *SignIns)

Except splits s by subscription: kept is s without the sign-ins of the subscriptions named in except (provider ids, a built-in's or its plugin's, either naming both), held is theirs alone. With none named, kept is s itself and held nil; a nil s gives nil for both.

func (*SignIns) Hashes added in v0.1.2835

func (s *SignIns) Hashes() map[string]string

Hashes are s's sign-ins as their ids and the hashes of their credentials: what a sync compares, never the credentials themselves.

func (*SignIns) With

func (s *SignIns) With(held *SignIns) *SignIns

With is s with held's sign-ins put back beside its own, as Except took them out: held's plugins and Codex only where s has none of its own.

type SignInsResult added in v0.1.2835

type SignInsResult struct {
	Added   int `json:"added,omitempty"`   // accounts that weren't here
	Updated int `json:"updated,omitempty"` // accounts here renewed later where they came from
	// Kept is the accounts left as they are here: renewed later here, the
	// agent's own sign-in, or more than one account here could be it.
	Kept int `json:"kept,omitempty"`
	// Codex: Codex was signed out here, and is signed in now.
	Codex bool `json:"codex,omitempty"`
}

SignInsResult says what putting sign-ins back did.

func ApplySignIns added in v0.1.2835

func ApplySignIns(p SignInPlan) (SignInsResult, error)

ApplySignIns does a plan here: under logins.json's lock, and plugin-auth.json's, each read afresh.

func RestoreSignIns added in v0.1.2835

func RestoreSignIns(s *SignIns) (SignInsResult, error)

RestoreSignIns puts a backup's sign-ins in: those not here are added, those here renewed later where the backup was made are updated, nothing is taken away, and Codex is signed in to its account when it is signed out here.

type SignedInError added in v0.1.1025

type SignedInError struct {
	Agent, User string
	Only        bool
}

SignedInError is ForgetLogin's refusal of the account an agent is signed in to now while it has another: that one is signed in to first (its Use), and this one removed then. Only is Claude Code's last account it can be signed in to, which magpie keeps rather than sign Claude Code out. The GUI says it in the reader's language (codes signed_in and signed_in_only).

func (*SignedInError) Error added in v0.1.1025

func (e *SignedInError) Error() string

type Spec added in v0.1.1360

type Spec struct {
	Context, Output, Vision, Reasoning SpecPart
	Entry                              Entry
}

Spec is a model's spec as magpie goes by it: the entry the gateway routes and the GUI and agents are shown, with where each part came from.

func SpecOf added in v0.1.1360

func SpecOf(ref string) (Spec, bool)

SpecOf is the spec of a model a provider serves, by "provider/model".

type SpecChange added in v0.1.1360

type SpecChange struct {
	// Context and Output are numbers of tokens; 0 takes the user's away.
	Context, Output *int
	// Vision is "on", "off", or "auto" for the vendor's list's answer.
	Vision *string
	// Reasoning is the levels the model offers: a range ("low-high"), a
	// list ("low,medium,high"), "off" for no reasoning ask at all, or
	// "auto" for the levels its list gives.
	Reasoning *string
}

SpecChange is what `magpie model spec` changes of one model. Each part left nil stays as it is.

func (SpecChange) Empty added in v0.1.1360

func (c SpecChange) Empty() bool

Empty is whether c changes nothing.

type SpecPart added in v0.1.1360

type SpecPart struct {
	Value string
	From  string
}

SpecPart is one part of a model's spec as it is in force: its value and where it came from — "model" for what the user set on it, "provider" for what they set on every model of its provider, "" for the vendor's list and models.dev.

type SpecRow added in v0.1.1360

type SpecRow struct {
	Key                                string
	Context, Output, Vision, Reasoning string
	// Gone: no provider of that id is there any more
	Gone bool
}

SpecRow is one model the user gave a spec, as `magpie model specs` lists it: each part as they set it, "" where they set none.

func ModelSpecs added in v0.1.1360

func ModelSpecs() []SpecRow

ModelSpecs are the models the user gave any part of a spec, by key.

type SpendCap added in v0.1.2819

type SpendCap struct {
	USD    float64 `json:"usd"`
	Period string  `json:"period"`
	// Since is when a cap in all was set, what it counts from; kept while
	// the cap stays one in all, its amount changed or not
	Since time.Time `json:"since,omitzero"`
}

SpendCap is a key's spend cap: USD over Period, which is SpendDay, SpendMonth or SpendTotal (in all, counted from Since).

func ParseSpendCap added in v0.1.2819

func ParseSpendCap(amount, period string) (*SpendCap, error)

ParseSpendCap reads a spend cap as the CLI takes it: an amount in USD ("20", "$20", "12.5") and its period (day, month or total, per day by default); off for none (nil).

func (SpendCap) Window added in v0.1.2819

func (c SpendCap) Window(now time.Time) (start, reset time.Time)

Window is the period c counts over at now: when it began and when the next begins, zero for a cap in all, which never renews.

type Stamp added in v0.1.1298

type Stamp struct {
	// contains filtered or unexported fields
}

Stamp marks what the catalog is built from, read without building it. Two equal stamps mean nothing magpie wrote or was told of came between them: no Changed (a provider, an account, a setting saved), no plugin's change, no catalog.Reset or Touched, no filememo.Forget, the same environment, and the providers', the settings' and the catalog's own files with the same time and size, as another process leaves them. What it can't see — another app rewriting an account's file, a model retired by its date — a caller that keeps what it built across stamps builds again now and then all the same.

func StampNow added in v0.1.1298

func StampNow() Stamp

StampNow is the Stamp as things are now.

type SubscriptionQuota

type SubscriptionQuota struct {
	Provider  string        `json:"provider"`
	Name      string        `json:"name"`
	Icon      string        `json:"icon"`
	Plan      string        `json:"plan,omitempty"`
	AccessSKU string        `json:"accessSku,omitempty"`
	User      string        `json:"user,omitempty"` // the account, so two of one vendor tell apart
	Windows   []QuotaWindow `json:"windows"`
	Balance   string        `json:"balance,omitempty"` // what is left on an API key, instead of windows
	// BalanceParts are the Balance's amounts each apart, when the balance
	// field the user wrote has several or a percent (cardParts)
	BalanceParts []BalancePart `json:"balanceParts,omitempty"`
	// BalanceSplit is what the Balance is made of, when the vendor tells
	// it: DeepSeek's granted credit and the money topped up, each a part
	// labelled SplitGranted or SplitTopUp
	BalanceSplit []BalancePart `json:"balanceSplit,omitempty"`
	// BalanceTrend is the Balance over time, as magpie read it, and when
	// it runs out at that pace (balance_history.go)
	BalanceTrend *BalanceTrend `json:"balanceTrend,omitempty"`
	// Estimate is set when the Balance is one the user typed less what
	// magpie priced the key's calls at since (key_balance_own.go), not a
	// vendor's reading
	Estimate *BalanceEstimate `json:"estimate,omitempty"`
	// SharedBalance is set on each key of a provider found to read one
	// account's balance with others (balance_shared.go): the name of the
	// first of them, whose card shows it once for all
	SharedBalance string `json:"sharedBalance,omitempty"`
	// Until is when the plan's paid time ends: it renews then when Renew
	// is "auto", is over when "off", and either when "" (the vendor
	// doesn't say which).
	Until *time.Time `json:"until,omitempty"`
	Renew string     `json:"renew,omitempty"`
	Error string     `json:"error,omitempty"`
	// PluginError is an Error a plugin's own usage read gave, in its own
	// words: magpie has no reading of it to say better, so the GUI shows
	// it on the card rather than only in a tooltip (aqiu817/magpie-sensenova#1).
	PluginError bool `json:"pluginError,omitempty"`
	// NeedsAccessKey is a plan read with the account's access key, which
	// its provider hasn't (accessKeyCard, #1821): the Usage page offers
	// the provider's settings to give it in.
	NeedsAccessKey bool `json:"needsAccessKey,omitempty"`
	// SeeAt is the vendor's page that shows what its API tells no key:
	// OpenCode Zen's credits, on its console (errOpenCodeNoBalance). The
	// Usage page offers to open it.
	SeeAt string `json:"seeAt,omitempty"`
	// AsOf is when an allowance shown in place of one that couldn't be
	// read was read (see keepLast); nil for a reading just made.
	AsOf *time.Time `json:"asOf,omitempty"`
	// ReadDeferred distinguishes a reading deliberately not requested from
	// a request that failed. AsOf and ReadAt still date the cached values.
	ReadDeferred bool `json:"readDeferred,omitempty"`
	// ReadError is why the reading AsOf stands in for failed, so a
	// stand-in that has lasted days says why (tmr11235 on X: agy-cli's
	// quota "as of" four days back, with no reason given).
	ReadError string `json:"readError,omitempty"`
	// ReadAt is when what is shown was read: a key's balance, kept a
	// minute (KeyBalances), or an account's allowance, which a cache (a
	// minute's, or a Claude account's until Claude Code tells it again)
	// can hand back long after; nil when not known.
	ReadAt *time.Time `json:"readAt,omitempty"`
	// Resets are the rate-limit resets a Codex account holds, nil when it
	// holds none (codex_resets.go).
	Resets *ResetCredits `json:"resets,omitempty"`
	// ResetsUsed are the Codex account's resets magpie spent, newest
	// first, by itself or by hand (codex_resets_used.go): what the card
	// says when one is gone and the user asks where
	ResetsUsed []ResetUse `json:"resetsUsed,omitempty"`
	// Held is set on a ChatGPT account the Codex app sends nothing for
	// now (codexHeld): not on a window at 100% alone, which credits get
	// past.
	Held bool `json:"held,omitempty"`
	// Daily is the account's credits used day by day, as magpie counted
	// them from its readings (credits_daily.go): its first credits
	// window's, and MoreDaily its other pools', each apart.
	Daily     *DailyCredits   `json:"daily,omitempty"`
	MoreDaily []*DailyCredits `json:"moreDaily,omitempty"`
	// Checkins is set on a WorkBuddy (China) or Trae CN account whose
	// daily check-in is pressed for, CheckinBy whose ("" WorkBuddy's,
	// "trae" Trae CN's), and Checkin is how its last one went, nil before
	// the first; never cached, added as the page asks (WithCheckins).
	Checkins  bool              `json:"checkins,omitempty"`
	CheckinBy string            `json:"checkinBy,omitempty"`
	Checkin   *WorkBuddyCheckin `json:"checkin,omitempty"`
	// CheckinOff is set on such an account the user left out of its
	// vendor's check-in (settings.CheckinOff, #1902): it isn't checked in.
	CheckinOff bool `json:"checkinOff,omitempty"`
	// CheckinKey is such an account's entry in its vendor's check-in, the
	// key Check in now presses it by (CheckInAccount).
	CheckinKey string `json:"checkinKey,omitempty"`
	// Kind is the card's kind as another magpie is told it (CachedCards):
	// subscription, plan or balance; "" here.
	Kind string `json:"kind,omitempty"`
	// From is the remote magpie a card is that one's (remote_quotas.go),
	// by its name here; "" for this computer's own.
	From string `json:"from,omitempty"`
	// Via is the magpies (catalog.Self) a card told another magpie
	// passed through, the one that read it first, this one last
	// (CachedCards): the receiver leaves out a card that comes back to
	// it (catalog.Loops). Only between magpies; nil here.
	Via []string `json:"via,omitempty"`
	// LastServedAt is when the account, plan or key last answered a
	// request through this computer's gateway, nil when it hasn't in the
	// last 30 days (served.go); set by Quotas, never cached.
	LastServedAt *time.Time `json:"lastServedAt,omitempty"`
	// Alias is the account's name of the user's own (AccountNames), else
	// Seat; Seat is the name of the key plan this account's card stands
	// in for (seatCards, #1515): the same GLM seat added both as a key
	// and as a signed-in account. Both "" when none; set as cards are
	// handed out, never cached.
	Alias string `json:"alias,omitempty"`
	Seat  string `json:"seat,omitempty"`
	// Named is set when Alias is the user's own name (AccountNames), not
	// the plugin's name for the account (PluginUserOf, a masked phone) or
	// Seat: the GUI's Hide accounts keeps the user's own name in sight
	// and hides the others as accounts (#3656).
	Named bool `json:"named,omitempty"`
	// GatewayKey is set on the card of a gateway key a remote magpie gave
	// this computer (#1547, remote_key_limits.go): the limit that magpie
	// holds the key to, beside the windows that show it.
	GatewayKey *GatewayKeyLimit `json:"gatewayKey,omitempty"`
	// Routing is, on a card told another magpie (RemoteCardsPath), what
	// each window's json leaves out for routing (Span, Model, Aside), in
	// the windows' order: that magpie weighs its Remote magpie by the card
	// (RemoteAllowance, #6708). Set only as cards are told; nil elsewhere.
	Routing []lastWindow `json:"routing,omitempty"`
	// contains filtered or unexported fields
}

SubscriptionQuota is provider-reported allowance usage. This is separate from Dial's local token log: vendors expose percentages, not token totals.

func Allotted added in v0.1.791

func Allotted(ctx context.Context) []SubscriptionQuota

Allotted is Quotas without the keys' balances: the accounts and plans whose allowance runs out and starts again, which is what magpie quota wait waits on; no key's balance is asked for.

func CachedCards added in v0.1.1078

func CachedCards(now time.Time) []SubscriptionQuota

CachedCards is the Usage page's cards as this magpie last read them, each with its kind, for another magpie to show: no vendor is asked, whatever their age. The cards a Remote magpie gave this one, as last read from it (passedOnCards), are passed on too, so a magpie that uses this one sees the accounts behind it as well (yuyong_id on Discord: a third magpie in a chain had none of the first's Codex cards). Each card carries the way it came by, this magpie last (Via).

The cards are the page's with what was read of the same accounts and keys behind it since (cards_kept.go): a magpie serving only other magpies has nobody on its page (#1313).

func InProviderOrder added in v0.1.1307

func InProviderOrder(qs []SubscriptionQuota) []SubscriptionQuota

InProviderOrder is qs in the order the user put the providers in on the Providers page (SetOrder), each provider's cards as they came; a card of no provider here (a remote magpie's) after them all. The window's Usage page and the tray panel's Allowances tab draw them so, where the user hasn't arranged the cards themselves (Zhenbao TONG on Discord: the providers moved in the window, the tray kept its own order).

func KeyBalances added in v0.1.37

func KeyBalances(ctx context.Context) []SubscriptionQuota

KeyBalances is the balance of every provider magpie can ask one of, the key in use and each other key it has on — or its account's, once, when it has a token for that — as cards beside the subscriptions' allowances. What was asked less than a minute ago is not asked again, unless the providers were saved since (ForgetBalances).

func OffCheckins

func OffCheckins() []SubscriptionQuota

OffCheckins are the accounts a daily check-in reaches whose provider the user switched off (wxkwxk666 on X: 禁用的供应商也要能签到). The Usage page leaves a switched-off provider's cards out (visibleQuotas), and the daily loop leaves it alone (leftAlone), so these are shown in a folded group of their own, each to be checked in by hand (CheckInAccount), which switches nothing back on.

Each is a card with no windows: the provider, its name and icon, the account, and its check-in, found by its own key. No allowance is read and nothing is asked; a provider whose account was removed from magpie (Hidden) is not listed.

func PlanQuotas added in v0.1.86

func PlanQuotas(ctx context.Context) []SubscriptionQuota

PlanQuotas is the windows of every plan magpie has a key for, each key on a card of its own when a provider has several. What was asked less than a minute ago is not asked again.

func QuotaRowsShown

QuotaRowsShown is q less the rows the Overview hides, by provider and the row's group (a pool's or family's name, else the window's), unless that would leave it with none.

func Quotas added in v0.1.114

func Quotas(ctx context.Context) []SubscriptionQuota

Quotas is what is left everywhere magpie can ask: the signed-in subscriptions' windows, the plans bought with a key, and the keys' balances, as the Usage page shows them. The vendors are asked at once; what doesn't answer before ctx ends comes back with an error.

func RemoteCards added in v0.1.1078

func RemoteCards(ctx context.Context) []SubscriptionQuota

RemoteCards is every remote magpie's cards, named for this computer.

func ShownQuotas

ShownQuotas is qs less the cards hidden (s.UsageCardsHidden) and the rows hidden (s.UsageWindowsHidden), as the Overview draws them.

func SubscriptionUsage

func SubscriptionUsage(ctx context.Context) []SubscriptionQuota

SubscriptionUsage returns rolling quotas for signed-in first-party agents. Results are cached because these private account endpoints are aggressively rate limited when several CLI sessions are active. Once there is something cached it comes back at once, and a stale copy is refreshed in the background; only the very first call waits, for as long as ctx allows.

func ToldRouting

func ToldRouting(cs []SubscriptionQuota) []SubscriptionQuota

ToldRouting is cs, each card with its windows' Routing, for another magpie: the gateway's answer of RemoteCardsPath.

func WithCheckins added in v0.1.773

func WithCheckins(qs []SubscriptionQuota) []SubscriptionQuota

WithCheckins is qs with each WorkBuddy (China) account's card told it is checked in each day and how its last check-in went, for the Usage page to say on the card (#694: having to look in Settings to know whether it checked in is wrong). It holds for a moved account too: magpie checks those in through the plugin's fetch. qs, which may be the usage cache, is left as it is; nothing is asked.

func WithHeldWindows added in v0.1.2640

func WithHeldWindows(qs []SubscriptionQuota, now time.Time) []SubscriptionQuota

WithHeldWindows is qs with HeldBy set on each window whose remainder an account can't spend: another of its windows that stops it for every model (usedPast's rule: not aside, no model of its own, not past its reset) is used up and starts again only after this one does, so what this one has left is lost at its own reset, unspent. An account with 0% of its 7 days left and 100% of its 5 hours has no 5 hours to spend, and the Usage page's all-accounts strip, the tray panel's and the Routing groups' (mergeQuotas) count it as none left rather than as a full window (hayden4608, handong66: three such accounts and one with its 5 hours used up read 75% of 5 hours left in all, #4791). It isn't so the other way: a week with 22% left behind five hours used up still has that 22% once the five hours start again. A ChatGPT account that goes on on its credits isn't held. Another magpie's cards are as it sent them; qs and its windows, which the caches share, are left as they were.

func WithImageLane

func WithImageLane(qs []SubscriptionQuota, now time.Time) []SubscriptionQuota

WithImageLane is qs with a row for the image allowance added to each ChatGPT account's card that was read: Text and Aside, so no share is told and routing never reads it, with ResetsAt when a refusal or a reply's headers named the time it comes back and no time otherwise. A card of another magpie is as it came; qs and its windows, which the caches share, are left as they were.

func WithWindowStarts added in v0.1.1232

func WithWindowStarts(qs []SubscriptionQuota, now time.Time) []SubscriptionQuota

WithWindowStarts is qs with each window's StartsAt set where its bounds are known, for the GUI's Pace number; qs and its windows, which the caches share, are left as they were.

type Template added in v0.1.1163

type Template struct {
	Kind string `json:"kind"`
	// Group is the group it makes, not saved: no Members when it can't be
	// made of the models there are, Why saying what is missing
	Group Group  `json:"group"`
	Why   string `json:"why,omitempty"`
	// Need is what is missing, for the GUI to say in the user's language:
	// NeedProvider, NeedProviders (Of the only one) or NeedCheap (Of the
	// strong model)
	Need string `json:"need,omitempty"`
	Of   string `json:"of,omitempty"`
}

Template is one template as the user's models make it now.

func MakeTemplate added in v0.1.1163

func MakeTemplate(kind string) (Template, error)

MakeTemplate is the template kind as the user's models make it now, or why it can't be made.

func Templates added in v0.1.1163

func Templates() []Template

Templates are every template as the user's models make it now.

type TestPick

type TestPick struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

TestPick is one account or key a test can be pinned to.

type TimeWindow added in v0.1.570

type TimeWindow struct {
	From string   `json:"from"`
	To   string   `json:"to"`
	Days []string `json:"days,omitempty"`
	// Zone: the IANA time zone the hours and days were set in
	// ("Asia/Shanghai"): the browser's on the Routing page, the terminal's
	// for magpie group rule. magpie on a server in UTC keeps a Beijing
	// user's 09:00–18:00 at Beijing's 09:00 (gaubeebangeel on X). A window
	// with none — every one set before zones were kept — is on this
	// computer's clock, as it was.
	Zone string `json:"zone,omitempty"`
}

TimeWindow is hours of the day: From until To, "HH:MM" each, past midnight when To comes before From (22:00–08:00), the whole day when they are the same. Days, when set, are the days it holds on ("mon" … "sun"); a window past midnight is of the day it begins on, so Friday's 22:00–08:00 takes Saturday's early hours too.

func ParseTimeWindow added in v0.1.570

func ParseTimeWindow(v string) (*TimeWindow, error)

ParseTimeWindow reads hours of the day: 09:00-18:00, 22:00-08:00, and the time zone they are in after an @: 09:00-18:00@Asia/Shanghai.

func (TimeWindow) DaysText added in v0.1.570

func (w TimeWindow) DaysText() string

DaysText is the window's days for a list: "Mon–Fri", "Sat,Sun", "Mon,Wed–Fri"; "" for every day.

func (TimeWindow) Holds added in v0.1.570

func (w TimeWindow) Holds(at time.Time) bool

Holds reports whether at is within the window, in its zone. A zone this magpie doesn't know (a file edited by hand; saving refuses one) is an unknown clock, and the window doesn't hold: the rule is as if it weren't there, rather than at hours that may be a day's half off.

func (TimeWindow) Text added in v0.1.570

func (w TimeWindow) Text() string

Text is the window as a rule's conditions show it: "09:00–18:00 Mon–Fri", its zone after it when it has one: "09:00–18:00 (Asia/Shanghai)".

type UnservedGroup

type UnservedGroup struct {
	Ref   string   // group/<id>, as agents are given it
	Name  string   // as the user named it
	Icons []string // its members' providers' icons, each once
	// Why is one of the Why… words, "" for a group the agent's lists
	// offer
	Why string
}

UnservedGroup is a routing group of the user's that an agent's lists may not offer, and why: its picker shows one it lacks all the same, so that a group is never gone from it without a word (@CHENGJIAHEGOXIS on X: DeepSeek-API-Agents, on on the Routing page, was in no section of Codex's picker).

func UnservedGroups

func UnservedGroups(agent string) []UnservedGroup

UnservedGroups are the user's own routing groups, in the Routing page's order, each with why agent's lists (CatalogFor) leave it out, "" for one they offer. A group magpie found is left out of these, as is one the user removed, one that answers System One alone (DecisionGroup), and every group while the user's groups aren't served (Groups has none then).

func (UnservedGroup) Pickable

func (u UnservedGroup) Pickable() bool

Pickable reports whether the gateway serves the group, which only the agent's own lists leave out: picked, it is put back in them (ShowFor).

type Vertex added in v0.1.1162

type Vertex struct {
	// Project is the Google Cloud project's id: requests are made, and
	// billed, there.
	Project string `json:"project,omitempty"`
	// Location is global, us, eu or a region (us-central1); each serves
	// models of its own (vertexModels).
	Location string `json:"location,omitempty"`
	// Credentials is a credentials file; "" finds them as Google's
	// libraries do (vertexCredentialsFile).
	Credentials string `json:"credentials,omitempty"`
	// Impersonate is the email of a service account the credentials are
	// traded for, "" to ask as their own account.
	Impersonate string `json:"impersonate,omitempty"`
	// BaseURL is the root a provider with an API key asks at in place of
	// Google's (a proxy, or a gateway that answers as Vertex AI does), with
	// no /v1 after it. Only with a key: the Google token goes nowhere but
	// Google's own address.
	BaseURL string `json:"baseUrl,omitempty"`
}

Vertex is where a Vertex AI provider's requests go, and whose credentials sign them.

func (*Vertex) Normal added in v0.1.1162

func (v *Vertex) Normal() *Vertex

Normal is v as it is kept: trimmed, at global when no location is given, nil when nothing is. The app's Refresh and Test ask with the values typed spelled so.

type WarmAllResult

type WarmAllResult struct {
	User string `json:"user"`
	Skip string `json:"skip,omitempty"`
	Err  string `json:"error,omitempty"`
}

WarmAllResult is what Warm up all came to for one account: Skip says why it was left alone ("off" or "running"), Err why its warm-up failed or couldn't be sent; both empty, it was warmed.

func WarmAll

func WarmAll(ctx context.Context, agent string) ([]WarmAllResult, error)

WarmAll is Warm up now for each of agent's accounts at once (CoderMaurice on X: one press for several Claude accounts). It sends the warm-up to every account in use (the one the agent is on, or one turned on beside it) whose windows aren't all running already, as the cached reads the Usage page shares tell them. An account turned off or paused, and one already in its windows, are left alone and listed with why; one whose sign-in lapsed is sent nothing and failed, as Warm up now has it.

type WindowCaps added in v0.1.1134

type WindowCaps struct {
	All     int
	Windows map[string]int
	// Amounts are the windows capped at a fixed amount of their own unit
	// instead, by WindowCapID (AccountWindowAmounts)
	Amounts map[string]float64
	Credits bool
}

WindowCaps is what holds an account at a share of its windows: its usage cap for every window (All), the share of each window the user set one on (Windows, by WindowCapID; 100 is none on that window), and Credits for a Codex account set not to spend its credits, which holds any window with no cap at the vendor's own 100%.

func AccountCapsOf added in v0.1.1134

func AccountCapsOf(id, user string) WindowCaps

AccountCapsOf is CapsOf of the provider id.

func HoldCaps added in v0.1.1134

func HoldCaps(p Provider, agent, user string) WindowCaps

HoldCaps is the shares of its windows at which routing holds the account user of p, of agent, as used up: its usage cap and its windows' own (account_caps.go), and for a Codex account set not to spend its credits, or a Claude account set not to spend extra usage (claude_extra.go), 100% of any window with no cap. Holds() is false when nothing holds it before the vendor does.

func (WindowCaps) Holds added in v0.1.1134

func (c WindowCaps) Holds() bool

Holds says whether any window can hold the account before the vendor does.

func (WindowCaps) Of added in v0.1.1134

func (c WindowCaps) Of(name string) (share int, credits bool)

Of is the share at which the window named name holds the account, 0 for none, and whether it is the credits that hold it there.

type WindowHolds added in v0.1.1120

type WindowHolds struct {
	Tokens   int64   `json:"tokens"`
	Cost     float64 `json:"cost,omitempty"`
	BaseCost float64 `json:"baseCost,omitempty"`
	Priced   bool    `json:"priced"`
	Used     float64 `json:"used"`
	Routed   struct {
		Calls      int     `json:"calls"`
		Tokens     int64   `json:"tokens"`
		CacheRead  int64   `json:"cacheRead,omitempty"`
		CacheWrite int64   `json:"cacheWrite,omitempty"`
		Cost       float64 `json:"cost,omitempty"`
		BaseCost   float64 `json:"baseCost,omitempty"`
	} `json:"routed"`
	Since time.Time `json:"since"`
	// PrevAt is set when this is the last window's whole, carried over a
	// reset until the new window has enough data (Musikrv77852 on X): the
	// time that figure was last reckoned. Since is then that window's start.
	PrevAt *time.Time `json:"prevAt,omitempty"`
}

WindowHolds is a window's whole allowance reckoned from magpie's own calls: Tokens of input and output (cache traffic aside, as the Usage page counts tokens unless its pick is With cache, when the card adds Routed's cache over Used itself) and, when every call's model has an API list price, Cost at those prices (cache reads and writes at the vendor's own rates). Routed is what magpie routed through the account in the window so far, up to when the share was read, and Used that share. A call made with the account outside magpie is in Used but not in Routed, so the estimate is then lower than the window really holds.

BaseCost is Cost with every call at its model's base rates, no API long-context premium (catalog.Price.Tiers) (#5861, NorethSea): a plan's own use has none (OpenAI bills no long-context surcharge in Codex), so two cycles whose calls' sizes differ compare by it. It is there only when some call was over a tier's size, else it is Cost.

type WorkBuddyCheckin added in v0.1.356

type WorkBuddyCheckin struct {
	User    string    `json:"user,omitempty"` // as listed now; never kept
	Day     string    `json:"day"`
	At      time.Time `json:"at"`
	Outcome string    `json:"outcome"`
	Credit  float64   `json:"credit,omitempty"`
	Streak  int       `json:"streak,omitempty"`
	Msg     string    `json:"msg,omitempty"`
	// ValidUntil is a campaign's end, or when a plugin said its vendor's
	// day turns (auth.checkin's until), when the answer must be checked
	// again, even if the Beijing day hasn't changed; on a failure, the
	// time before which it isn't asked again (heldUntil).
	ValidUntil time.Time `json:"until,omitzero"`
	// Offline is a failure that never reached WorkBuddy, and Tries how
	// many before it the same day did the same.
	Offline bool `json:"offline,omitempty"`
	Tries   int  `json:"tries,omitempty"`
	// By is the vendor whose check-in it is: "" WorkBuddy's, "trae"
	// Trae CN's; never kept.
	By string `json:"by,omitempty"`
	// Vendor is a plugin's provider by name, for a check-in By
	// "plugin:<id>"; never kept.
	Vendor string `json:"vendor,omitempty"`
	// Asked is true of one checked in on this run, not one read back;
	// sent so a press can tell a claim now from one earlier today.
	// Never kept: the file is written before it is set.
	Asked bool `json:"asked,omitempty"`
	// Claimed is when magpie last saw the account's credits claimed,
	// carried over while later answers that day say done: a done after
	// magpie's own claim is the day's, one before it may be yesterday's
	// (#3326).
	Claimed time.Time `json:"claimed,omitzero"`
	// Again says the answer is provisional (provisional): magpie asks
	// the vendor again later that day. Worked out when shown, never
	// kept.
	Again bool `json:"again,omitempty"`
}

WorkBuddyCheckin is what came of a WorkBuddy account's check-in on Day (Beijing): the credits it gave and the streak it made, or why none.

func CheckInAccount added in v0.1.2649

func CheckInAccount(ctx context.Context, by, key string) []WorkBuddyCheckin

CheckInAccount checks one account in for today now, as a press of Check in now does for its vendor's (CheckinAccount's By and Key): asked again unless claimed today, even while left out of the daily check-in, and no switch changed (xiaowu_95660: 手动签到一次). It says how the account stands, or nothing for an account no check-in reaches.

func CheckInMiniMax added in v0.1.910

func CheckInMiniMax(ctx context.Context) []WorkBuddyCheckin

CheckInMiniMax checks each MiniMax Code account in use in for today now, those not in yet, and says how each stands.

func CheckInPlugins added in v0.1.1085

func CheckInPlugins(ctx context.Context, ids ...string) []WorkBuddyCheckin

CheckInPlugins checks the accounts of each plugin that checks in in for today now, those not in yet; with ids, only those providers'. It says how each stands.

func CheckInQoder added in v0.1.1077

func CheckInQoder(ctx context.Context) []WorkBuddyCheckin

CheckInQoder checks each Qoder account in use in for today now, those not in yet, and says how each stands.

func CheckInTrae added in v0.1.784

func CheckInTrae(ctx context.Context) []WorkBuddyCheckin

CheckInTrae checks each Trae CN account in use in for today now, those not in yet, and says how each stands.

func CheckInWorkBuddy added in v0.1.356

func CheckInWorkBuddy(ctx context.Context) []WorkBuddyCheckin

CheckInWorkBuddy checks each WorkBuddy (China) account in use in for today now, those not in yet, and says how each stands.

func MiniMaxCheckins added in v0.1.910

func MiniMaxCheckins() []WorkBuddyCheckin

MiniMaxCheckins is each MiniMax Code account's last check-in, as kept, by its name now; asks nothing.

func QoderCheckins added in v0.1.1077

func QoderCheckins() []WorkBuddyCheckin

QoderCheckins is each Qoder account's last check-in, as kept, by its name now; asks nothing.

func TraeCheckins added in v0.1.784

func TraeCheckins() []WorkBuddyCheckin

TraeCheckins is each Trae CN account's last check-in, as kept, by its name now; asks nothing.

func WorkBuddyCheckins added in v0.1.356

func WorkBuddyCheckins() []WorkBuddyCheckin

WorkBuddyCheckins is each WorkBuddy (China) account's last check-in, as kept, by its name now; asks nothing.

func (WorkBuddyCheckin) Checked added in v0.1.356

func (r WorkBuddyCheckin) Checked() bool

Checked says whether the day's credits are in, claimed now or before.

type ZhipuTeam added in v0.1.431

type ZhipuTeam struct {
	Org     string `json:"org,omitempty"`
	Project string `json:"project,omitempty"`
}

ZhipuTeam is the team a Zhipu or Z.ai key's GLM Coding Plan belongs to: its organization and project IDs, as the BigModel console shows them.

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL