providers

package
v0.16.521 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: AGPL-3.0 Imports: 38 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 providers holds the backend profiles: another vendor's models (Kimi, GLM, Grok, GPT) behind an agent CLI the machine already runs. A profile is no Provider: Kimi and GLM run through Claude Code on a settings file of their own, Grok through Codex with an `xai` provider, GPT through Claude Code on a local CLIProxyAPI that turns its requests into the ChatGPT backend's (GPTProxy). The presets here are data; the person picks one and gives a key, and never types an address, so a key cannot be pointed at a host the runtime does not know.

Index

Constants

View Source
const (
	ProfilesProtocol   = "harnessly.model-profiles/v1"
	ProfilesCapability = "profiles"
)

ProfilesCapability is what an adapter lists in its description to offer profiles; it answers GET /v1/profiles.

View Source
const (
	RouterModelAuto = "auto"
	RouterModelFast = "auto-fast"
)

The models of the auto profile: one decided per turn, one always light (Claude Code's small model: titles, summaries).

View Source
const (
	SpeechOpenAI = "openai"
	// SpeechYandex is a Yandex Cloud API key of a service account; SpeechYandexFolder the folder id some accounts
	// send beside it (it is no secret, but is kept and shown the same way).
	SpeechYandex       = "yandex"
	SpeechYandexFolder = "yandex-folder"
)

The keys of the speech recognition providers live in the same store as the keys of the backend profiles (one file each, <Dir>/<id>.key); they are no profiles: no agent runs on them, so Presets does not list them.

View Source
const ChatHeaderEnv = `ANTHROPIC_CUSTOM_HEADERS="` + chatHeader + `: ` + chatMarker + `$TMUX_PANE/$TMUX"`

ChatHeaderEnv is the environment word of a GPT chat's launch line, written for sh: the pane's shell fills in the pane ($TMUX_PANE) and its tmux server ($TMUX) when the line runs, so every launch and resume of the chat says its pane whichever way it was started.

View Source
const CodexRenewAhead = 4 * time.Minute

CodexRenewAhead is how long before its expiry the Codex token is renewed: inside the five minutes in which the CLI itself renews it, else the CLI would find it fresh and leave it.

View Source
const ExtRelayPath = "/api/cli/ext"

ExtRelayPath is where the runtime mounts the relay of the OpenAI-compatible providers.

View Source
const GPTRelayPath = "/api/cli/gpt/v1"

GPTRelayPath is where the runtime mounts the GPT relay.

View Source
const OAuthStub = "harnessly-no-oauth"

OAuthStub is the Claude Code OAuth token of a profile's chat. Claude Code takes the key of apiKeyHelper before an OAuth token, so the stub changes nothing for the chat itself; it is for a `claude` the chat's agent starts from Bash, which inherits the environment but not the helper's key: without a token of its own that one would fall back to the person's subscription and send it to the vendor.

View Source
const (
	ProxyVersion = "8.1.2"
)

CLIProxyAPI (github.com/router-for-me/CLIProxyAPI, MIT) is the proxy a GPT chat of Claude Code runs on: it takes Anthropic's Messages API and sends the ChatGPT backend's Responses requests. The runtime downloads one release of it, pinned here with the digest of each archive, the first time the switch goes on; a new release is a change of this file. Linux takes the builds without plugins: static, and the proxy's plugins stay off anyway.

View Source
const RelayBodyMax = 64 << 20

RelayBodyMax bounds a request Codex sends: a long chat with every tool runs to a few megabytes.

View Source
const RelayPrefix = "/api/cli/providers"

RelayPrefix is where the runtime mounts the relays: <RelayPrefix>/<profile id>/v1/….

View Source
const RenewAhead = 10 * time.Minute

RenewAhead is how long before its expiry a token is renewed.

View Source
const RouterPath = "/api/cli/router"

RouterPath is where the runtime mounts the router.

View Source
const TestTimeout = 15 * time.Second

TestTimeout bounds a test of a connection.

View Source
const VendorModelsEvery = 6 * time.Hour

VendorModelsEvery is how often the lists are asked again.

Variables

View Source
var (
	// ErrNotClaude: only a profile that runs through Claude Code has a settings file.
	ErrNotClaude = errors.New("providers: the profile does not run through Claude Code")
	// ErrUnknownModel: the model is none of the preset's.
	ErrUnknownModel = errors.New("providers: the preset has no such model")
	// ErrNoSecret: a secret variable of the profile has no value in the safe.
	ErrNoSecret = errors.New("providers: a secret variable of the profile has no value in the safe")
	// ErrSubscriptionToken: the key or a secret variable of a provider is the token of a Claude subscription's sign-in.
	// The machine has one such sign-in, the CLI's own; a chat is not started on a second one.
	ErrSubscriptionToken = errors.New("providers: a provider holds the token of a Claude subscription, not a key of the API")
	// ErrSwitchOff: the profile's switch is off, or its proxy has no address yet.
	ErrSwitchOff = errors.New("providers: the profile is switched off")
)
View Source
var AccountVendors = []string{"kimi", "kimi-code", "glm", "glm-cn"}

AccountVendors are the vendors' profiles whose key is an account of the person's providers, added and removed among the providers and not typed for the profile itself.

View Source
var ErrNoKey = errors.New("providers: no key saved")

ErrNoKey: no key is saved for the profile.

View Source
var ErrNoLogin = errors.New("providers: the vendor's CLI is not signed in")

ErrNoLogin: the CLI is not signed in, or its sign-in can no longer be renewed.

View Source
var ErrNoProxyBuild = errors.New("providers: no CLIProxyAPI build for this system")

ErrNoProxyBuild: CLIProxyAPI has no build for this system.

View Source
var RouterTargets = map[Tier][]Target{
	TierHeavy: {{"kimi-code", "k3.1-pro"}, {"glm", "glm-5.3"}, {"glm-cn", "glm-5.3"}},
	TierLight: {{"glm", "glm-5.3-flash"}, {"glm-cn", "glm-5.3-flash"}, {"kimi-code", "kimi-for-coding"}},
}

RouterTargets are the subscriptions' models by tier, in the order they are tried: the heavy tier is Kimi Code's strongest model, then GLM's; the light tier is GLM's fast model, then Kimi's everyday one. A profile without a key is skipped, so either subscription alone is enough.

SpeechKeys are the ids of the speech providers' keys.

Functions

func AddProfiles added in v0.16.154

func AddProfiles(doc []byte) error

AddProfiles adds the profiles of a ProfileFile document (the bytes of a file or an adapter's answer).

func CodexHome added in v0.16.42

func CodexHome(home string) string

CodexHome is the Codex CLI's home for a user's home: $CODEX_HOME, else ~/.codex.

func CommandSecrets added in v0.16.154

func CommandSecrets(line string) func(string) (string, error)

CommandSecrets reads a secret of the safe by running a command: the line is split at spaces (no shell), «{name}» in it is replaced by the secret's name, and what the command prints is the value. Empty line, no resolver.

func FlatName

func FlatName(namespace, name string) string

FlatName is the function name of a namespace's tool: `<namespace>__<tool>`, cut to the 64 characters a function name may have and told apart by a hash where it is cut.

func GrokHome

func GrokHome(home string) string

GrokHome is the Grok CLI's home for a user's home: $GROK_HOME, else ~/.grok.

func InstallProxy added in v0.16.42

func InstallProxy(ctx context.Context, dir string, client *http.Client) (string, error)

InstallProxy puts the pinned release's binary under dir unless it is there: the archive of this system is downloaded with client (nil is one of ProxyFromEnvironment that gives up after two minutes), checked against its digest and unpacked. A failed download leaves nothing behind.

func IsAccountVendor

func IsAccountVendor(id string) bool

IsAccountVendor says whether a profile is one of AccountVendors.

func IsSpeechKey added in v0.16.86

func IsSpeechKey(id string) bool

IsSpeechKey says id names the key of a speech provider.

func LoadAdapter added in v0.16.154

func LoadAdapter(ctx context.Context, c *ext.Client) error

LoadAdapter asks an adapter of the extension protocol (internal/hub/ext) for its profiles and adds them. A failing adapter adds nothing, and the built-in presets stay.

func LoadProfileFile added in v0.16.154

func LoadProfileFile(path string) error

LoadProfileFile reads the file and adds its profiles; on any error nothing is added.

func Mask

func Mask(key string) string

Mask is the form a saved key takes in the feed: bullets and the last four characters.

func ProxyBin added in v0.16.42

func ProxyBin(dir string) string

ProxyBin is where the pinned release's binary is kept under dir.

func RefreshVendorModels

func RefreshVendorModels(ctx context.Context, s *Store, client *http.Client, force bool) bool

RefreshVendorModels asks each preset's vendor with a credential for its list, at most once in VendorModelsEvery (force: now), and keeps the lists in the store's folder. It says whether a list changed. A vendor that does not answer keeps what was kept.

func RelayPath

func RelayPath(prefix, profile string) string

RelayPath is the path of a profile's relay under the runtime's relay prefix.

func Relays

func Relays(store *Store, prefix string) http.Handler

Relays serves the relay of every Relayed preset under prefix, each over the store's credential of its profile.

func RewriteRequest

func RewriteRequest(raw []byte) ([]byte, map[string]flatTool, error)

RewriteRequest turns a Responses request of Codex into one xAI takes (see Relay) and answers which flat function names stand for which namespaced tools.

func SetBacked

func SetBacked(m map[string]Backing)

SetBacked says which account each of the vendors' profiles runs on: the whole map, as the registry has it now. A profile the map does not name keeps the key typed for it.

func SetCodexLogins

func SetCodexLogins(list []Preset)

SetCodexLogins replaces the profiles of the other sign-ins of the Codex CLI: the whole list, as the registry (internal/codexaccounts) has it now. One that is not of Codex, has no home, no model or an id that is no profile id is left out.

func SetCustom

func SetCustom(list []Preset)

SetCustom replaces the profiles made of the providers the person added by hand: the whole list, as the registry has it now. A profile that is not of Claude Code (a local model's one of Codex is the exception), has no model or an id that is no profile id is left out.

func WithFastTier

func WithFastTier(body []byte, hasFast func(model string) bool) []byte

WithFastTier is a Responses request asking for the fast tier when its model has one; any other body is given back as it came. A body without a service tier gets one put first, so the rest of its bytes stay as they were.

func WithReasoningSummary

func WithReasoningSummary(body []byte) []byte

WithReasoningSummary is a Responses request whose reasoning asks for its summary. CLIProxyAPI (8.0.x) sets only reasoning.effort when it turns Claude Code's request into the backend's, and without a summary the backend sends the reasoning encrypted alone: Claude Code gets empty thinking blocks and the chat shows nothing of what the model thinks for the whole of a long step. A request with a summary of its own, without a reasoning object, or that is not a JSON object goes as it came.

Types

type Backing

type Backing struct {
	KeyRef string
	Label  string
}

Backing is the account of the person's providers a vendor's profile runs on: the secret of the safe that holds its key, and the name the person gave the account. An empty KeyRef says there is no account: the profile has no key.

type ClassifyRequest added in v0.16.86

type ClassifyRequest struct {
	// Text is the person's message (its end, when long).
	Text string
	// Turns is how many messages of the person the conversation has, this one included.
	Turns int
	// Step is the step of the turn's tool loop the request is (1 and on); 0 is the turn itself.
	Step int
	// Current is the tier the turn is on now, for a step.
	Current Tier
	// Did is what the agent did at the step before and what the tools gave back (each part cut short), for a step.
	Did string
	// OnCurrent is how many steps the turn has been on Current; Errors is how many of the last steps in a row got an
	// error back from a tool.
	OnCurrent, Errors int
}

ClassifyRequest is what the classifier reads of a new turn.

type CodexLogin added in v0.16.42

type CodexLogin struct {
	// Path is the CLI's auth.json.
	Path string
	// Renew runs the CLI so that it renews the token; nil runs `codex debug models` (Bin, else `codex` on PATH).
	Renew func(ctx context.Context) error
	// Bin is the CLI; empty finds it.
	Bin string
	// Now is the clock; nil is time.Now.
	Now func() time.Time
	// contains filtered or unexported fields
}

CodexLogin is the Codex CLI's sign-in by a ChatGPT subscription: the `auth.json` in its home (~/.codex), an access token of about ten days, the account it is of and the refresh token the CLI renews it with. As with Grok, the runtime never uses the refresh token itself (it rotates, and two renewers would log each other out): Codex renews the token in the last minutes before it runs out, on the first request it makes then, so when the token is that close the runtime runs the CLI once (`codex debug models`, which asks the backend for the models and so renews first) and reads the file again. A sign-in by an API key is no subscription and does not count.

func (*CodexLogin) Account added in v0.16.42

func (c *CodexLogin) Account() (string, bool)

func (*CodexLogin) AccountID added in v0.16.42

func (c *CodexLogin) AccountID() string

AccountID is the ChatGPT account the sign-in is of: the backend wants it beside the token.

func (*CodexLogin) Token added in v0.16.42

func (c *CodexLogin) Token(ctx context.Context) (string, error)

type ExtModel

type ExtModel struct {
	Name, Alias string
	Efforts     []wire.Effort
}

ExtModel is a model of an ExtUpstream.

type ExtProxy

type ExtProxy interface {
	// ExtReady: the proxy relays the provider of that id.
	ExtReady(provider string) bool
	// ExtEndpoint is the proxy's address and the file of its key, the proxy started when it does not run.
	ExtEndpoint(ctx context.Context) (baseURL, keyFile string, err error)
}

ExtProxy is the proxy Claude Code reaches an OpenAI-compatible provider through (GPTProxy).

type ExtUpstream

type ExtUpstream struct {
	// ID is the provider's id: the path of its relay.
	ID     string
	Models []ExtModel
}

ExtUpstream is an OpenAI-compatible provider of the proxy: Claude Code asks for a model by its Alias, the proxy sends the provider its Name at /chat/completions, through the runtime's relay of the provider.

type FastTiers

type FastTiers interface {
	HasFast(model string) bool
}

FastTiers is a switch whose vendor has a fast tier for some of its models.

type FileModel added in v0.16.154

type FileModel struct {
	ID            string     `json:"id"`
	Label         string     `json:"label,omitempty"`
	Hint          string     `json:"hint,omitempty"`
	Window        int        `json:"window,omitempty"`
	Efforts       []string   `json:"efforts,omitempty"`
	DefaultEffort string     `json:"default_effort,omitempty"`
	Price         *FilePrice `json:"price,omitempty"`
}

FileModel is one model of a FileProfile: its limits and, optionally, its price.

type FilePrice added in v0.16.154

type FilePrice struct {
	Input       float64  `json:"input"`
	Output      float64  `json:"output"`
	CachedInput *float64 `json:"cached_input,omitempty"`
}

FilePrice is dollars per million tokens.

type FileProfile added in v0.16.154

type FileProfile struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	// Vendor picks the mark the page draws: kimi, glm, grok or gpt. A profile of a vendor of its own takes the closest.
	Vendor string `json:"vendor"`
	// API is the format the endpoint speaks: «anthropic» (Claude Code) or «openai-responses» (Codex).
	API     string `json:"api"`
	BaseURL string `json:"base_url"`
	Hint    string `json:"hint,omitempty"`
	// KeyRef is the name of the secret in the safe that holds the key; empty while the person types the key in Settings.
	KeyRef string `json:"key_ref,omitempty"`
	// KeyEnv is the variable Codex reads the key from (api openai-responses only).
	DisableMCP bool `json:"disable_mcp,omitempty"`
	// ExcludeBuiltinMCP lists built-in MCP groups to leave out of the launch: media, runtime or apps. Servers the person
	// or the provider configured stay.
	ExcludeBuiltinMCP []string          `json:"exclude_builtin_mcp,omitempty"`
	KeyEnv            string            `json:"key_env,omitempty"`
	Env               map[string]string `json:"env,omitempty"`
	Small             string            `json:"small,omitempty"`
	Test              string            `json:"test,omitempty"`
	Models            []FileModel       `json:"models"`
}

FileProfile is one profile of a ProfileFile.

type GPTProxy added in v0.16.42

type GPTProxy struct {
	Dir string
	// OnFile keeps the switch across restarts: it exists while the switch is on.
	OnFile string
	// OffFile keeps the person's «off»; with it set, the switch is on until it exists (switchOn).
	OffFile string
	// Login is the Codex CLI's sign-in the requests go up on.
	Login *CodexLogin
	// RelayBase is the runtime's GPT relay as the proxy reaches it (http://127.0.0.1:<port>/api/cli/gpt/v1).
	RelayBase string
	// Install puts the proxy's binary in place and gives its path; nil is InstallProxy.
	Install func(ctx context.Context, dir string) (string, error)
	// Command is the proxy's command for a config file; nil runs the binary with it and the built-in model lists.
	Command func(bin, config string) *exec.Cmd
	// FastTier says whether the ChatGPT backend has the fast tier for a model (Codex's model cache); nil: for none.
	FastTier func(model string) bool
	// ExtRelayBase is the runtime's relay of the OpenAI-compatible providers as the proxy reaches it
	// (http://127.0.0.1:<port>/api/cli/ext): the upstream of provider <id> is ExtRelayBase/<id>, and the relay puts the
	// provider's key from the safe on each request, so the proxy's config holds no key of a provider. "" runs none.
	ExtRelayBase string
	// FastPane says whether the chat in a tmux pane (its $TMUX_PANE, on the server of that socket name, "" for any) is
	// in fast mode; nil: none is. It is read on each request of the relay.
	FastPane func(pane, socket string) bool
	// contains filtered or unexported fields
}

GPTProxy is the switch of the gpt profile and the CLIProxyAPI it keeps running while it is on. The chain of a GPT chat is Claude Code → the proxy (127.0.0.1, a port of its own, a key of its own) at Anthropic's /v1/messages → the proxy's Codex upstream, set up as an API key with a base URL that is the runtime's GPT relay → the relay, which puts on the Codex CLI's ChatGPT token and account and sends it to chatgpt.com. So the proxy never holds the person's sign-in, and the Codex CLI stays the only one that renews it (CodexLogin).

The proxy is a child of the runtime: started when the switch goes on (downloaded the first time, InstallProxy), watched and started again after a crash with a growing pause, stopped when the switch goes off or the runtime ends. Its files are under Dir, a folder of 0700: the config (written on every start), the key Claude Code sends, the port, the log and the binary.

func (*GPTProxy) Close added in v0.16.42

func (g *GPTProxy) Close()

Close stops the proxy and leaves the switch as it is: the runtime ends.

func (*GPTProxy) Endpoint added in v0.16.42

func (g *GPTProxy) Endpoint() (string, string, bool)

Endpoint is the proxy's address and the file of its key, while the switch is on and the proxy has a port.

func (*GPTProxy) Ensure

func (g *GPTProxy) Ensure(ctx context.Context) error

Ensure starts the proxy (downloaded the first time) when the switch is on and it does not run: a chat is about to ask Endpoint for it.

func (*GPTProxy) ExtEndpoint

func (g *GPTProxy) ExtEndpoint(ctx context.Context) (string, string, error)

ExtEndpoint is where a Claude Code chat on an OpenAI-compatible provider sends its requests and the file of the key it sends: the proxy, started (downloaded the first time) when it does not run.

func (*GPTProxy) ExtReady

func (g *GPTProxy) ExtReady(id string) bool

ExtReady says whether a chat may start on the OpenAI-compatible provider of that id: the proxy has it among its upstreams (it is started when the chat asks for it).

func (*GPTProxy) HasFast

func (g *GPTProxy) HasFast(model string) bool

HasFast says whether the ChatGPT backend has the fast tier for the model, by Codex's own model cache.

func (*GPTProxy) LogFile added in v0.16.42

func (g *GPTProxy) LogFile() string

LogFile is the proxy's output, both streams.

func (*GPTProxy) Notify added in v0.16.42

func (g *GPTProxy) Notify(f func())

Notify sets what is told when the proxy comes up or goes down by itself, so a machine can show the profile offered or not.

func (*GPTProxy) On added in v0.16.42

func (g *GPTProxy) On() bool

func (*GPTProxy) Ready added in v0.16.42

func (g *GPTProxy) Ready() bool

Ready: the switch is on and Codex is signed in by the subscription. The proxy is started by the chat that needs it (Ensure), so a machine that never opens a GPT chat never downloads it.

func (*GPTProxy) RefreshModels

func (g *GPTProxy) RefreshModels()

RefreshModels gives a running proxy the latest models of Codex's cache. CLIProxyAPI watches its config, so existing chats can switch to a newly offered model without restarting either the proxy or the chat.

func (*GPTProxy) Relay added in v0.16.42

func (g *GPTProxy) Relay() *Relay

Relay is the GPT relay mounted on GPTRelayPath: only the proxy, with the secret of this runtime, may use it, and each request goes up to the ChatGPT backend with the Codex CLI's token and account.

func (*GPTProxy) Resume added in v0.16.42

func (g *GPTProxy) Resume()

Resume starts the proxy in the background when the switch is on and Codex is signed in: at the start of the runtime. A proxy that does not come up is tried again with the pauses of a crash.

func (*GPTProxy) Secret added in v0.16.42

func (g *GPTProxy) Secret() string

Secret is the key the proxy sends the relay.

func (*GPTProxy) SetExt

func (g *GPTProxy) SetExt(list []ExtUpstream)

SetExt sets the OpenAI-compatible providers of the proxy. A proxy that runs takes them at once (its config is written again, and CLIProxyAPI reads it again); one that runs only for them stops when there are none left.

func (*GPTProxy) SetOn added in v0.16.42

func (g *GPTProxy) SetOn(ctx context.Context, on bool) error

SetOn turns the switch. On: Codex must be signed in by the subscription; the binary is installed, the proxy started, and the call returns once it answers (a *wire.ProfileSwitchError when it does not, and the switch stays off). Off stops the proxy.

type GrokLogin

type GrokLogin struct {
	// Path is the CLI's auth.json.
	Path string
	// Renew runs the CLI so that it renews the token; nil runs `grok models` (Bin, else `grok` on PATH, else
	// ~/.grok/bin/grok next to Path).
	Renew func(ctx context.Context) error
	// Bin is the CLI; empty finds it.
	Bin string
	// Now is the clock; nil is time.Now.
	Now func() time.Time
	// contains filtered or unexported fields
}

GrokLogin is the Grok CLI's sign-in: the `auth.json` in its home (~/.grok), an access token of a few hours and the refresh token the CLI renews it with. The runtime does not use the refresh token itself: refresh tokens rotate, and two renewers of one sign-in would log each other out. When the token is about to run out it runs the CLI once (`grok models`, which renews before it asks) and reads the file again.

func (*GrokLogin) Account

func (g *GrokLogin) Account() (string, bool)

func (*GrokLogin) Token

func (g *GrokLogin) Token(ctx context.Context) (string, error)

type Launcher

type Launcher struct {
	Store *Store
	// Relay is where Codex reaches a Relayed profile; nil sends it straight to the vendor with the saved key.
	Relay *RelayEndpoint
	// SyncHome brings the home of a profile that is another sign-in of Codex up to date before a chat starts in it
	// (what the main home gained since); nil does nothing.
	SyncHome func(profile string) error
}

Launcher is what a launch on a backend profile asks of the profiles (agents.ProfileLauncher), over a Store.

func (Launcher) ClaudeLineEnv

func (l Launcher) ClaudeLineEnv(profile string) string

ClaudeLineEnv is what a Claude Code chat on the profile adds to its launch line: the pane header for gpt (whose proxy has a fast tier to offer), nothing for another profile.

func (Launcher) ClaudeMCPDisabled

func (l Launcher) ClaudeMCPDisabled(profile string) bool

ClaudeMCPDisabled reports the MCP policy of a deployment-defined model profile.

func (Launcher) ClaudeMCPExcluded

func (l Launcher) ClaudeMCPExcluded(profile string) []string

ClaudeMCPExcluded lists the built-in MCP groups a deployment-defined profile leaves out of a launch; nil for the ordinary profiles.

func (Launcher) ClaudeModelPinned

func (l Launcher) ClaudeModelPinned(profile string) bool

ClaudeModelPinned says whether the person typed the model of their own provider (ANTHROPIC_MODEL among its variables): what is filled in is always what a chat on it runs, whatever the picker of the chat says.

func (Launcher) ClaudeModelSwitchLabel

func (Launcher) ClaudeModelSwitchLabel(profile, id string) string

ClaudeModelSwitchLabel returns a distinct display name Claude may use when acknowledging this model. A name shared with another model or alias on the route cannot identify the requested target.

func (Launcher) ClaudeSettings

func (l Launcher) ClaudeSettings(profile, model, hooksPath string) (string, error)

ClaudeSettings is the settings file of a Claude Code chat on a profile and a model (Store.SettingsFile).

func (Launcher) Codex

func (l Launcher) Codex(profile string) (agents.CodexProfile, error)

Codex points Codex at the profile's provider: the address, the variable the key is read from, the Responses API. The key is not here; the launch line fills the variable from the key's file.

func (Launcher) Lookup

func (l Launcher) Lookup(id string) (via wire.Provider, configured bool, models []string, ok bool)

Lookup says what a conversation may start on for the profile: the CLI it runs through, whether it is ready (a key is saved, or the vendor CLI is signed in), and the ids of its models (convo.Profiles).

func (Launcher) Model

func (l Launcher) Model(profile, id string) (wire.AgentModel, bool)

Model is the wire capability record of one of the profile's models.

func (Launcher) OwnsModel

func (Launcher) OwnsModel(model string) bool

OwnsModel says whether the model id is one of some profile's: a conversation on the CLI's own account is not to be started on it or switched to it.

func (Launcher) Window

func (Launcher) Window(profile, model string) int

Window is the context window of a model of the profile; 0 for one it does not know.

type Login

type Login interface {
	// Account is whom the sign-in is of (an email); ok is false while there is no usable sign-in.
	Account() (account string, ok bool)
	// Token is a current access token, renewed through the CLI when it is about to run out.
	Token(ctx context.Context) (string, error)
}

Login is a sign-in of a vendor's own CLI on this machine that a profile can run on instead of a saved key: a subscription the person already pays for. The runtime reads the CLI's credential and never writes it; the CLI renews it.

type Model

type Model struct {
	ID     string
	Label  string
	Hint   string
	Window int
	// EffortUnknown means the route has not described its reasoning controls.
	EffortUnknown bool
	Efforts       []wire.Effort
	DefaultEffort wire.Effort
}

Model is one model of a preset: the vendor's id (what `--model` takes), a short label for the picker, the size of its context window in tokens and the reasoning efforts the vendor accepts. DefaultEffort is empty when there is no effort to choose.

func (Model) WithRouteEffort

func (m Model) WithRouteEffort(base, api string) Model

WithRouteEffort fills in the documented default for an ID-only list on QwenCloud's own Messages or OpenAI-compatible endpoint. Gateways and explicit capabilities keep their own contract. https://docs.qwencloud.com/developer-guides/getting-started/latest-model

type Preset

type Preset struct {
	DisableMCP bool
	// ExcludeMCP are the built-in MCP groups the profile leaves out of a launch (claude.ExcludeGroups).
	ExcludeMCP []string
	ID         string
	Label      string
	Vendor     wire.ProfileVendor
	Via        Route
	// BaseURL is where the CLI sends its requests: the Anthropic-compatible address for Claude Code, the OpenAI-
	// compatible `/v1` for Codex.
	BaseURL string
	// Host is BaseURL's host, shown on the Settings screen.
	Host string
	Hint string
	// Models are the vendor's models, the first being the one a new chat offers.
	Models []Model
	// Small is the model that stands in for Claude Code's «haiku» (background work), one of Models.
	Small string
	// Test is the cheapest model, the one a test of the connection asks.
	Test string
	// Env is added to the CLI's environment (Claude Code only).
	Env map[string]string
	// KeyEnv is the variable the key goes to for the CLI that takes it from the environment (Codex only).
	KeyEnv string
	// Relayed: Codex reaches the vendor through the runtime's Relay, which holds the credential and turns Codex's
	// requests into what the vendor takes. Without a relay on the launcher it goes straight to BaseURL with the key.
	Relayed bool
	// Switched: the profile takes no key. The person turns it on (Store.Switches), and Claude Code is pointed at the
	// local proxy the switch keeps; BaseURL is where the proxy's requests end up.
	Switched bool
	// Custom: a provider the person added by hand (the registry of internal/extproviders, SetCustom). Its key and the
	// values of SecretEnv come from the machine's safe (Store.Safe), and it may run on a credential of SecretEnv alone.
	Custom bool
	// Local: a model server on the person's own machine or network (extproviders.PresetLocal). It takes no
	// key, so the profile is ready as soon as it is added, and no credential is sent to it.
	Local bool
	// Proxied names the OpenAI-compatible provider (internal/extproviders) a custom profile reaches through the
	// runtime's proxy (Store.Proxy): Claude Code is pointed at the proxy with the proxy's key, and the proxy turns its
	// requests into the provider's. "" for every other profile.
	Proxied string
	// Backed: the vendor's profile takes its key from an account of the person's providers (SetBacked), not from a key
	// typed for the profile itself. Its KeyRef is that account's secret in the safe; "" while there is no account.
	Backed bool
	// Unlisted: a chat that runs on the profile goes on with it, and a new one is not offered it: the account it is of
	// is the vendor's own profile now (the default account of a vendor), which is the one to pick.
	Unlisted bool
	// SecretEnv are the variables of the CLI's environment whose values the safe holds: the name of the variable to the
	// name of its secret. They are put over Env and over everything the launch sets itself (a custom profile only).
	SecretEnv map[string]string
	// KeyRef names a secret of the safe the key is taken from (a profile of the profiles file, ProfileFile). It is a
	// name and never the value; Store.Secrets turns it into the key when the key is needed.
	KeyRef string
	// Home: the profile is another sign-in of the Codex CLI (SetCodexLogins): the CODEX_HOME a chat on it runs with.
	// It takes no key; it is ready when that home is signed in.
	Home string
}

Preset is a vendor setup.

func Find

func Find(id string) (Preset, bool)

Find is the preset with that id.

func Presets

func Presets() []Preset

Presets are the vendor setups the runtime knows, in the order the Settings screen lists them.

func WithVendorModels

func WithVendorModels(p Preset, listed []VendorModel) Preset

WithVendorModels adds to the preset the vendor's models that are newer versions of a family it has: each goes right before its newest sibling, with that sibling's window and efforts.

func (Preset) AgentModels

func (p Preset) AgentModels() []wire.AgentModel

AgentModels are the preset's models as the wire lists them. Efforts and their defaults belong to the vendor model, not to the CLI it runs through: Kimi and GLM take low/high/max, Grok 4.7 low/medium/high/xhigh.

func (Preset) ClaudeEnv

func (p Preset) ClaudeEnv(model Model) map[string]string

ClaudeEnv is the environment block of a profile's Claude Code settings for a chat on model. Every variable that could carry an Anthropic credential to the vendor is blanked or stubbed; the vendor's key is not here, it is read from a file by apiKeyHelper.

func (Preset) ModelOf

func (p Preset) ModelOf(id string) (Model, bool)

ModelOf is the preset's model with that id.

type ProfileFile added in v0.16.154

type ProfileFile struct {
	Profiles []FileProfile `json:"profiles"`
}

ProfileFile is the document of the profiles file and of the adapter's GET /v1/profiles.

type ProxyConfig added in v0.16.42

type ProxyConfig struct {
	Port                int
	AuthDir             string
	ClientKey, RelayKey string
	RelayBase           string
	ExtBase             string
	Ext                 []ExtUpstream
}

ProxyConfig is what the proxy's config says: where it listens and with which key, and its upstreams: the runtime's GPT relay with the gpt preset's models (RelayBase, "" for none), and the runtime's relay of each OpenAI-compatible provider (ExtBase/<id>). Both relays take RelayKey and put the real credential on; the config holds none.

func (ProxyConfig) YAML added in v0.16.42

func (c ProxyConfig) YAML() []byte

YAML is the proxy's config file, in CLIProxyAPI's flat layout (its v8 template still reads it). Everything the proxy does besides relaying is off: the management API and its panel, usage statistics, the image tool, the retries of another credential (there is none). The upstream goes direct: the relay is on this machine.

type Relay

type Relay struct {
	// Upstream is the vendor's `/v1` address.
	Upstream string
	// Prefix is the path the relay is mounted on, taken off before the rest is put after Upstream.
	Prefix string
	// Credential is the bearer token of one request.
	Credential func(ctx context.Context) (string, error)
	// Client sends the requests up; nil is one without a total timeout (a turn streams for minutes) that follows no
	// redirect.
	Client *http.Client
	// Plain: the body goes up as it came, without the rewrite for xAI (the GPT relay: CLIProxyAPI already sends what
	// the ChatGPT backend takes).
	Plain bool
	// Forward are the headers of the request that go up with it; nil is the ones Codex sends xAI.
	Forward []string
	// Extra are headers of the credential's own put on each request (the ChatGPT account); nil puts none.
	Extra func(ctx context.Context) http.Header
	// Allow says whether a request may use the relay; nil lets every one through, the route in front having checked it.
	Allow func(*http.Request) bool
	// Prepare may change an allowed request before it goes up: its headers in place, and its body (nil for a request
	// without one), given back; rest is the path after Prefix. nil sends it as it came (the GPT relay's fast
	// tier).
	Prepare func(r *http.Request, rest string, body []byte) []byte
}

Relay is the Responses endpoint a Codex chat on a relayed profile (xAI) talks to, on the runtime's own address. It puts the credential on each request (the saved key, else the vendor CLI's sign-in), so Codex holds none, and it turns what Codex sends into what the vendor takes:

  • Codex sends the tools of an MCP server, an app or its sub-agents as one `namespace` tool each, which xAI refuses (422). Each tool of a namespace goes up as a plain function `<namespace>__<tool>`, the namespace's description joins the instructions, and the calls coming back are given their namespace again, so Codex sees what it sent.
  • `web_search` goes without `external_web_access`, which xAI does not take (400).
  • a reasoning item of the history goes without its null fields: xAI reads `content: null` as a broken compaction blob (400).

func (*Relay) ServeHTTP

func (rl *Relay) ServeHTTP(w http.ResponseWriter, r *http.Request)

type RelayEndpoint

type RelayEndpoint struct {
	Base     string
	Header   string
	TokenEnv string
}

RelayEndpoint is the runtime's relay as Codex is told about it: the address of a profile's relay is <Base>/<profile id>/v1, and Codex proves it is the runtime's own with the CLI token, read from TokenEnv into Header (as for the runtime's MCP server), so the address is of no use to anything else on the machine.

type Route

type Route = wire.Provider

Route is the agent CLI a preset runs through.

type Router added in v0.16.86

type Router struct {
	Dir string
	// OnFile keeps the switch across restarts: it exists while the switch is on.
	OnFile string
	// OffFile keeps the person's «off»; with it set, the switch is on until it exists (switchOn).
	OffFile string
	// Base is the router as Claude Code reaches it (http://127.0.0.1:<port>/api/cli/router).
	Base string
	// Store holds the vendors' keys.
	Store *Store
	// Client sends the requests up; nil is one without a total timeout (a turn streams for minutes).
	Client *http.Client
	// Classify decides the tier of a new turn; nil asks the light model (classifyByModel).
	Classify func(ctx context.Context, req ClassifyRequest) (Tier, string, error)
	// Targets are the candidates of each tier in order; nil is RouterTargets.
	Targets map[Tier][]Target
	// Upstream gives a profile's Messages address; nil is the preset's BaseURL + /v1/messages.
	Upstream func(id string) string
	// contains filtered or unexported fields
}

Router is the switch of the auto profile and the endpoint its chats talk to. A chat of the profile is Claude Code sent to the runtime's own address (RouterPath) in Anthropic's Messages format; the router puts each turn on one of the vendor subscriptions the person has a key for (GLM Coding Plan, Kimi Code), with that profile's key, and streams the answer back as it came. Nothing of the person's Anthropic account goes anywhere: the chat's settings stub its OAuth token like any vendor profile's.

Which vendor takes a request is decided at every step of the agent: when the person writes (a user message that is no tool result), a short call to the light model reads the ask and says whether it needs the heavy model or the light one; at every step of the tool loop after it, the same call reads the ask, what the agent just did and what the tools gave back, and says what the next step needs. A plan or a failing test can go to the heavy model and reading files or running a given command to the light one within one task; when the step's classifier does not answer, the step stays where the turn is. A target that answers 429, 5xx or refuses the key before a byte was streamed is put aside for a while and the next one of the tier takes the request, so a used-up weekly quota of one subscription moves the work to the other. Every decision is a line of Dir/decisions.jsonl.

func (*Router) Endpoint added in v0.16.86

func (r *Router) Endpoint() (string, string, bool)

Endpoint is the router's address and the file of the key Claude Code sends it.

func (*Router) LogFile added in v0.16.86

func (r *Router) LogFile() string

LogFile is the journal of decisions, one JSON line each.

func (*Router) Notify added in v0.16.86

func (r *Router) Notify(f func())

Notify sets what is told when the router's readiness may have changed.

func (*Router) On added in v0.16.86

func (r *Router) On() bool

func (*Router) Ready added in v0.16.86

func (r *Router) Ready() bool

Ready: the switch is on and at least one subscription has a key.

func (*Router) RouterStatus added in v0.16.86

func (r *Router) RouterStatus() map[string]time.Time

RouterStatus is what the router says of its targets now: which rest and until when.

func (*Router) ServeHTTP added in v0.16.86

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP takes /v1/messages and /v1/messages/count_tokens of a chat on the auto profile.

func (*Router) SetOn added in v0.16.86

func (r *Router) SetOn(_ context.Context, on bool) error

SetOn turns the switch. On needs a key of GLM or Kimi Code (a *wire.ProfileSwitchError without one).

type Source

type Source struct {
	Store *Store
	// Client sends the test request; nil is a client with TestTimeout that follows no redirect (a redirect would carry
	// the key to the host it points at).
	Client *http.Client
	// BaseURL gives the address a test goes to; nil is the preset's own. It is for tests, which point it at a fake
	// server; the runtime never takes an address from a person.
	BaseURL func(Preset) string
	// OnChange is told after a key is saved or removed, so a machine can show the profile offered or not.
	OnChange func()
}

Source is the wire's ProfilesSource over a Store: the presets of the runtime, the keys and the test of a connection.

func (*Source) Profiles

func (s *Source) Profiles(context.Context) (wire.ProfileList, error)

func (*Source) RemoveProfileKey

func (s *Source) RemoveProfileKey(_ context.Context, id string) (wire.ProfileKey, error)

func (*Source) SetProfileKey

func (s *Source) SetProfileKey(_ context.Context, id, key string) (wire.ProfileKey, error)

func (*Source) SwitchProfile added in v0.16.42

func (s *Source) SwitchProfile(ctx context.Context, id string, on bool) (wire.ProfileInfo, error)

SwitchProfile turns a switched profile on or off and answers it as Profiles lists it.

func (*Source) TestProfile

func (s *Source) TestProfile(ctx context.Context, id string) (wire.ProfileTest, error)

TestProfile makes one minimal request to the vendor with the saved key (else the vendor CLI's sign-in): a message of a token for the Anthropic- compatible vendors, a response of a few tokens for xAI. The answer says how it went and holds neither the key nor the vendor's body.

type Store

type Store struct {
	Dir string
	// Logins are the vendor CLIs' own sign-ins a profile runs on when no key is saved for it, by profile id (the Grok
	// CLI's for xai); nil for none.
	Logins map[string]Login
	// Switches are the switched profiles' switches, by profile id (GPTProxy for gpt); nil for none, and a switched
	// profile without one is never ready.
	Switches map[string]Switch
	// Secrets turns the name of a secret of the safe (Preset.KeyRef of a profile of the profiles file) into its value; nil
	// for none, and a profile with a KeyRef then takes the key typed on the Settings screen like any other.
	Secrets func(name string) (string, error)
	// Safe reads a secret of the machine's safe: the key and the secret variables of a custom profile (Preset.Custom).
	Safe func(name string) (string, error)
	// Proxy is the runtime's proxy a profile of an OpenAI-compatible provider runs on (Preset.Proxied); nil for none,
	// and such a profile is then never ready.
	Proxy ExtProxy
	// contains filtered or unexported fields
}

Store keeps the keys of the profiles, one file each: <Dir>/<profile id>.key, 0600 in a folder of 0700, written whole under a temporary name and renamed over. A key is the person's, on this machine, and is read only by the file the CLI is told to read (apiKeyHelper, `cat`), by a test of the connection and by the mask the wire puts over the feed. It is never logged and never put in a launch line.

func (*Store) AgentModels

func (s *Store) AgentModels(p Preset) []wire.AgentModel

AgentModels are the wire records of the profile's models, each with the fast mode its switch says the vendor has.

func (*Store) Configured

func (s *Store) Configured(id string) bool

Configured says whether a key is saved for the profile.

func (*Store) Credential

func (s *Store) Credential(ctx context.Context, id string) (string, error)

Credential is what a request of the profile is authorised with: the saved key, else the token of the vendor CLI's sign-in. A saved key is the person's choice on the Settings screen and goes first.

func (*Store) Key

func (s *Store) Key(id string) (string, error)

Key is the saved key of a profile; ErrNoKey when there is none. Callers use it for the request of a test and never keep it.

func (*Store) KeyFile

func (s *Store) KeyFile(id string) string

KeyFile is the file the key of a profile is kept in (it may not exist).

func (*Store) LoginOf

func (s *Store) LoginOf(id string) (account string, ok bool)

LoginOf is the account of the vendor CLI's sign-in the profile can run on; ok is false while there is none.

func (*Store) Ready

func (s *Store) Ready(id string) bool

Ready says whether a conversation can run on the profile: a key is saved, or the vendor CLI is signed in; for a switched profile, its switch says.

func (*Store) Redact

func (s *Store) Redact(b []byte) []byte

Redact puts the mask over every saved key in b (a frame as it goes on the wire), in the form it has in a JSON string too. It is for a key an agent printed: a `cat` of the key file, an environment dump. It returns b itself when there is nothing to hide.

func (*Store) Remove

func (s *Store) Remove(id string) (wire.ProfileKey, error)

Remove deletes the saved key; a profile with none stays as it is.

func (*Store) Set

func (s *Store) Set(id, key string) (wire.ProfileKey, error)

Set saves the key of a profile, replacing a saved one, and answers what the page may know of it.

func (*Store) SettingsFile

func (s *Store) SettingsFile(id, model, hooksPath string) (string, error)

SettingsFile writes (rewritten only when its content changes) the `--settings` file of a Claude Code chat on a profile and a model, and gives its path. It is a copy of the hooks settings file (hooksPath) with the profile's environment and an apiKeyHelper that reads the key from its file; a variable the hooks file already had in `env` is kept unless the profile sets it. The key itself is never written here. The file is named after the profile and the model, because the context window is the model's. A switched profile's chat goes to its proxy, with the proxy's key.

func (*Store) Stale

func (s *Store) Stale(id string)

Stale makes the next reader of a profile's key ask the safe again: the provider was changed.

func (*Store) State

func (s *Store) State(id string) wire.ProfileKey

State is whether a key is saved for the profile, and its tail.

func (*Store) SwitchOf added in v0.16.42

func (s *Store) SwitchOf(id string) Switch

SwitchOf is the switch of a switched profile; nil for another profile, or when the runtime keeps none.

type Switch added in v0.16.42

type Switch interface {
	// On is the person's choice, kept across restarts.
	On() bool
	// SetOn turns the switch: on waits until the proxy answers (a *wire.ProfileSwitchError when it can not, and the
	// switch stays off), off stops it.
	SetOn(ctx context.Context, on bool) error
	// Ready: on, the vendor CLI signed in, and the proxy answers or can be started again.
	Ready() bool
	// Endpoint is where Claude Code sends its requests and the file of the key it sends; ok is false while the switch
	// is off or the proxy has never had an address.
	Endpoint() (baseURL, keyFile string, ok bool)
}

Switch is a profile that runs on a local proxy the runtime keeps instead of a key (Preset.Switched): the person turns it on and off, and while it is on Claude Code is pointed at the proxy.

type Target added in v0.16.86

type Target struct {
	Profile string `json:"profile"`
	Model   string `json:"model"`
}

Target is a model of a vendor profile a turn can go to.

type Tier added in v0.16.86

type Tier string

Tier is how much a turn needs.

const (
	TierHeavy Tier = "heavy"
	TierLight Tier = "light"
)

type VendorModel

type VendorModel struct {
	ID   string `json:"id"`
	Name string `json:"name,omitempty"`
}

VendorModel is a model as the vendor lists it.

func ParseVendorModels

func ParseVendorModels(raw []byte) []VendorModel

ParseVendorModels reads an OpenAI- or Anthropic-style list: {"data":[{"id":…,"display_name"?:…}]}.

Jump to

Keyboard shortcuts

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