access

package
v0.1.5010 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 29 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 access keeps the named API keys issued by the gateway.

Index

Constants

View Source
const (
	RedactOn  = "on"
	RedactOff = "off"
)

A key's Redact.

View Source
const (
	AdminLocal = "local"
	AdminAny   = "any"
)

The levels of Key.Admin.

View Source
const (
	MinTTL = time.Minute
	MaxTTL = 30 * 24 * time.Hour
)

MinTTL and MaxTTL bound how long an issued key lives.

View Source
const (
	// ReachAll: the key is held to no model, so it may use every
	// provider, those added later too.
	ReachAll = "all"
	// ReachWhole: every model of the provider, "<provider>/*".
	ReachWhole = "whole"
	// ReachSome: some of its models, each named.
	ReachSome = "some"
	// ReachNone: none of them by name; Via says which patterns of the
	// key's may still name some.
	ReachNone = ""
)

How far a key reaches one provider (ProviderKey.Reach).

View Source
const ExcludeMark = "!"

ExcludeMark starts an entry's account to keep the key off it: "<provider>/!<ref>" (LeiWang_2000 on X). A magpie older than the mark reads it as an account no provider has, which holds the key to none of that provider's: it fails closed.

View Source
const GroupMark = "@"

GroupMark starts an entry of a key's account list that names an account group by its id: "@<id>", or "!@<id>" (ExcludeMark) to keep the group's accounts out. A magpie older than the mark reads it as an entry naming no provider, a key that names no model holding it to no model (HeldModels): it fails closed.

View Source
const JoinMinLen = 8

JoinMinLen is the fewest characters a join password may have.

View Source
const MaxAliases = 200

MaxAliases is the most model names a key may give.

View Source
const MaxDays = 3650

MaxDays is the longest "days" cycle, ten years.

View Source
const MaxHours = 8760

MaxHours is the longest "hours" cycle, a year; a longer one is a "days" cycle.

View Source
const MaxKeyConcurrency = 1000

MaxKeyConcurrency is the most MaxConcurrency a key may have, as a provider's.

View Source
const MaxLimitModels = 50

MaxLimitModels is how many models one limit can count.

View Source
const MaxLimits = 5

MaxLimits is how many limits one key can have (#2227).

View Source
const NoMCP = "-"

NoMCP is the list of a key held to no MCP server at all.

View Source
const NoModels = "-"

NoModels is the model list of a key held to no model at all, one for MCP servers only (ifitscolorful on X: an MCP gateway's key that can't spend the subscriptions), as NoMCP is the MCP list of one for models only. It matches no model, so every check of a key's models refuses it, and the gateway refuses it every model route besides (keySurfaceGuard). A magpie from before it reads it as a model no provider has, so the key still reaches none.

View Source
const PatternPrefix = "re:"

PatternPrefix starts a model entry that is a regular expression (tsingchao on X): "re:^gpt-5" holds a key to every model whose id has that match. Go's RE2 syntax, letter case aside, unanchored (write ^ and $ to anchor), tried on the whole id "<provider>/<model>" and on the model alone, so "re:^gpt-" names GPT models of any provider. It never names a routing group ("group/<name>" does that), so a pattern like "re:.*" doesn't hand a key every group of the user's own.

View Source
const Prefix = "sk-magpie-key-"
View Source
const RoutingSmart = "smart"

RoutingSmart is a key's Routing for Smart: a group's own routing "" is Smart, and a key's "" follows the group.

Variables

View Source
var ErrNoKey = errors.New("Key not found")

ErrNoKey: there is no gateway key with that id.

View Source
var LANChanged = func() {}

LANChanged is called after sharing is turned on or off, or its key made anew: what was given the key goes on with the one there is now (the library's MCP servers relayed to an agent in a WSL distro under NAT).

View Source
var Now = time.Now

Now is when Update sets or resets a limit. A variable for the tests.

View Source
var Periods = []string{"day", "week", "month", "days", "hours", "account", "total"}

Periods are the windows a limit can be set for.

"account" follows one subscription account's window (Account, AccountWindow): it starts and resets when that window does, as the account's last reading tells. "total" never resets by the calendar: it counts from when it was set, or last reset, and only a reset starts it again.

Functions

func AccountsShown

func AccountsShown(names map[string]string, accounts []string) string

AccountsShown is a key's accounts as words say them: those it may use by names[entry] (provider.AccountNames), else the entry itself, and those it keeps out as "every account but …" (LeiWang_2000 on X).

func CleanAccounts added in v0.1.1076

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

CleanAccounts is a key's account list as kept (#905): each entry "<provider>/<account>", an account named by its stable id — or by the name it is shown by, resolved to that id, so the command line reads while the list keeps what a rename doesn't move — and a key by its fingerprint; trimmed, told apart in lower case as accounts are, each once, in the order given. Every account the entry names must be one its provider has now, so a typo can't quietly hold a key to nothing; one gone later — a key rotated, an account signed out — is kept as it is, matching nothing.

An entry "<provider>/!<account>" keeps that account out instead (LeiWang_2000 on X): the key may use every other account, those signed in later too. An account is never both kept out and named.

An entry "@<group>" uses an account group's accounts, and "!@<group>" keeps them out (AccountGroup, LeiWang_2000 on X): the group named by its id or name, kept by its id, so a group renamed or changed is the key's as it is then.

func CleanAdmin

func CleanAdmin(v string) (string, error)

CleanAdmin reads a management level: "" (off), AdminLocal or AdminAny.

func CleanAliases

func CleanAliases(in map[string]string) (map[string]string, error)

CleanAliases is a key's model names as kept: each name a key's client asks by, mapped to the model it is, "<provider>/<model>" or a routing group "group/<name>" (tsingchao on X). A name is one word of at most 120 characters that is no pattern.

func CleanMCP added in v0.1.3195

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

CleanMCP is a key's MCP list as it is kept: each entry trimmed and checked, told apart in no other way than as written, a tool dropped whose server is listed whole, and NoMCP dropped beside any server.

func CleanModels added in v0.1.990

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

CleanModels is a key's model list as kept (#882): each pattern trimmed, empty and repeated ones dropped. A pattern names a provider and a model, "<provider>/<model>", every model of one, "<provider>/*", or a routing group, "group/<name>"; NoModels alone holds the key to none, and is dropped beside any model.

func CleanRedact

func CleanRedact(v string) (string, error)

CleanRedact is a key's masking setting as it is kept: "" to follow Settings › Privacy, RedactOn or RedactOff.

func CleanRouting

func CleanRouting(v string) (string, error)

CleanRouting is a key's group routing as it is kept: "" to follow the group, RoutingSmart, a built-in routing or a plugin's.

func CleanTier

func CleanTier(v string) (string, error)

CleanTier is a key's service tier as it is kept: "" to follow the request, settings.CodexTierStandard, "priority" or "ultrafast", read from the words people use for them too (normal, fast, ultra_fast).

func ConfigureLAN

func ConfigureLAN(on, rotate bool) error

ConfigureLAN starts sharing with a named key. Rotation preserves the key's identity, name and enabled state.

func Current added in v0.1.3178

func Current(who Identity) bool

Current: who, a key Check took earlier, is still one it takes now, by the same secret: not turned off, removed, expired, rotated, nor bounded by an issuer that no longer lets it in. A connection a key opened (Magpie Browser's WebSocket) is closed once it isn't. false for no key, and when the store can't be read.

func Default added in v0.1.1280

func Default(secret string) bool

Default says secret is the sharing key magpie itself made (the default key ConfigureLAN keeps), whether sharing is on now or not: magpie's own, never one the user brought, so a write that keeps "a caller key of the gateway's own the user put there" must not keep it (#2545: with sharing off the key stays enabled in the store, Authenticate still took it, and Rekey could no longer bring gateway.Token back). An older magpie kept it in the settings alone; that value answers too, short of its revoked mirror.

func Excluded

func Excluded(a string) bool

Excluded says the entry keeps an account out, "<provider>/!<ref>".

func ExpandGroups

func ExpandGroups(accounts []string) []string

ExpandGroups is accounts with each account group put in its place, for what reads a key's list outside a request (the CLI's models, the GUI): groups that can't be read hold it to nothing.

func GroupNames

func GroupNames() map[string]string

GroupNames maps each group entry a key's list may hold, "@<id>", to its group's name, for words that say a key's accounts.

func GroupsPath

func GroupsPath() string

GroupsPath is where the account groups are kept.

func HeldModels added in v0.1.2094

func HeldModels(models, accounts []string) []string

HeldModels is the models a key that lists models and accounts may use. A key that names some accounts and no model may use only the models of those accounts' providers, "<provider>/*" each (Linka on Discord): in the Gateway page's "Models this key may use", ticking an account and no model narrows the key to that account, and never leaves it every model of every other provider, as it did when the accounts held only the providers they name (#905). A key that lists models is held to those, its accounts holding the providers they name, as before. An account kept out ("<provider>/!<ref>", LeiWang_2000 on X) holds the key to no model: a key that only keeps some out may use every model.

func IsGroupEntry

func IsGroupEntry(a string) bool

IsGroupEntry says the entry names an account group, "@<id>" or "!@<id>".

func IsPattern

func IsPattern(p string) bool

IsPattern says the entry is a regular expression (PatternPrefix).

func JoinOn

func JoinOn() bool

JoinOn: a join password is set, and readable.

func JoinPasswordOK

func JoinPasswordOK(pw string) bool

JoinPasswordOK: pw is the join password. None set, or a file that can't be read, lets no password in.

func JoinPath

func JoinPath() string

JoinPath is the file the join password's hash is kept in.

func JoinSince

func JoinSince() time.Time

JoinSince is when the join password was set; zero when none is.

func LANSecret added in v0.1.972

func LANSecret() string

LANSecret is the key magpie shares the gateway on the local network with (the default key ConfigureLAN made), for an agent of this computer's that reaches it from beyond loopback — one in a WSL distro under NAT, whose requests the gateway takes only with a named key; "" while the gateway isn't shared, or that key is off.

func Managed

func Managed(secret string) bool

func MigrateLegacyLANKey

func MigrateLegacyLANKey() error

MigrateLegacyLANKey makes the old Settings key a normal, revocable caller key. Keep LANKey for older Magpie versions; LANKeyID marks a completed migration so the retained credential cannot resurrect a removed key.

func MigrateLegacyLANKeyBestEffort

func MigrateLegacyLANKeyBestEffort()

func ModelAllowed added in v0.1.990

func ModelAllowed(patterns []string, id string) bool

ModelAllowed says id ("<provider>/<model>") matches one of patterns, letter case aside; a "*" in a pattern stands for any run of characters, slashes too, and "re:<expression>" is a regular expression (PatternPrefix). No patterns allow every model.

func MoveModel added in v0.1.2345

func MoveModel(from, to string) error

MoveModel gives every key's models that name from ("<provider>/<model>", letter case aside) to instead. A pattern ("relay/*") is the user's own and is left as written.

func Named added in v0.1.1100

func Named(secret string) bool

Named: secret has a named gateway key's form (sk-magpie-…), or is the key's own value a user gave it (Change.Secret), so a request from this computer with one is counted and limited as that key, as a sk-magpie- key is.

func On added in v0.1.2240

func On(id string) bool

On: the key with this id is one Authenticate takes, in the store and not turned off, or the legacy sharing key not yet written there; false when the store can't be read.

func Path

func Path() string

func ProveSecret added in v0.1.3177

func ProveSecret(id string) (string, bool)

ProveSecret is the enabled gateway key whose sha256 is id (hex), for a magpie's proof that it holds the key (provider.RemoteProvePath): one Authenticate takes, found by constant-time compares over every key, so which one matched, or whether any did, takes no different time. A key turned off, expired or whose issuer no longer lets it in, and a store that can't be read, have none.

func Prune added in v0.1.2334

func Prune() (int, error)

Prune removes the keys that expired over expiredKept ago and those issued under a key no longer in the store, and says how many.

func RemoveAccountGroup

func RemoveAccountGroup(id string) error

RemoveAccountGroup removes the group id. A group a gateway key names is not removed: a key held to it would be held to nothing, and one keeping it out would be let onto its accounts; the error names the keys.

func ReplaceAccount added in v0.1.1220

func ReplaceAccount(pid, was, now string) (int, error)

ReplaceAccount moves every key's account list from one of provider pid's keys to the fingerprint it has now (#1869: the key's value replaced in place), so a key held to it is held to it still. It returns how many keys it moved.

func Restore

func Restore(keys []Key) error

Restore replaces the gateway credentials when restoring their settings.

func RestoreGroups

func RestoreGroups(gs []AccountGroup) error

func RevokeIssued added in v0.1.2334

func RevokeIssued(id, by string) error

RevokeIssued removes the issued key id. by is the key asking: it may remove only a key issued under it; "" is the user, who may remove any issued key (a key of their own they remove with remove-key).

func ScopeBrowser added in v0.1.3178

func ScopeBrowser(id string) error

ScopeBrowser holds the key id to connecting the Magpie Browser extension alone (Key.Browser), read-only for a magpie from before that, and unable to issue keys. It is for the key a magpie from before the scope made for the extension (gui's browserKey), which could use every model and was written into a zip in Downloads: the extension goes on connecting with it, and the copy in the zip loses the rest. The sharing key, which magpie gives its own agents, is never scoped.

func SetJoinPassword

func SetJoinPassword(pw string) error

SetJoinPassword sets the join password, or with "" clears it, which closes the join page. Keys already given out stay until each is removed in Gateway keys.

func SetProviderKeys

func SetProviderKeys(pid string, add, remove, providers []string, groups []GroupRef) error

SetProviderKeys lets the keys add use provider pid and the keys remove use it no longer, writing each key's Models as its own models picker would, and nothing else of it:

  • add, to a key held to some models: "<pid>/*" joins them; to a key held to some accounts' providers alone, those providers' "/*" and "<pid>/*" become its models, so it keeps every one it had; a key that reaches pid already is left as it is (some of its models stay some, never made every one).
  • remove: the key's entries of pid's own go; one held to accounts alone keeps its other providers. A key that may use every model (ReachAll) is held to every other provider of providers, the ids there are now, "<id>/*" each, and the user's routing groups none of whose members may be pid's, "group/<id>" each (justforlxz on X: a key on every model, as most are, couldn't be unticked at all, so the list did nothing); a provider or group added later is not among them. A group magpie found is the key's when it may use every member. An entry of the key's that names groups, one that reaches pid among them, keeps those that don't: a key that names a group goes to every member of it. A key that would be left no model (Only, or groups alone, none kept) is refused, never let off to all.

Either every change is made or none is.

func Update

func Update(action string, in Change) (string, error)

Update writes the named key store atomically.

func Window added in v0.1.675

func Window(period string, now time.Time) (start, reset time.Time)

Window is the calendar window of period that now is in, in now's location: its start and when the next begins.

func WithIdentity

func WithIdentity(ctx context.Context, who Identity) context.Context

Types

type AccountGroup

type AccountGroup struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Accounts are "<provider>/<ref>", as a key's list keeps them
	// (CleanAccounts): an account by its stable id, a key by its
	// fingerprint. One signed out since stays, matching nothing.
	Accounts []string `json:"accounts"`
}

AccountGroup is a named set of accounts and keys, of any providers (LeiWang_2000 on X): a gateway key's list names it as "@<id>" to use its accounts, or "!@<id>" to keep them out, instead of each account one by one. A key reads the group as it is when a request comes, so changing a group's accounts changes every key that names it.

func AccountGroups

func AccountGroups() ([]AccountGroup, error)

AccountGroups are the account groups, in the order they were made.

func ExportGroups

func ExportGroups() ([]AccountGroup, error)

ExportGroups are the account groups for a backup; RestoreGroups puts a backup's back.

func FindAccountGroup

func FindAccountGroup(ref string) (AccountGroup, error)

FindAccountGroup is the group ref names, by its id or name, in any case.

func SaveAccountGroup

func SaveAccountGroup(g AccountGroup) (AccountGroup, error)

SaveAccountGroup adds g (no ID) or changes the group with g's ID: its name and accounts. A name is 1 to 80 characters and no other group's; each account is one a provider has now, as a key's (CleanAccounts), except one the group had already, kept though signed out since. A group holds accounts only, never another group or an account kept out.

type Change

type Change struct {
	Key  string `json:"key"`
	Name string `json:"name"`
	// Limit is what "limit-key" sets; nil or Unlimited takes the limit off.
	Limit *Limit `json:"limit,omitempty"`
	// Index is which of the key's limits "limit-key" sets and
	// "reset-limit-key" resets (#2227), counted from 0: one past the last
	// adds a limit, a nil Limit there removes that one. Without it,
	// "limit-key" makes Limit the key's only limit, and "reset-limit-key"
	// resets every one. For "move-key" it is the place in the list the key
	// goes to, counted from 0.
	Index *int `json:"index,omitempty"`
	// Models is what "models-key" sets; none lets the key use every model,
	// NoModels alone none.
	Models []string `json:"models,omitempty"`
	// Aliases is what "aliases-key" sets; none takes the names away.
	Aliases map[string]string `json:"aliases,omitempty"`
	// Accounts is what "accounts-key" sets (#905); none lets the key use
	// every account and key.
	Accounts []string `json:"accounts,omitempty"`
	// MCP is what "mcp-key" sets: none lets the key use every MCP server
	// and tool, NoMCP alone none of them.
	MCP []string `json:"mcp,omitempty"`
	// Quotas is what "quotas-key" sets (#2216).
	Quotas bool `json:"quotas,omitempty"`
	// ReadOnly is what "access-key" sets, and "add-key" gives the new key:
	// it may read stats and use no model (Key.ReadOnly).
	ReadOnly bool `json:"readOnly,omitempty"`
	// Browser is what "add-key" gives the new key: it may connect the
	// Magpie Browser extension alone (Key.Browser).
	Browser bool `json:"browser,omitempty"`
	// Admin is what "admin-key" sets (CleanAdmin's AdminLocal, AdminAny or "").
	Admin string `json:"admin,omitempty"`
	// Memory is what "memory-key" sets (Key.Memory).
	Memory bool `json:"memory,omitempty"`
	// Issues is what "issuer-key" sets: the key may issue short-lived
	// keys under itself (Key.Issues).
	Issues bool `json:"issues,omitempty"`
	// MaxConcurrency is what "concurrency-key" sets: how many requests
	// the key may have in flight at once, 0 for no limit.
	MaxConcurrency int `json:"maxConcurrency,omitempty"`
	// ServiceTier is what "tier-key" sets (Key.ServiceTier), "" to follow
	// the request.
	ServiceTier string `json:"serviceTier,omitempty"`
	// Redact is what "redact-key" sets (Key.Redact): "", "on" or "off".
	Redact string `json:"redact,omitempty"`
	// Routing is what "routing-key" sets (Key.Routing), "" to follow the
	// group's own.
	Routing string `json:"routing,omitempty"`
	// Secret is the value "add-key" gives the new key, one its clients
	// already send (love1sbug on X: keys handed out from another gateway),
	// or "rotate-key" gives the key; "" for one magpie makes.
	Secret string `json:"secret,omitempty"`
}

type GroupRef

type GroupRef struct {
	// Refs are the ids a key's models may name it by: "group/<id>", and
	// a found group's "auto/<model>".
	Refs []string
	// Found: a group magpie found (one model several providers serve). A
	// key held to some models may use one whose every member it may use
	// without naming it, so an unticked key needs no entry for it.
	Found bool
	// Reaches: a member of it may be the provider's, now or as its
	// patterns match later. A key that names the group is sent to every
	// member, whatever models it lists besides.
	Reaches bool
}

GroupRef is a routing group as a provider's side of the keys reads it.

type Identity

type Identity struct {
	KeyID, KeyName string
	Limit          *Limit
	More           []Limit
	Models         []string
	// Aliases are Key.Aliases; an issued key has none.
	Aliases map[string]string
	// AccountModels says Models are only HeldModels' "<provider>/*" of
	// a key that names accounts and no model, nor does the key it was
	// issued under: every model of those accounts' providers is the
	// key's, a routing group of them alone too. A key that lists models
	// is given a routing group of the user's only by naming it (kautism
	// on Discord).
	AccountModels bool
	Accounts      []string
	// MCP are the MCP servers and tools the key may use (Key.MCP); an
	// issued key is held to its issuer's too (Issuer.MCP)
	MCP      []string
	Quotas   bool
	ReadOnly bool
	// Browser: the key may connect the Magpie Browser extension and do
	// nothing else (Key.Browser).
	Browser bool
	// Admin is Key.Admin, "" for a key that can't have it (adminOf).
	Admin string
	// Memory is Key.Memory, false for a key that can't have it (memoryOf).
	Memory bool

	// Expires is when the key stops working, its issuer's expiry if
	// sooner; zero for never.
	Expires time.Time
	// Issuer is the key it was issued under: its limits hold this key's
	// requests too, and count what this key spends.
	Issuer *Identity
	// Issues: the key may issue keys under itself.
	Issues bool
	// MaxConcurrency is the key's own cap on requests in flight at once
	// (Key.MaxConcurrency), 0 for none; an issued key is held to its
	// issuer's too (Issuer.MaxConcurrency).
	MaxConcurrency int
	// ServiceTier is Key.ServiceTier.
	ServiceTier string
	// Redact is Key.Redact; an issued key is held on by its issuer's on.
	Redact string
	// Routing is Key.Routing; an issued key that sets none follows its
	// issuer's.
	Routing string
	// Default: the key is the sharing key magpie made itself (Default),
	// the one it writes into this computer's own agents that reach the
	// gateway from beyond loopback, never one the user made for someone
	// else.
	Default bool
	// Group is the routing group, by name, whose own accounts hold the
	// request as well (HeldToGroup); "" when none does.
	Group string
	// Agent is the agent whose own account or key of some providers
	// (provider.Provider.AgentAccounts, nb5p on Discord) holds the request
	// as well (HeldToAgent); "" when none does.
	Agent string

	// Spent are the key's limits of some models (Limit.Models) with
	// nothing left, as the gateway found them for this request: their
	// models are left out of its candidates, a routing group's members
	// too, and a request naming one is refused with Why.
	Spent []SpentScope
	// contains filtered or unexported fields
}

Identity is the gateway key a request came with, its budget, the models and the accounts it may use.

func Authenticate

func Authenticate(secret string) (Identity, bool)

Authenticate reloads the store so revocation takes effect in running gateways. An expired key, or one whose issuer no longer lets it in, is refused as one turned off is; Check says why.

func Caller

func Caller(ctx context.Context) Identity

func Check added in v0.1.2334

func Check(secret string) (Identity, error)

Check is Authenticate with why a key it knows is turned away: a *Refused for one expired or whose issuer no longer lets it in.

func (Identity) AgentOnly

func (who Identity) AgentOnly() bool

AgentOnly says every account who is held to is the one its agent was set to use (HeldToAgent), none a gateway key's or a routing group's.

func (Identity) AliasFor

func (who Identity) AliasFor(name string) (string, bool)

AliasFor is the model a name the key gives stands for, letter case aside.

func (Identity) AliasOf

func (who Identity) AliasOf(id string) (string, bool)

AliasOf is the name the key gives the model id, if it does (case aside).

func (Identity) Allows added in v0.1.990

func (who Identity) Allows(ids ...string) bool

Allows says one of ids is among the key's models; any, for a key that lists none. An Identity's models are already HeldModels: a key that names accounts and no model may use its accounts' providers' models.

func (Identity) AllowsAccount added in v0.1.1076

func (who Identity) AllowsAccount(pid, ref string) bool

AllowsAccount says the provider pid's account or key ref is among the key's accounts — "<provider>/<ref>", told apart in lower case, as accounts are. The list holds a key to some accounts **of the providers it names**: a provider it names no account of, the key uses as it always did, its every account and key. Any, for a key that lists none. An account the list keeps out ("<provider>/!<ref>") is never one, and keeps the key off no other: every account its provider signs in later is one the key may use.

func (Identity) HeldToAgent

func (who Identity) HeldToAgent(agent string, accounts []string) Identity

HeldToAgent is who held to the accounts agent was set to use (accounts, "<provider>/<ref>", one a provider), by HeldToGroup's rule: a provider one names is used on that account or key alone, while it is one the caller's key may use as well; every other provider as before. Agent is set, for the error to say whose choice held the request.

func (Identity) HeldToGroup added in v0.1.2618

func (who Identity) HeldToGroup(group string, accounts []string) Identity

HeldToGroup is who held to a routing group's accounts too (accounts, a Group's Accounts, in the key's form): a provider the group names is used only on the accounts the group names that the key may use as well, none when the two share none, never one either leaves out; a provider only the key names, on the key's; one neither names, on every account it has. Group is set to the group's name, for the error to say whose accounts held the request. A group naming no account is who as it is. Everything that holds a request to its key's accounts (AllowsAccount) holds it to the group's then, by the one rule.

func (Identity) IssuerID added in v0.1.2334

func (who Identity) IssuerID() string

IssuerID is the id of the key who was issued under, "" for none.

func (Identity) KeyHeld

func (who Identity) KeyHeld() bool

KeyHeld is Restricted less the accounts an agent was set to use: a key or a group holds who to some models or accounts. A request held by its agent's accounts alone is routed as one held to none, those accounts aside (the gateway's keyHolds).

func (Identity) Limited added in v0.1.2334

func (who Identity) Limited() bool

Limited: a request of who's is held to a limit, its own key's or the key it was issued under's.

func (Identity) Limits added in v0.1.1242

func (who Identity) Limits() []*Limit

Limits are the limits who's key holds it to, as Key.Limits.

func (Identity) MCPAllows added in v0.1.3195

func (who Identity) MCPAllows(server, tool string) bool

MCPAllows is whether the key may use the tool of the MCP server called server.

func (Identity) MCPHeld added in v0.1.3195

func (who Identity) MCPHeld() bool

MCPHeld is whether the key, or the key it was issued under, is held to some MCP servers or tools.

func (Identity) MCPOff

func (who Identity) MCPOff() bool

MCPOff is whether the key, or the key it was issued under, is held to no MCP server at all (NoMCP): a key for models only.

func (Identity) MCPServer added in v0.1.3195

func (who Identity) MCPServer(server string) (ok, every bool)

MCPServer is whether the key may reach the MCP server called server, and whether it may use every tool of it (else MCPAllows says which).

func (Identity) ModelsOff

func (who Identity) ModelsOff() bool

ModelsOff is whether the key is held to no model at all (NoModels): a key for MCP servers only. An issued key's Models are folded with its issuer's already (identityOf).

func (Identity) NamesProvider

func (who Identity) NamesProvider(pid string) bool

NamesProvider says who's accounts name some account of provider pid.

func (Identity) Restricted added in v0.1.990

func (who Identity) Restricted() bool

Restricted says the key may use only the models or accounts it lists.

func (Identity) ShownAccounts added in v0.1.2618

func (who Identity) ShownAccounts() []string

ShownAccounts is who's accounts as a message lists them: the entries HeldToGroup adds to name a provider with none of its accounts left out. An account kept out stays "<provider>/!<ref>".

func (Identity) SpentOn added in v0.1.3170

func (who Identity) SpentOn(model string) (SpentScope, bool)

SpentOn is the spent limit that counts model ("<provider>/<model>"), the one that resets last when several do.

type Issue added in v0.1.2334

type Issue struct {
	Name string
	TTL  time.Duration
	// Models and Accounts hold the key as Key's do; with an issuer, each
	// must be one the issuer may use, and none takes the issuer's.
	Models   []string
	Accounts []string
	// Tokens and Cost cap what the key may spend over its whole life.
	Tokens   int64
	Cost     float64
	ReadOnly bool
	// Issuer is the id of the key it is issued under; "" for one the
	// user issues themselves (the command line, or loopback with no key).
	Issuer string
}

Issue is what IssueKey makes.

type Issued added in v0.1.2334

type Issued struct {
	ID       string    `json:"id"`
	Name     string    `json:"name"`
	Key      string    `json:"key"`
	Expires  time.Time `json:"expires"`
	Issuer   string    `json:"issuer,omitempty"`
	Models   []string  `json:"models,omitempty"`
	Accounts []string  `json:"accounts,omitempty"`
	Limit    *Limit    `json:"limit,omitempty"`
	ReadOnly bool      `json:"readOnly,omitempty"`
}

Issued is a key IssueKey made, its secret told once.

func IssueKey added in v0.1.2334

func IssueKey(in Issue) (Issued, error)

IssueKey makes a short-lived key. It never outlives its issuer, nor is let use a model or account its issuer may not.

type Key

type Key struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Off    bool   `json:"off,omitempty"`
	LAN    bool   `json:"lan,omitempty"` // default key and durable migration marker
	Secret string `json:"secret,omitempty"`
	Masked string `json:"masked,omitempty"`
	// Limit is the key's own budget (#585); nil for none.
	Limit *Limit `json:"limit,omitempty"`
	// More are its limits after the first (#2227), each a window of its
	// own: a request passes only while every one has something left. A
	// key has them only beside a Limit, which an older magpie still reads.
	More []Limit `json:"moreLimits,omitempty"`
	// Models are the models the key may use (#882): "<provider>/<model>",
	// "<provider>/*" or a group's "group/<name>"; none for every model,
	// unless it lists accounts: then its accounts' providers' (HeldModels).
	// NoModels alone is no model: a key for MCP servers only.
	Models []string `json:"models,omitempty"`
	// Aliases are the names the key gives models (tsingchao on X): a name
	// its client asks by, the model "<provider>/<model>" it stands for.
	// /v1/models lists the name in the model's place and a request by it
	// goes to the model, which the key's Models must allow.
	Aliases map[string]string `json:"aliases,omitempty"`
	// Accounts are the accounts and keys the key may use (#905), as
	// "<provider>/<account>": a signed-in account by its stable id, a
	// key by its fingerprint; none for every account, as keys always did.
	Accounts []string `json:"accounts,omitempty"`
	// MCP are the MCP servers and tools the key may use (mcp.go):
	// "<server>", "<server>/<tool>", or NoMCP alone for none; none
	// listed for every server and tool.
	MCP []string `json:"mcp,omitempty"`
	// Quotas lets a key held to a budget, models or accounts be told the
	// quotas of what it may use (#2216): the cards of the providers whose
	// every model it may use, of the accounts and keys it may use, names
	// and balances included. Off, it is told none (#1981).
	Quotas bool `json:"quotas,omitempty"`
	// ReadOnly holds the key to reading this magpie's stats (Steven on
	// Discord: a desk display polling quotas and usage, its key kept in
	// a device's flash): the gateway answers it only the routes in its
	// readOnlyRoutes and refuses it every other, every model, MCP and
	// write route among them. Off, the key may do what its other limits let it.
	ReadOnly bool `json:"readOnly,omitempty"`
	// Browser holds the key to connecting the Magpie Browser extension
	// (GET /v1/magpie/browser/extension) and nothing else: the key the
	// GUI writes into the extension's zip (gui's browserKey), which lands
	// in Downloads, where anyone who reads it has it. The gateway refuses
	// it every other route, every model and MCP server among them
	// (readOnlyGuard). Such a key is ReadOnly too, so a magpie from before
	// this field, which reads it as any other key, holds it to reading
	// stats rather than handing it every model.
	Browser bool `json:"browser,omitempty"`
	// Admin lets the key use the management API (/v1/magpie/admin/, ljayic
	// on X): AdminLocal from this computer only, AdminAny from the network
	// too; "" for none. Only a key the user made themselves can have it:
	// not a read-only, browser, issued or expiring key, nor the default
	// sharing key, which magpie hands to agents.
	Admin string `json:"admin,omitempty"`
	// Memory lets the key's agents on another computer use Magpie Memory
	// (/mcp/magpie/memory, and the hub's magpie-memory), reading and
	// saving what is known about this computer's user (Niapyaya on X).
	// Memory's digest goes into every agent's instructions here, so it is
	// never a key's by default: only a key the user made themselves can
	// have it, as Admin (memoryOf). Agents on this computer use memory
	// whatever it says.
	Memory bool `json:"memory,omitempty"`
	// Expires is when the key stops working (an issued key, IssueKey);
	// zero for one that doesn't. Prune removes it a while after.
	Expires time.Time `json:"expires,omitzero"`
	// Issuer is the id of the key it was issued under, which bounds it
	// (issue.go); "" for one the user made or issued themselves.
	Issuer string `json:"issuer,omitempty"`
	// Issues lets the key issue short-lived keys under itself
	// (POST /v1/magpie/keys); an issued key never can.
	Issues bool `json:"issues,omitempty"`
	// MaxConcurrency is how many of the key's requests may be in flight
	// at once (young02036 on Discord); over it they wait in the key's
	// queue and go out in order, as over a provider's MaxConcurrency.
	// 0 for no limit.
	MaxConcurrency int `json:"maxConcurrency,omitempty"`
	// ServiceTier is the service tier the key's OpenAI-API requests (Chat
	// and Responses) are sent at whatever the client asked (JackyFill on
	// X): settings.CodexTierStandard for none, "priority" (Codex's Fast)
	// or "ultrafast"; "" follows the request.
	ServiceTier string `json:"serviceTier,omitempty"`
	// Redact is whether Settings › Privacy's masking applies to the key's
	// requests (y0ngb1n on X): "" follows the setting, RedactOn masks them
	// even where the setting masks nothing, RedactOff sends them as they
	// are, for a device the user trusts. A request with no key (this
	// computer's own) always follows the setting.
	Redact string `json:"redact,omitempty"`
	// Routing is how a routing group the key asks for picks among its
	// members' accounts and keys for the key's requests (justforlxz on
	// X): RoutingSmart, one of provider's group routings but Manual, or a
	// plugin's
	// "<plugin>/<name>"; "" follows the group's own. A manual group
	// still sends to its pick, and a group in the group, or a provider
	// routed its own way in it, keeps its own routing, as always.
	Routing string `json:"routing,omitempty"`
}

func Export

func Export() ([]Key, error)

Export returns credentials only for the encrypted backup bundle.

func IssuedBy added in v0.1.2334

func IssuedBy(by string) ([]Key, error)

IssuedBy lists the keys issued under the key by ("" for those the user issued themselves), without their secrets.

func List

func List() ([]Key, error)

List never returns credentials; only the administrator's copy action does.

func (Key) Limits added in v0.1.1242

func (k Key) Limits() []*Limit

Limits are k's limits, its Limit first; none for a key with no limit. Each holds the key on its own: a request passes only while all of them have something left.

type Limit added in v0.1.675

type Limit struct {
	Period string `json:"period"`
	// Days is a "days" limit's cycle, 1 to MaxDays; 0 for the others.
	Days int `json:"days,omitempty"`
	// Hours is an "hours" limit's cycle, 1 to MaxHours; 0 for the others.
	Hours      int     `json:"hours,omitempty"`
	Tokens     int64   `json:"tokens,omitempty"`
	Cost       float64 `json:"cost,omitempty"`
	CacheReads bool    `json:"cacheReads,omitempty"`
	// Since is magpie's, never the caller's (Update sets it): for "days"
	// and "hours", when the first cycle began, the limit set or last reset; for a
	// calendar period, when it was last reset, so a call before it in
	// the same window doesn't count. Zero for a calendar limit never
	// reset, as every limit from before #1509 is.
	Since time.Time `json:"since,omitzero"`
	// Models scope the limit to some models (zola_xynb on X: a cap for
	// one model or one provider under one key): "<provider>/<model>" or
	// "<provider>/*", as a key's models are written. The limit counts
	// only the key's calls a model of them answered, and holds only
	// requests that would go to one: a routing group goes on to its
	// members outside it. None, the whole key, as every limit from
	// before this.
	Models []string `json:"models,omitempty"`
	// Account and AccountWindow are an "account" limit's window
	// (ljayic on X): the window of that name ("5h", "Weekly") of one
	// subscription account ("codex/me@example.com", as a key's accounts
	// are written), so the key's budget starts again when the account's
	// does. Empty for the others.
	Account       string `json:"account,omitempty"`
	AccountWindow string `json:"accountWindow,omitempty"`
}

Limit is a gateway key's budget for a window: a calendar one in local time (#585), a day from midnight, a week from Monday's midnight, a month from the 1st's; or a cycle of Days days (#1509, period "days") or of Hours hours (#2102, period "hours", a subscription's 5-hour window's pace), the first from when the limit was set, each next one a cycle after the last. Tokens counts each call's uncached input, output (reasoning included) and cache writes, and its cache reads too when CacheReads is set; Cost is an estimate in US dollars at the prices magpie shows on the Usage page, not a vendor's bill. A cap of 0 is no cap; a limit with neither is no limit.

func (*Limit) Counts added in v0.1.3170

func (l *Limit) Counts(model string) bool

Counts says a call model answered ("<provider>/<model>") counts toward l: every call for a limit of the whole key.

func (*Limit) Limited added in v0.1.675

func (l *Limit) Limited() bool

Limited: l caps something.

func (*Limit) Per added in v0.1.1166

func (l *Limit) Per() string

Per is the window as a sentence ends it: "day", "week", "month", "total", "10-day cycle", "5-hour cycle" or "codex/me@example.com 5h window".

func (*Limit) Scope added in v0.1.3170

func (l *Limit) Scope() string

Scope is l's models as one string, the same for the same models in any order or letter case; "" for the whole key.

func (*Limit) Scoped added in v0.1.3170

func (l *Limit) Scoped() bool

Scoped: l counts only some models' calls (Limit.Models).

func (*Limit) Valid added in v0.1.675

func (l *Limit) Valid() (*Limit, error)

Valid is l as it is kept: nil for no limit, an error for one that can't be. Since is left as it came; Update decides it.

func (*Limit) Window added in v0.1.1166

func (l *Limit) Window(now time.Time) (start, reset time.Time)

Window is the window l counts in at now, in now's location: when it began and when the next begins. A "days" or "hours" cycle is counted in absolute time, 24h a day whatever the clocks do, so a restart or a change of time zone or summer time keeps it; one with no Since runs from the Unix epoch. A calendar window starts at Since instead when the key was reset in it.

type ProviderKey

type ProviderKey struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Off   bool   `json:"off,omitempty"`
	Reach string `json:"reach"`
	// Only: the provider is all the key may use by name, so taking it off
	// would leave it no model, which reads as every model (Models empty):
	// such a key is changed in its own models.
	Only bool `json:"only,omitempty"`
	// Via are the key's patterns that may name some of the provider's
	// models whatever it is ticked: "re:…", or a wildcard provider.
	Via []string `json:"via,omitempty"`
}

ProviderKey is a gateway key as a provider's editor shows it.

func ProviderKeys

func ProviderKeys(pid string, groups []GroupRef) ([]ProviderKey, error)

ProviderKeys are the gateway keys that may use a model, each with how far it reaches provider pid, in the keys' own order; groups are the routing groups, as they reach pid now.

type Refused added in v0.1.2334

type Refused struct{ Why string }

Refused is why Check turned away a key it knows: expired, or bounded by an issuer that no longer lets it in. The gateway says it with a 401 on every route, from this computer too.

func (*Refused) Error added in v0.1.2334

func (r *Refused) Error() string

type SpentScope added in v0.1.3170

type SpentScope struct {
	// Models are the limit's models, with the other ids each goes by
	Models []string
	Reset  time.Time
	// Why is what a request for one of them is told
	Why string
}

SpentScope is a limit of some models with nothing left until Reset.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL