provider

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 129 Imported by: 1 module, 0 packages

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

Documentation

Overview

Package provider resolves model routes and speaks every supported inference wire protocol

Index

Constants

View Source
const (
	// AccountUsageRefreshAfter is the minimum gap between refresh tries of one usage slot
	AccountUsageRefreshAfter = 120 * time.Second
	// AccountUsageSnapshotStaleAfter is the age past which a snapshot no longer renders as a live gauge
	AccountUsageSnapshotStaleAfter = 15 * time.Minute
)
View Source
const (
	CodexOAuthAuthorizeURL   = "https://auth.openai.com/oauth/authorize"
	CodexOAuthBrowserScope   = "openid profile email offline_access"
	CodexBrowserCallbackPort = 1455
	CodexBrowserCallbackPath = "/auth/callback"
	CodexBrowserCallbackWait = 300 * time.Second
	CodexBrowserPortBusyCode = "codex_browser_port_busy"
)
View Source
const (
	AuthStoreVersion             = 1
	AuthLockTimeout              = 15 * time.Second
	AccessTokenRefreshSkew       = 120 * time.Second
	DeviceAuthPollIntervalCap    = 1 * time.Second
	DeviceCodeGrantType          = "urn:ietf:params:oauth:grant-type:device_code"
	DefaultCodexBaseURL          = "https://chatgpt.com/backend-api/codex"
	DefaultXAIOAuthBaseURL       = "https://api.x.ai/v1"
	MinimaxOAuthClientID         = "78257093-7e40-4613-99e0-527b14b39113"
	MinimaxOAuthScope            = "group_id profile model.completion"
	MinimaxOAuthGrantType        = "urn:ietf:params:oauth:grant-type:user_code"
	MinimaxOAuthGlobalBase       = "https://api.minimax.io"
	MinimaxOAuthCNBase           = "https://api.minimaxi.com"
	MinimaxOAuthGlobalInference  = "https://api.minimax.io/anthropic"
	MinimaxOAuthCNInference      = "https://api.minimaxi.com/anthropic"
	MinimaxOAuthRefreshSkew      = 60 * time.Second
	DefaultQwenBaseURL           = "https://portal.qwen.ai/v1"
	DefaultOllamaCloudBaseURL    = "https://ollama.com/v1"
	DefaultActualBaseURL         = "https://api.actual.inc/v1"
	DefaultActualLocalBaseURL    = "http://127.0.0.1:8080/v1"
	StepfunStepPlanIntlBaseURL   = "https://api.stepfun.ai/step_plan/v1"
	StepfunStepPlanCNBaseURL     = "https://api.stepfun.com/step_plan/v1"
	CodexOAuthClientID           = "app_EMoamEEZ73f0CkXaXp7hrann"
	CodexOAuthTokenURL           = "https://auth.openai.com/oauth/token"
	CodexAccessTokenRefreshSkew  = 120 * time.Second
	XAIOAuthIssuer               = "https://auth.x.ai"
	XAIOAuthDiscoveryURL         = XAIOAuthIssuer + "/.well-known/openid-configuration"
	XAIOAuthClientID             = "b1a00492-073a-47ea-816f-4c329264a828"
	XAIOAuthScope                = "openid profile email offline_access grok-cli:access api:access"
	XAIOAuthDeviceCodeURL        = XAIOAuthIssuer + "/oauth2/device/code"
	XAIAccessTokenRefreshSkew    = 3600 * time.Second
	QwenOAuthClientID            = "f0304373b74a44d2b584a3fb70ca9e56"
	QwenOAuthTokenURL            = "https://chat.qwen.ai/api/v1/oauth2/token"
	QwenAccessTokenRefreshSkew   = 120 * time.Second
	OpenRouterAuthURL            = "https://openrouter.ai/auth"
	OpenRouterAuthKeysURL        = "https://openrouter.ai/api/v1/auth/keys"
	OpenRouterOAuthDocsURL       = "https://openrouter.ai/docs/guides/overview/auth/oauth"
	LMStudioNoAuthPlaceholder    = "dummy-lm-api-key"
	ActualLocalNoAuthPlaceholder = "dummy-actual-local-api-key"
	CodexRateLimitedCode         = "codex_rate_limited"
)
View Source
const (
	PreAuxiliaryCall  = "pre_auxiliary_call"
	PostAuxiliaryCall = "post_auxiliary_call"
)
View Source
const (
	DefaultCatalogTTLMinutes = 20.0
	DefaultCatalogTTLHours   = DefaultCatalogTTLMinutes / 60.0
	DefaultCatalogTimeout    = 8 * time.Second
	// CatalogFetchRetryDelay keeps a failed URL unasked in this process after a fetch with nothing cached
	CatalogFetchRetryDelay  = 300 * time.Second
	SupportedCatalogVersion = 1
)
View Source
const (
	TimeoutPhaseConnect = "connect"
	TimeoutPhaseRead    = "read"
	TimeoutPhaseWrite   = "write"
	TimeoutPhasePool    = "pool"
)

Transport timeout phases an adapter may stamp on an error

View Source
const (
	// Set to off after a repeat invalid_encrypted_content 400 to stop replaying encrypted reasoning
	CodexReasoningReplayOffKey = "codex_reasoning_replay"
	// Set to off after a context_management rejection to stop native compaction for the session
	CodexNativeCompactionOffKey = "codex_native_compaction"
	// Truthy when a trusted proxy implements OpenAI native compaction
	CodexTrustedProxyCompactionKey = "openai_native_compaction"
	// Local compressor trigger in tokens that bounds the native compact threshold
	CompressionTriggerTokensKey = "compression_trigger_tokens"
)

Request metadata keys the agent sets to steer a Codex Responses call

View Source
const (
	CodexMigrationMarker    = "# managed by icebath-agent — `icebath codex-runtime migrate` regenerates this section"
	CodexMigrationEndMarker = "# end icebath-agent managed section"
)

Marker comments wrapping the managed section of codex config.toml so a rerun replaces only its own text

View Source
const (
	CodexTTFBTimeoutEnv       = "ICEBATH_CODEX_TTFB_TIMEOUT_SECONDS"
	CodexEventStaleTimeoutEnv = "ICEBATH_CODEX_EVENT_STALE_TIMEOUT_SECONDS"
	CodexTTFBDisableAboveEnv  = "ICEBATH_CODEX_TTFB_DISABLE_ABOVE_TOKENS"
	CodexTTFBStrictEnv        = "ICEBATH_CODEX_TTFB_STRICT"
	CodexTTFBMaxEnv           = "ICEBATH_CODEX_TTFB_MAX_SECONDS"
	CodexHardTimeoutEnv       = "ICEBATH_CODEX_HARD_TIMEOUT_SECONDS"
	APICallStaleTimeoutEnv    = "ICEBATH_API_CALL_STALE_TIMEOUT"
)

Environment knobs of the Codex stream watchdogs

View Source
const (
	HighEffortSilenceFloorSeconds    = 300.0
	CodexFirstProgressTimeoutSeconds = 300.0
)

Silence floor for high effort reasoning and the first progress grace of large Codex requests

View Source
const (
	CredentialSourceEntraID      = "entra-id"
	CredentialSourceVertexOAuth  = "vertex-oauth"
	CredentialSourceMinimaxOAuth = "minimax-oauth"
)

Credential source tags for callable keys that mint a bearer on first use

View Source
const (
	IronProxyMgmtKeyEnv = "ICEBATH_IRON_PROXY_MGMT_KEY"

	DefaultIronTunnelPort = 9090
	IronProxyNonceEnv     = "ICEBATH_IRON_PROXY_NONCE"
)
View Source
const (
	SpeedFloorTokS       = 6.0
	TargetWindow         = 144 * 1024
	RuntimeOverheadBytes = int64(1.5 * (1 << 30))
	DefaultUbatch        = 512
	PrefillUbatch        = 2048
)
View Source
const (
	GrowthActionGrow     = "grow"
	GrowthActionHold     = "hold"
	GrowthActionCompress = "compress-default"
)

Growth verdict actions

View Source
const (
	GGMLDeviceGPU  = 1
	GGMLDeviceIGPU = 2
)

Device types of enum ggml_backend_dev_type in ggml-backend.h

View Source
const (
	TouchPrompt = "Reply with exactly one word: the capital of France."
	TouchExpect = "paris"
)

Touch generation prompt and the token its answer must carry, the readiness proof of a router child

View Source
const (
	// MoAMarkerPrefix starts a hidden one shot MoA turn message
	MoAMarkerPrefix = "__ICEBATH_MOA_TURN_V1__"
	// DefaultMoAPresetName names the preset a legacy flat MoA config becomes
	DefaultMoAPresetName = "default"
)
View Source
const (
	ModelSwitchErrOnceWithGlobal     = "once_with_global"
	ModelSwitchErrOnceRequiresTarget = "once_requires_target"
	ModelSwitchErrBadReasoning       = "bad_reasoning"
	ModelSwitchErrResetWithFlags     = "reset_with_flags"
)

Error codes a model command request can carry

View Source
const (
	// Recent exchanges preserved verbatim when compress here has no explicit count
	DefaultKeepLast = 2
	// Ceiling a fat fingered keep count clamps to instead of turning the split into a no op
	MaxKeepLast = 100
)
View Source
const (
	StatusOK        = "ok"
	StatusExhausted = "exhausted"
	// Terminal failure that never recovers on its own, cleared only by a write side re-auth sync
	StatusDead = "dead"

	// Locally generated terminal reason for a rotated pair that never reached its store
	CredentialPersistFailedReason = "credential_persist_failed"
	// Quiet window after which a DEAD manual entry is pruned
	DeadManualPruneTTL = 24 * time.Hour

	AuthTypeOAuth = "oauth"

	SourceManual           = "manual"
	SourceManualDeviceCode = SourceManual + ":device_code"

	StrategyFillFirst  = "fill_first"
	StrategyRoundRobin = "round_robin"
	StrategyRandom     = "random"
	StrategyLeastUsed  = "least_used"

	ExhaustedTTL401            = 5 * time.Minute
	ExhaustedTTL429            = time.Hour
	ExhaustedTTLDefault        = time.Hour
	ExhaustedTTLSoleCredential = time.Minute

	FailureReasonBilling           = "billing"
	FailureReasonBillingUnverified = "billing_unverified"
	// Usage window plan limit that benches only the refused model
	FailureReasonUsageWindow = "usage_window"
	// Codex model entitlement bench that only an explicit reset clears
	ModelEntitlementBench = 365 * 24 * time.Hour

	NoAvailableEntriesLogThrottle     = 60 * time.Second
	CustomPoolPrefix                  = "custom:"
	DefaultMaxConcurrentPerCredential = 1
)
View Source
const (
	AuthTypeAPIKey          = "api_key"
	AuthTypeOAuthDeviceCode = "oauth_device_code"
	AuthTypeOAuthExternal   = "oauth_external"
	AuthTypeOAuthMiniMax    = "oauth_minimax"
	AuthTypeExternalProcess = "external_process"
	AuthTypeAWSSDK          = "aws_sdk"
	AuthTypeVertex          = "vertex"
	AuthTypeVirtual         = "virtual"
)

Auth_type literals a profile declares

View Source
const (
	OpenRouterBaseURL     = home.OpenRouterBaseURL
	CodexBaseURL          = "https://chatgpt.com/backend-api/codex"
	OpenAIBaseURL         = "https://api.openai.com/v1"
	AnthropicBaseURL      = "https://api.anthropic.com"
	QwenBaseURL           = "https://portal.qwen.ai/v1"
	XAIBaseURL            = "https://api.x.ai/v1"
	LMStudioBaseURL       = "http://127.0.0.1:1234/v1"
	OllamaCloudBaseURL    = "https://ollama.com/v1"
	ActualBaseURL         = "https://api.actual.inc/v1"
	StepFunIntlBaseURL    = "https://api.stepfun.ai/step_plan/v1"
	MiniMaxOAuthBaseURL   = "https://api.minimax.io/anthropic"
	MiniMaxOAuthCNBaseURL = "https://api.minimaxi.com/anthropic"
	RouterBaseURL         = "https://api.router.com/v1"
	MoaBaseURL            = "moa://local"
	MoaAPIKey             = "moa-virtual-provider"
	NoKeyPlaceholder      = "no-key-required"
)

Canonical default endpoints shared by resolution and the profile table

View Source
const (
	DefaultProxyPort = 8645
	DefaultProxyHost = "127.0.0.1"
)
View Source
const (
	DefaultSecretFetchTimeout = 120 * time.Second
	DefaultSecretCLITimeout   = 30 * time.Second
)
View Source
const (
	HostedChoice    = "choice"
	HostedChecklist = "checklist"
	HostedText      = "text"
	HostedSecret    = "secret"
	HostedCommand   = "command"
)

Kinds of question a hosted setup flow puts to its host

View Source
const (
	QwenOAuthDeviceCodeURL = "https://chat.qwen.ai/api/v1/oauth2/device/code"
	QwenOAuthScope         = "openid profile email model.completion"
)

Device authorization endpoint and scope of the Qwen account sign in the Qwen CLI uses

View Source
const (
	SpotifyProvider               = "spotify"
	SpotifyDefaultAccountsBaseURL = "https://accounts.spotify.com"
	SpotifyDefaultAPIBaseURL      = "https://api.spotify.com/v1"
	SpotifyDefaultRedirectURI     = "http://127.0.0.1:43827/spotify/callback"
	SpotifyHelpCommand            = "icebath spotify --help"
	SpotifyDashboardURL           = "https://developer.spotify.com/dashboard"
	// Seconds before expiry a runtime read refreshes the access token
	SpotifyAccessTokenRefreshSkewSeconds = 120
)
View Source
const (
	BarWidth = 10
	BarFill  = "|"
	BarEmpty = " "
)

Usage bar geometry, cells and the basis points of a full allowance

View Source
const (
	XAIMigrationGuideURL = "https://docs.x.ai/developers/migration/may-15-retirement"
	XAIRetirementDate    = "May 15, 2026"
)
View Source
const (

	// AIGatewayBaseURL is the Vercel AI Gateway OpenAI compatible root
	AIGatewayBaseURL = home.AIGatewayBaseURL
)
View Source
const APITimeoutEnv = "ICEBATH_API_TIMEOUT"

Env var for the overall request timeout in seconds

View Source
const AuthLockTimeoutLead = "Timed out waiting for auth store lock"

Lead of the auth store lock timeout, read back from failure details by the TUI server

View Source
const AuxExplicitCancelCause = "explicit_host_cancel"

AuxExplicitCancelCause is the frozen cause every explicit auxiliary cancellation carries

View Source
const BedrockConverseIssuerType = "bedrock.native_assistant"

BedrockConverseIssuerType names the reasoning_details record stamping the model that minted a turn

View Source
const BedrockDefaultContextLength = 128_000

BedrockDefaultContextLength is the window of a Bedrock model no source knows

View Source
const BedrockGuardrailActionField = "amazon-bedrock-guardrailAction"

BedrockGuardrailActionField is the InvokeModel body field flagging a guardrail substitution

View Source
const CharsPerToken = tools.ModelCharsPerToken

Rough chars per token ratio for ASCII text

View Source
const CodexAccountModelEntitlementMarker = "model is not supported when using codex with a chatgpt account"

Codex ChatGPT account entitlement wording for a slug the account can never use

View Source
const CodexContextVariantSuffix = "-900k"

CodexContextVariantSuffix is the picker only opt in suffix never sent on the wire

View Source
const CodexModelsCatalogEndpoint = "https://chatgpt.com/backend-api/codex/models"

CodexModelsCatalogEndpoint is the hard coded Codex catalog

View Source
const CodexNewestClientVersion = "99.0.0"
View Source
const CodexQuotaProbeMinInterval = 300 * time.Second

CodexQuotaProbeMinInterval throttles the live Codex quota probe per access token

View Source
const CodexStreamStallMarker = "stream stalled"

Text the context compressor reads as a retry ladder timeout

View Source
const CodexToolsMCPServerEntry = "__icebath_tools_mcp_server__"

CodexToolsMCPServerEntry is the argv[1] that turns the icebath binary into the tools MCP server

View Source
const CodexToolsMCPServerName = "icebath-tools"

CodexToolsMCPServerName is the mcp_servers key the runtime migration registers the icebath tools server under

View Source
const CodexUngatedClientVersion = "0.0.0"
View Source
const ContentPolicyNextSteps = "Try rewording your message or removing sensitive attachments, or switch to another model with /model."

Next step copy for a content policy block

View Source
const ContextFloor = 64 * 1024

The guaranteed and target window of every managed local model

View Source
const (

	// Display label source for a key minted by a command
	CredentialSourceKeyCmd = "key-cmd"
)
View Source
const (

	// DaybreakProgram is the cyber access program the Daybreak switch requests
	DaybreakProgram = "daybreak_blue"
)
View Source
const (
	// DeepinfraDefaultBaseURL is the OpenAI compatible DeepInfra root
	DeepinfraDefaultBaseURL = "https://api.deepinfra.com/v1/openai"
)
View Source
const DefaultCatalogURL = "https://icebath.app/api/model-catalog.json"

DefaultCatalogURL is the site copy of the shipped model catalog the refresh fetches

View Source
const DefaultContextCacheSwitchThreshold = 100_000

DefaultContextCacheSwitchThreshold is the context size above which a mid session switch asks first

View Source
const DefaultErrorBodyMaxBytes = 64 * 1024

Byte cap that holds any real provider error envelope while rejecting pathological bodies

View Source
const DefaultErrorBodyTimeout = 10 * time.Second

Hard deadline for the whole read, past it the connection is closed and the partial bytes kept

View Source
const DefaultFallbackContext = 256_000

DefaultFallbackContext is the window assumed when every detection source misses

View Source
const DefaultFastWindowSeconds = 60

Default bounded fast window length

View Source
const DefaultImageTokenCost = 1500

Flat per image token price before a route calibrates it from usage

View Source
const DefaultMTPDraftDepth = 3

The speculative draft depth launch flags use unless told otherwise

View Source
const DeviceCodeExpiredCode = "device_code_timeout"

DeviceCodeExpiredCode is the code a device code poller carries when the code ran out

View Source
const ExternalLoginsNotAdoptedNotice = "External CLI logins (Codex CLI, Claude Code) are not adopted: auth.adopt_external_logins is false. " +
	"Icebath uses only its own logins; run `icebath auth add <provider>` to add one."

ExternalLoginsNotAdoptedNotice is printed once per process when a borrowed CLI login is skipped

View Source
const (

	// ForkScopeSeparator joins a scope and a fork tag, doubled so single colon gateway keys never read as forks
	ForkScopeSeparator = "::"
)
View Source
const GeminiDefaultMaxOutputTokens = geminiDefaultMaxOutputTokens

GeminiDefaultMaxOutputTokens is the maxOutputTokens the native adapter sends when no cap is set

View Source
const HookCtxKey = hookCtxKey

Params key the agent request builder stores its turn context under for the profile hooks

View Source
const HookPayloadMaxCharsEnv = "ICEBATH_PLUGIN_PAYLOAD_MAX_CHARS"

Env var overriding the serialized hook payload cap, floor 1000 chars

View Source
const (
	IcebathPKCESource = "icebath_pkce"
)

Source label of the Anthropic OAuth file icebath writes, and the spelling older builds stored in auth.json

View Source
const (
	// IncludedNote marks a cost result that is covered by a subscription rather than a $0 rate card
	IncludedNote = "subscription-included; no provider invoice for usage"
)
View Source
const KimiCodeBaseURL = "https://api.kimi.com/coding"

Kimi Code endpoint selected by an sk-kimi- prefixed key

View Source
const LargeRequestHintBytes = 256 * 1024

LargeRequestHintBytes is the body size above which a refused connect may be a size limit

View Source
const LiveRetryWaitCap = 60 * time.Second

LiveRetryWaitCap is the wait a person feels so longer non rate limit waits are announced when they start

View Source
const LlamaIdleUnloadS = 15 * 60

Seconds a resident model may stay idle before the sweeper unloads it and frees its memory

View Source
const LlamacppProviderID = "llamacpp"

LlamacppProviderID is the managed llama.cpp runtime provider id the resolver and the picker Local row share

View Source
const LocalStreamStaleTimeoutEnv = "ICEBATH_LOCAL_STREAM_STALE_TIMEOUT"

Env var for the stale ceiling of a local endpoint in seconds

View Source
const MaxHistorySeedChars = 32_000

MaxHistorySeedChars caps the rendered history codex resends on every request of a fresh thread

View Source
const MinFragmentLength = 400

Fragments shorter than this are never judged for repetition

View Source
const MinimumContextLength = 64_000

MinimumContextLength is the smallest window sessions, model switches and cron jobs accept

View Source
const ModelSwitchResetToken = "reset"

ModelSwitchResetToken clears the session model override instead of naming a model

View Source
const ModelsDevURL = "https://models.dev/api.json"

ModelsDevURL is the live registry endpoint

View Source
const NearDeadlineSecs = 15.0

Seconds before a watchdog fires inside which the notice says still waiting and updates once

View Source
const OfflineSummary = "Icebath can't reach the model provider. You may be offline. Check your internet connection and try again."

OfflineSummary is the one line shown when the provider host cannot be resolved

View Source
const OneshotSource = "oneshot"

Source label of finite one shot runs

View Source
const OpenRouterModelsURL = home.OpenRouterModelsURL

OpenRouter catalog endpoint

View Source
const OpencodeSessionHeader = "x-opencode-session"

Header the OpenCode relay pins a conversation to one upstream backend with

View Source
const PartialStreamStubID = "partial-stream-stub"

Response id of a stream that ended without a finish reason after delivering content

View Source
const PleasantFloorTokS = 20.0

Predicted decode speed below which a model stops feeling pleasant for agentic use

View Source
const PreferredSilentDefaultModel = "z-ai/glm-5.3"

PreferredSilentDefaultModel is the offline fallback for the model landed on when the user never picked one

View Source
const ProviderStreamEmptyFrameCode = "provider_stream_empty_frame"

Error code of an SSE frame that carried no payload at all

View Source
const ProviderStreamEmptyFrameErrorCode = "provider_stream_empty_frame"

Same rejection with an empty payload so the session switches to non streaming

View Source
const ProviderStreamNonJSONCode = "provider_stream_non_json_data"

Error code of an SSE data frame that was not JSON

View Source
const ProviderStreamNonJSONErrorCode = "provider_stream_non_json_data"

Synthetic code for a stream data field rejected before any completion chunk arrived

View Source
const ReasoningCapsDiskTTL = reasoningCapsDiskTTL

ReasoningCapsDiskTTL is how long a disk mirrored catalog counts as fresh

View Source
const ReasoningFloorEffort = "low"

ReasoningFloorEffort is the lowest effort every reasoning wire accepts

View Source
const RepetitionLoopInterrupted = "[the reply degenerated into a repetition loop and was interrupted]"

Interrupt checkpoint text used instead of a repetition dominated partial

View Source
const RetryAfterCap = 600 * time.Second

RetryAfterCap rejects pathological provider waits while covering Anthropic Tier 1 bucket resets

View Source
const SDKDefaultTimeout = auxSDKDefaultTimeout

SDKDefaultTimeout is the OpenAI SDK default request timeout in seconds

View Source
const ScopeAIAzureDefault = "https://ai.azure.com/.default"

Default Entra scope for Azure AI Foundry

View Source
const SecretSourceAPIVersion = 1

SecretSourceAPIVersion gates plugin secret source compatibility

View Source
const SetupProviderHelp = "icebath model --help"

Help command the provider setup screen points to

View Source
const SnapshotOwnerKey = "custom_entry"

SnapshotOwnerKey is the primary runtime field holding the owning entry's provenance

View Source
const StopPathMinChars = 16000

Stop path scale floor below which asked for repeats are delivered

View Source
const StreamReadTimeoutEnv = "ICEBATH_STREAM_READ_TIMEOUT"

Env var for the socket read timeout of a streaming request in seconds

View Source
const StreamStaleTimeoutEnv = "ICEBATH_STREAM_STALE_TIMEOUT"

Env var for the stale stream detector base in seconds

View Source
const ToolCallContract = "Available tools (OpenAI function schema). " +
	"When using a tool, emit ONLY <tool_call>{...}</tool_call> with one JSON object " +
	"containing id/type/function{name,arguments}. arguments must be a JSON string."

Prompt rule telling an ACP agent how to emit the tool calls parsed back out of its text

View Source
const ToolStreamingBeta = anthToolStreamingBeta

Anthropic beta that enables fine grained tool streaming, added for Claude over OpenRouter

View Source
const (
	TurnAuthorEnvName = "ICEBATH_TURN_AUTHOR"
)
View Source
const UsageAnchorModelConfigKey = "_usage_anchor"

UsageAnchorModelConfigKey is the session model config key holding the persisted usage anchor

View Source
const XAIEntitlementHint = " — xAI rejected this OAuth account. NOTE: X Premium+ does NOT " +
	"include xAI API access — only standalone SuperGrok subscribers " +
	"can use this provider. Other possible causes: no Grok " +
	"subscription, your tier doesn't include this model, or your " +
	"quota is exhausted. Check https://grok.com/?_s=usage to see " +
	"which, or run `/model` to switch providers."

XAIEntitlementHint is appended to xAI's permission denied body so Premium+ holders learn why

Variables

View Source
var (
	// One tagged tool call block with its JSON body as group one
	ToolCallBlockRe = pyre.MustCompile(`(?s)<tool_call>\s*(\{.*?\})\s*</tool_call>`)
	// One bare OpenAI shaped tool call JSON object
	ToolCallJSONRe = pyre.MustCompile(`(?s)\{\s*\"id\"\s*:\s*\"[^\"]+\"\s*,\s*\"type\"\s*:\s*\"function\"\s*,\s*\"function\"\s*:\s*\{.*?\}\s*\}`)
)
View Source
var (
	ResponsesBypassFields       = []string{"input", "tools"}
	ChatCompletionsBypassFields = []string{"messages", "tools"}
)
View Source
var (
	ChromiumExecutable      func(env *tools.Env, allowOverride bool) string
	FasterWhisperImportable func() bool
)

Local stack probes pkg/browser and pkg/media install at init, each accessor panics when its owner never linked

View Source
var AcceptedImageMIMEs = map[string]bool{"image/png": true, "image/jpeg": true}

Image formats the managed server's stb_image decoder handles, anything else is transcoded first

View Source
var AgentImportRunner func(ctx context.Context, icebathHome string, opts AgentImportOptions, console *cliui.Console) (int, error)

AgentImportRunner runs icebath import-agent in process against the home on the console, installed by the binary wiring

View Source
var AgentImportersInstaller func(ctx context.Context, icebathHome string, present bool, out io.Writer) error

AgentImportersInstaller installs the plugin enabled in the home, or only enables it when present, installed by the binary wiring

View Source
var AuxRouteKeys = auxRouteKeys

Exported auxiliary route fields that travel as one unit

View Source
var BackendPackages = map[string]string{
	"cuda":   "llamacpp-cuda",
	"vulkan": "llamacpp-vulkan",
	"metal":  "llamacpp-metal",
	"hip":    "llamacpp-hip",
	"cpu":    "llamacpp-cpu",
}
View Source
var BedrockCachePointPlacements = []string{"tools", "system", "messages"}

BedrockCachePointPlacements lists the Converse sections a cachePoint marker can sit in

View Source
var BedrockGeoPrefixes = []string{"us.", "eu.", "ap.", "apac.", "jp.", "ca.", "sa.", "me.", "af."}

BedrockGeoPrefixes are the cross region inference profile prefixes that route only from their own geography

View Source
var BedrockOpenAIResponsesModelIDs = []string{
	"openai.gpt-6-astra", "openai.gpt-6.1-sol", "openai.gpt-6-sol", "openai.gpt-6-luna",
	"openai.gpt-5.5", "openai.gpt-5.6-sol", "openai.gpt-5.6-terra", "openai.gpt-5.6-luna",
}

BedrockOpenAIResponsesModelIDs are the bare in region OpenAI ids Mantle serves

View Source
var BoundedFastModes = map[string]bool{"auto": true, "cold": true}

Service tiers that open a bounded window per user turn or per session start

View Source
var BuildVersion = "dev"

Release string stamped into user agents and attribution tags, set by the build

View Source
var CodexLoginFlows = []string{"device_code", "browser"}

CodexLoginFlows are the login flows auth.codex_login_flow may name

View Source
var CodexMinVersion = [3]int{0, 125, 0}

CodexMinVersion is the oldest codex CLI the app server runtime accepts

View Source
var CodexTierWords = map[string]string{"priority": "fast"}

Codex app server names for the wire tiers it accepts

View Source
var CodexValidRuntimes = []string{"auto", "codex_app_server"}

Runtimes the codex runtime switch accepts

View Source
var DefaultBackoff = BackoffOptions{BaseDelay: 5 * time.Second, MaxDelay: 120 * time.Second, JitterRatio: 0.5}

DefaultBackoff matches the 5s base, 120s cap, half jitter schedule

View Source
var DefaultCatalogFallbackURLs = []string{
	"https://raw.githubusercontent.com/nickheyer/icebath/main/pkg/provider/model-catalog.json",
}

DefaultCatalogFallbackURLs hold the same manifest at its repository path

View Source
var DefaultCodexModels = []string{
	"gpt-6-sol",
	"gpt-6-luna",
	"gpt-5.6-sol",
	"gpt-5.6-terra",
	"gpt-5.6-luna",
	"gpt-5.5",
	"gpt-5.4-mini",
	"gpt-5.4",
	"gpt-5.3-codex-spark",
}

DefaultCodexModels is the curated offline Codex catalog, only slugs the ChatGPT OAuth backend accepts

View Source
var DefaultHookJSONCaps = HookJSONCaps{MaxDepth: 8, MaxString: 8000, MaxSequence: 200}

DefaultHookJSONCaps matches depth 8, 8000 char strings, and 200 item sequences

View Source
var DefaultIronAllowedHosts = []string{
	"openrouter.ai", "*.openrouter.ai", "api.openai.com", "api.anthropic.com", "generativelanguage.googleapis.com",
	"api.x.ai", "api.mistral.ai", "api.groq.com", "api.together.xyz", "api.deepseek.com",
}

Hosts allowed by default for AI inference traffic

View Source
var DefaultIronUpstreamDenyCIDRs = []string{
	"127.0.0.0/8", "::1/128", "169.254.0.0/16", "fe80::/10", "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7",
	"::ffff:0:0/96", "100.64.0.0/10", "198.18.0.0/15",
}

Default SSRF deny list refused regardless of the allowlist

View Source
var DefaultProbePorts = []int{8080}

Ports probed for a llama-server beside the managed and configured ones, always on 127.0.0.1

View Source
var DeveloperRoleModels = []string{"gpt-5", "codex"}

DeveloperRoleModels are model name substrings whose system prompt is sent under the developer role

View Source
var DirectAliases = NewDirectAliasTable()

DirectAliases holds the builtin plus active profile aliases, reloaded in place when the profile config changes

View Source
var DoneSSEFrame = []byte("data: [DONE]\n\n")

DoneSSEFrame is the terminal sentinel strict OpenAI clients expect at the end of a stream

View Source
var DumpBlockedLoop = dumpBlockedLoopDiagnostics

Diagnostics dump of a dispatch goroutine that never processed its expiry, the stack dumper in production

View Source
var ErrNoAWSCredentials = errors.New("Unable to locate credentials")

ErrNoAWSCredentials is the chain walked to the end without any source answering

View Source
var ErrSecretPromptInterrupted = errors.New("KeyboardInterrupt")

ErrSecretPromptInterrupted is the Ctrl+C a masked secret prompt raises as KeyboardInterrupt

View Source
var ErrStreamStalled = errors.New(CodexStreamStallMarker)

Main model stream that stopped producing chunks after it had started

View Source
var ExternalLoginProviders = map[string]bool{"anthropic": true, "openai-codex": true}

ExternalLoginProviders are the providers whose sibling CLI login icebath may borrow

View Source
var FastArgAliases = map[string]string{"ultra": "ultrafast"}

Typed /fast shorthands to the canonical word

View Source
var GGUFSplitPartRE = regexp.MustCompile(`-(\p{Nd}{5})-of-(\p{Nd}{5})\.gguf\n?\z`)

Matches the split suffix "-00001-of-00003.gguf" and captures part and total

View Source
var GatewayHooks struct {
	LegacyJSON            func(h string) map[string]any
	BridgedAllowAllUsers  func() (string, bool)
	MergePlatformSections func(yamlCfg map[string]any, gatewayBlock any, gwData map[string]any, also []string) map[string]any
	PlatformEnabled       func(block map[string]any) (bool, string)
	ServesHome            func(h string) bool
}

Gateway functions provider reads, installed by the gateway package at init, each answering for no gateway while unset

View Source
var GetModelContextLength func(ctx context.Context, req ContextLengthRequest) int

GetModelContextLength resolves the window through config, caches, probes, catalogs and defaults

View Source
var ImportSources = []ImportSource{
	{Name: "openclaw", Label: "OpenClaw", Dirs: []string{".openclaw", ".clawdbot", ".moltbot"}, SetupSecrets: true},
	{Name: "claude-code", Label: "Claude Code", Dirs: []string{".claude"}},
	{Name: "codex", Label: "Codex CLI", Dirs: []string{".codex"}},
	{Name: "cursor", Label: "Cursor", Dirs: []string{".cursor"}},
	{Name: "grok-bot", Label: "Grok Bot", Dirs: []string{"Library/Application Support/Grok Bot", "/Applications/Grok Bot.app",
		"Applications/Grok Bot.app", ".config/Grok Bot", "AppData/Roaming/Grok Bot", "AppData/Local/Programs/Grok Bot"},
		Exports: []string{"Downloads/grok-bot-export*"}},
	{Name: "openbot", Label: "OpenBot", Dirs: []string{"Library/Application Support/OpenBot", ".config/OpenBot", "AppData/Roaming/OpenBot", "OpenBot/Agents"}},
}

ImportSources lists the native importers with the dirs their own auto detection checks

View Source
var LeftCoreTerminalKeys = map[string]string{"terminal.singularity_image": "TERMINAL_SINGULARITY_IMAGE"}

Terminal config keys the built in singularity backend reads mapped to the env copy core also wrote

View Source
var LlamacppAliases = map[string]bool{"llamacpp": true, "llama.cpp": true, "llama-cpp": true}

Provider names that route to the managed llama.cpp server

View Source
var LoopBlockedDumpGrace = 5 * time.Second

Grace after a deadline fires before the blocked worker is reported

View Source
var LoopbackHosts = []string{"127.0.0.1", "localhost", "::1"}

LoopbackHosts must never be dialed through a proxy

View Source
var MaxSafeTimeout = func() time.Duration {
	if runtime.GOOS == "windows" {
		return time.Duration((0xFFFFFFFF - 1000) / 1000.0 * float64(time.Second))
	}
	return 365 * 24 * time.Hour
}()

Longest wait handed to any platform primitive, a year off Windows and the DWORD millisecond cap on it

View Source
var ModelAliases = map[string]ModelIdentity{
	"sonnet":   {"anthropic", "claude-sonnet"},
	"opus":     {"anthropic", "claude-opus"},
	"haiku":    {"anthropic", "claude-haiku"},
	"claude":   {"anthropic", "claude"},
	"gpt5":     {"openai", "gpt-5"},
	"gpt":      {"openai", "gpt"},
	"codex":    {"openai", "codex"},
	"o3":       {"openai", "o3"},
	"o4":       {"openai", "o4"},
	"gemini":   {"google", "gemini"},
	"deepseek": {"deepseek", "deepseek-chat"},
	"grok":     {"x-ai", "grok"},
	"llama":    {"meta-llama", "llama"},
	"qwen":     {"qwen", "qwen"},
	"minimax":  {"minimax", "minimax"},
	"nemotron": {"nvidia", "nemotron"},
	"kimi":     {"moonshotai", "kimi"},
	"glm":      {"z-ai", "glm"},
	"step":     {"stepfun", "step"},
	"mimo":     {"xiaomi", "mimo"},
	"trinity":  {"arcee-ai", "trinity"},
}

ModelAliases maps short names to a vendor and family resolved against the live catalog

View Source
var ModelSwitchErrorText = map[string]string{
	ModelSwitchErrOnceWithGlobal:     "/model --once cannot be combined with --global",
	ModelSwitchErrOnceRequiresTarget: "/model --once requires a model or provider.",
	ModelSwitchErrBadReasoning:       "/model --reasoning takes none, minimal, low, medium, high, xhigh, max or ultra.",
	ModelSwitchErrResetWithFlags: "/model reset takes no flags — it clears this session's model override so the " +
		"configured default applies again.",
}

ModelSwitchErrorText is the surface neutral copy for each model command error code

View Source
var NetworkResolutionMarkers = []string{
	"temporary failure in name resolution", "name or service not known",
	"nodename nor servname provided, or not known", "getaddrinfo failed",
	"no address associated with hostname", "network is unreachable",
	"no such host", "server misbehaving",
}

Offline DNS failure wording that transports wrap in a generic connection error

View Source
var NewCopilotACPClient func(ctx context.Context, clientKwargs map[string]any) (CopilotACPChatClient, error)

Builder of the Copilot CLI ACP client, installed by the acpclient package at init

View Source
var NormalTierWords = map[string]bool{"": true, "normal": true, "default": true, "standard": true, "off": true, "none": true}

Words that mean the normal tier

View Source
var OAuthProviderFlows map[string]OAuthProviderFlow

OAuthProviderFlows is the registry of built in OAuth providers, filled at init so the pool tables can name its predicates

View Source
var OpenRouterModels = func() []CatalogModel {
	out := make([]CatalogModel, 0, len(openRouterModelIDs))
	for _, mid := range openRouterModelIDs {
		desc, ok := openRouterDescriptions[mid]
		if !ok && strings.HasSuffix(mid, ":free") {
			desc = "free"
		}
		out = append(out, CatalogModel{ID: mid, Description: desc})
	}
	return out
}()

OpenRouterModels is the fallback OpenRouter snapshot used when the live catalog is unavailable

View Source
var PluginAuthActions = []string{"add", "status", "logout", "refresh"}

Auth actions a provider plugin's auth handler can own

View Source
var PluginUsageHookDeadline = 10 * time.Second

Wall clock bound on a plugin profile account usage hook, shared by every usage surface

View Source
var PostToDispatch = func(fn func()) { fn() }

Hands an expiry callback to the waiting dispatch goroutine, run at once in production where the waiter selects on it

View Source
var ProviderStreamParseMarkers = []string{
	"expected ident at line", "expected value at line", "eof while parsing a value at line",
	"eof while parsing a string at line", "eof while parsing a list at line", "eof while parsing an object at line",
	"key must be a string at line", "trailing characters at line", "trailing comma at line",
	"expected `,` or `}` at line", "expected `,` or `]` at line", "expected `:` at line",
	"invalid escape at line", "invalid number at line", "found while parsing a string at line",
}

Substrings of the SSE JSON parser error for a truncated or corrupted event stream frame

View Source
var ProxyEnvKeys = []string{"HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "https_proxy", "http_proxy", "all_proxy"}

ProxyEnvKeys are the proxy variables read in order, both casings

View Source
var RateLimitFailoverReasons = map[FailoverReason]bool{ReasonRateLimit: true, ReasonBilling: true, ReasonUpstreamRateLimit: true}

Failover reasons that leave the primary rate limited and so arm its cooldown

View Source
var RefreshableOAuthProviders = map[string]bool{"anthropic": true, "openai-codex": true, "xai-oauth": true}

RefreshableOAuthProviders are the built in providers whose pooled OAuth rows the pool can refresh

View Source
var RegistryAuthTypeArms = map[string]auxRegistryArm{
	"vertex":            auxResolveVertexArm,
	"aws_sdk":           auxResolveBedrockArm,
	"oauth_minimax":     auxResolveMinimaxOAuthArm,
	"oauth_device_code": auxResolvePluginOAuthArm,
	"oauth_external":    auxResolvePluginOAuthArm,
}

RegistryAuthTypeArms maps a registered auth type to the arm that builds and routes its client

Reasons the retry loop keeps retrying with backoff before any fallback cascade

View Source
var RunGitWithCredentialFallback = gitcred.RunGitWithCredentialFallback

Runs a git network verb anonymously, then with each credential the user owns for the remote host

View Source
var SanitizeOutboundKwargsHook func(agent any, apiKwargs map[string]any)

Agent outbound kwargs sweep the agent package installs at init, run on hand built summary kwargs

View Source
var ServiceTierWords = map[string]string{
	"fast": "priority", "priority": "priority", "on": "priority",
	"ultrafast": "ultrafast", "ultra": "ultrafast", "auto": "auto", "cold": "cold",
}

User or config word to stored service tier

View Source
var SingleUseOAuthSingletonFiles = []string{".anthropic_oauth.json"}

SingleUseOAuthSingletonFiles hold single use grants outside auth.json and must never be copied into a profile

View Source
var SingleUseRefreshPoolProviders = map[string]bool{"anthropic": true, "openai-codex": true, "xai-oauth": true}

SingleUseRefreshPoolProviders rotate a single use refresh token on every refresh

View Source
var SpotifyDefaultScope = strings.Join([]string{
	"user-modify-playback-state", "user-read-playback-state", "user-read-currently-playing",
	"user-read-recently-played", "playlist-read-private", "playlist-read-collaborative",
	"playlist-modify-public", "playlist-modify-private", "user-library-read", "user-library-modify",
}, " ")

SpotifyDefaultScope is every scope the seven Spotify tools need, space separated

View Source
var StaticTiers = map[string]bool{"priority": true, "ultrafast": true}

Tiers sent on every request of the session

View Source
var StrayToolCallCloserPattern = regexp2.MustCompile(`</(?:`+toolTagNSPrefix+`(?:`+toolCallTagAlt+`|function))>\s*`, regexp2.IgnoreCase)

Orphan tool call or function closing tag with the whitespace after it

View Source
var StreamDiagHeaders = []string{
	"cf-ray", "cf-cache-status", "x-openrouter-provider", "x-openrouter-model", "x-openrouter-id",
	"x-request-id", "x-vercel-id", "via", "server", "x-forwarded-for",
}

StreamDiagHeaders lists the lowercased upstream headers captured per attempt

View Source
var StripImagesForRejectingModelHook func(agent any, apiMessages *[]any) bool

Agent per model image strip the agent package installs at init, true when an image part was removed

View Source
var SwitchModel = switchModel

SwitchModel routes, resolves credentials for and validates a model switch shared by the CLI and gateway

View Source
var ThinkStripPatterns = func() []*regexp2.Regexp {
	const dotallNoCase = regexp2.Singleline | regexp2.IgnoreCase
	var out []*regexp2.Regexp
	for _, name := range ThinkTagNames {
		out = append(out, regexp2.MustCompile(`<`+name+`>.*?</`+name+`>`, dotallNoCase))
	}
	for _, name := range strings.Split(toolCallTagAlt, "|") {
		out = append(out, regexp2.MustCompile(`<`+toolTagNSPrefix+name+`\b[^>]*>.*?</`+toolTagNSPrefix+name+`>`, dotallNoCase))
	}
	return append(out,
		regexp2.MustCompile(`(?:(?<=^)|(?<=[\n\r.!?:]))[ \t]*<function\b[^>]*\bname\s*=[^>]*>(?:(?:(?!</function>).)*)</function>`, dotallNoCase),
		regexp2.MustCompile(`(?:^|\n)[ \t]*<(?:`+strings.Join(ThinkTagNames, "|")+`)\b[^>]*>.*$`, dotallNoCase),
		regexp2.MustCompile(`</?(?:`+strings.Join(ThinkTagNames, "|")+`)>\s*`, regexp2.IgnoreCase),
		StrayToolCallCloserPattern,
		UnterminatedToolCallPattern,
	)
}()

Ordered strip passes of closed pairs, tool call blocks, named functions, unterminated and orphan tags, stray closers

View Source
var ThinkTagNames = []string{"think", "thinking", "reasoning", "thought", "REASONING_SCRATCHPAD", "思考", "反思", "推理", "推敲"}

Reasoning tag names every surface hides

View Source
var UITransportSources = map[string]bool{"tui": true}

Interactive UI transport labels a one shot child inherits but does not belong to

View Source
var UnsupportedParamMarkers = []string{
	"unsupported parameter", "unsupported_parameter", "not supported", "does not support",
	"doesn't support", "is deprecated for this model",
	"unknown parameter", "unrecognized request argument", "unrecognized parameter",
	"invalid parameter", "extra inputs are not permitted",
	"invalid option: expected one of",
}

Generic markers a provider 400 puts next to the offending parameter name

View Source
var UnterminatedToolCallPattern = regexp2.MustCompile(`(?:^|\n)[ \t]*<`+toolTagNSPrefix+`(?:`+toolCallTagAlt+`)\b[^>]*>.*$`+
	`|(?:^|\n)[ \t]*[\w.:-]*</?arg_(?:key|value)\b[^\n]*`+
	`|(?:^|\n)[^\n<]*</arg_(?:key|value)>[ \t\r]*(?=\n|$)`, regexp2.Singleline|regexp2.IgnoreCase)

Tool call opened on its own line and never closed, and cut arg_key or arg_value lines

View Source
var VercelAIGatewayModels = func() []CatalogModel {
	out := []CatalogModel{{ID: "moonshotai/kimi-k2.6", Description: "recommended"}}
	for _, mid := range []string{
		"alibaba/qwen3.6-plus", "zai/glm-5.1", "minimax/minimax-m2.7", "anthropic/claude-sonnet-4.6",
		"anthropic/claude-opus-4.7", "anthropic/claude-opus-4.6", "anthropic/claude-haiku-4.5",
		"openai/gpt-5.4", "openai/gpt-5.4-mini", "openai/gpt-5.3-codex", "google/gemini-3.1-pro-preview",
		"google/gemini-3-flash", "google/gemini-3.1-flash-lite-preview", "xai/grok-4.20-reasoning",
	} {
		out = append(out, CatalogModel{ID: mid})
	}
	return out
}()

VercelAIGatewayModels is the fallback Vercel AI Gateway snapshot, open weight first then closed by family

View Source
var ZaiEndpoints = []zaiEndpoint{
	{"global", "https://api.z.ai/api/paas/v4", []string{"glm-5"}, "Global"},
	{"cn", "https://open.bigmodel.cn/api/paas/v4", []string{"glm-5"}, "China"},
	{"coding-global", "https://api.z.ai/api/coding/paas/v4", zaiCodingProbeModels, "Global (Coding Plan)"},
	{"coding-cn", "https://open.bigmodel.cn/api/coding/paas/v4", zaiCodingProbeModels, "China (Coding Plan)"},
}

Z.AI endpoints in detection priority order

Functions

func ACPFormatMessagesAsPrompt

func ACPFormatMessagesAsPrompt(messages []any, tools []any, toolChoice any) (string, error)

Prompt an ACP client sends for OpenAI chat messages, tools and tool choice

func AIGatewayHeaders

func AIGatewayHeaders() map[string]string

AIGatewayHeaders is the AI Gateway attribution header set for callers outside the package

func AIGatewayModelIDs

func AIGatewayModelIDs(ctx context.Context, forceRefresh bool) []string

AIGatewayModelIDs returns just the AI Gateway model id strings

func AWSErrorClassName

func AWSErrorClassName(err error) string

Name of the botocore exception class an AWS client error stands for

func AccountUsageIdentityID

func AccountUsageIdentityID(provider string, entry PooledCredential) string

AccountUsageIdentityID is the stable non secret account id of a pool entry for slot keys and wire account ids

func AccountUsageSnapshotIsStale

func AccountUsageSnapshotIsStale(snapshot *AccountUsageSnapshot) bool

AccountUsageSnapshotIsStale reports a snapshot too old or from the future to render as a live gauge

func ActivateMultiProfileHosting

func ActivateMultiProfileHosting()

Freezes the launch env and makes unscoped credential reads fail closed for a host serving a second home

func AdaptiveRateLimitBackoff

func AdaptiveRateLimitBackoff(attempt int, baseURL, model string, e error, defaultWait time.Duration) (time.Duration, string)

AdaptiveRateLimitBackoff keeps the default wait except Z.AI overloads which widen to 30 60 90 120s after the short attempts

func AddLoopbackNoProxy

func AddLoopbackNoProxy(env map[string]string) map[string]string

AddLoopbackNoProxy appends the loopback hosts to both NO_PROXY casings in env keeping operator entries

func AddOpenAIClientResponseHook

func AddOpenAIClientResponseHook(client any, mark string, hook func(resp *http.Response)) bool

Appends a response hook to the SDK client once per mark, false when the client has no SDK HTTP client

func AdmittedResidencyCount

func AdmittedResidencyCount(modelsDir string, budget HardwareBudget, configured int, live *HardwareBudget, engineTag string) (int, error)

Models the card may hold resident at once, raised above one only while the largest fits twice

func AdoptExternalLoginsEnabled

func AdoptExternalLoginsEnabled(env PoolEnv) bool

AdoptExternalLoginsEnabled is auth.adopt_external_logins, default true, logged once when off

func AdoptLegacyEngine

func AdoptLegacyEngine(ctx context.Context, backend string) bool

Moves the newest verified pre PM install of backend into PM's store and records it, never fails, true when moved

func AffinityScope

func AffinityScope(ctx context.Context) string

Declared routing affinity scope the context carries, empty when unset

func AffordableMaxTokensFromError

func AffordableMaxTokensFromError(err error) (int, bool)

AffordableMaxTokensFromError is the affordable output budget a credit limited 402 names, false without one

func AggregatorProviders

func AggregatorProviders() []string

AggregatorProviders returns the catalog aggregator set in sorted order

func AnchoredContextTokens

func AnchoredContextTokens(ctx context.Context, messages []*state.Message, anchor *UsageAnchor, chargeStaleThinking bool) (int, bool)

AnchoredContextTokens is anchored prompt plus completion tokens and an estimate of messages appended since

func AnsweredByRequestedModel

func AnsweredByRequestedModel(requested, returned string) bool

AnsweredByRequestedModel reports a provider reported model that is the requested one or a dated snapshot of it, an empty report matching

func AnthropicBaseClientQuery

func AnthropicBaseClientQuery(baseURL string) (string, map[string]string)

Normalized Anthropic base URL with the default query Azure endpoints need, nil for every other endpoint

func AnthropicLiveBlocks

func AnthropicLiveBlocks(m *state.Message) ([]any, bool)

AnthropicLiveBlocks is the live ordered Messages content block sidecar of a message, false when it has none

func AnthropicMaxOutput

func AnthropicMaxOutput(model string) int

Max output tokens of an Anthropic model by its longest matching family

func AnthropicOAuthProbeBetas

func AnthropicOAuthProbeBetas() (full, withoutContext1M string)

Comma joined anthropic-beta values an OAuth token probe sends, with and without the 1M context beta

func AnthropicPromptCachePolicy

func AnthropicPromptCachePolicy(ctx context.Context, agent *CachePolicyAgent, dest CacheDestination) (bool, bool)

Prompt cache policy of a policy agent at one destination as should cache and native layout

func AnthropicRequiresBearerAuth

func AnthropicRequiresBearerAuth(baseURL string) bool

Whether an Anthropic compatible base URL authenticates with a bearer token instead of x-api-key

func AnthropicResponseGuardrailIntervened

func AnthropicResponseGuardrailIntervened(message map[string]any) bool

AnthropicResponseGuardrailIntervened reports an InvokeModel reply Bedrock replaced with guardrail messaging

func AnthropicRouteIsOAuth

func AnthropicRouteIsOAuth(ctx context.Context, baseURL, credential string, tokenSource func(context.Context) (string, error), provider string) bool

AnthropicRouteIsOAuth reports the Claude Code OAuth identity for one Anthropic Messages route

func AnyHeaderMap

func AnyHeaderMap(m map[string]any) map[string]string

AnyHeaderMap is a header mapping of arbitrary values as a string map in declaration order, values printed with fmt

func ApplyAnthropicCacheControl

func ApplyAnthropicCacheControl(apiMessages []map[string]any, ttl string, nativeAnthropic bool, staticSystemPrefix string, toolPartMarkers bool) []map[string]any

Messages with Anthropic cache_control breakpoints applied for the given ttl and layout

func ApplyCapabilities

func ApplyCapabilities(ctx context.Context, rows []map[string]any, metadataConfig map[string]any) error

Attaches the capability map of every model per picker row, metadata config nil when the caller has none

func ApplyCustomProviderExtraHeadersToClientKwargs

func ApplyCustomProviderExtraHeadersToClientKwargs(clientKwargs map[string]any, baseURL string, customProviders []map[string]any, cfg map[string]any)

Merges the route entry's extra headers onto the client kwargs default headers, the entry winning over existing values

func ApplyCustomProviderTLSToClientKwargs

func ApplyCustomProviderTLSToClientKwargs(clientKwargs map[string]any, baseURL string, customProviders []map[string]any, cfg map[string]any)

Attaches the TLS knobs of the entry serving the base URL to OpenAI client kwargs

func ApplyDaybreak

func ApplyDaybreak(route Route, daybreak bool, overrides map[string]any)

ApplyDaybreak adds the daybreak cyber access program when enabled and the request credential and model are listed

func ApplyDefaultAgentSettings

func ApplyDefaultAgentSettings(ctx context.Context, cfg config.Tree) error

ApplyDefaultAgentSettings writes the recommended iteration and compression defaults without prompting

func ApplyExternalSecretSources

func ApplyExternalSecretSources(h string)

ApplyExternalSecretSources pulls secrets from every enabled source into the process env once per home

func ApplyInheritedModelAssignment

func ApplyInheritedModelAssignment(ctx context.Context, modelCfg any, inherited map[string]any) (map[string]any, error)

Model block with another profile's raw block pinned over it unvalidated, the source's endpoint bound keys left behind

func ApplyMainModelAssignment

func ApplyMainModelAssignment(ctx context.Context, modelCfg any, result ModelSwitchResult) (map[string]any, error)

Model block with a validated main slot selection applied for the home in ctx

func ApplyModelAssignmentSync

func ApplyModelAssignmentSync(ctx context.Context, provider, model, baseURL, apiKey string, prepared *PreparedMainAssignment) (map[string]any, error)

Persists a main model pick, prepared carrying a validation done outside the config lock

func ApplyModelSelection

func ApplyModelSelection(modelCfg any, result ModelSwitchResult, maskCleared bool) map[string]any

ApplyModelSelection returns the model section with the selection applied, cleared keys removed or masked with null

func ApplyRequiredCodexHeaders

func ApplyRequiredCodexHeaders(headers map[string]string, accessToken, baseURL string) map[string]string

ApplyRequiredCodexHeaders adds the identity headers the official Codex endpoint requires

func ApplyUserDefaultHeaders

func ApplyUserDefaultHeaders(ctx context.Context, headers map[string]string) map[string]string

Resolved headers with model.default_headers and model.extra_headers merged over them, user values winning

func ApplyUserMoAPresets

func ApplyUserMoAPresets(merged map[string]any, raw any)

ApplyUserMoAPresets makes an explicit user preset map authoritative over the merged defaults

func AskOnErrorPath

func AskOnErrorPath(ctx context.Context, p *Profile, hook string, fallback any, kwargs map[string]any) any

AskOnErrorPath is the profile's answer to an API error path hook asked every time, a failure answers fallback

func AskProfile

func AskProfile(ctx context.Context, p *Profile, hook string, fallback any, scope any, args []any, kwargs map[string]any) any

AskProfile is the profile's answer to a per request hook, a failure answers fallback for the rest of the scope's session

func AsyncCallLLM

func AsyncCallLLM(ctx context.Context, kwargs map[string]any) (any, error)

AsyncCallLLM runs an auxiliary LLM request on the async client surface under the async task limit

func AtomicWriteCacheJSON

func AtomicWriteCacheJSON(path string, payload any) error

AtomicWriteCacheJSON writes a secret cache entry 0600 with the containing dir tightened to 0700

func AttributeSecretSourceForTests

func AttributeSecretSourceForTests(name, source string) func()

Attributes an env name to an external secret source and returns the restore of its prior attribution

func AuthCommand

func AuthCommand(ctx context.Context, env PoolEnv, ns map[string]any, w, errw io.Writer) (int, error)

AuthCommand runs icebath auth from the parsed namespace, SystemExit shaped errors printed to errw with their code

func AutoCacheTTLForSource

func AutoCacheTTLForSource(source string) string

AutoCacheTTLForSource resolves the auto tier, 5m for machine paced sources and 1h for human paced ones

func AutoDetectLocalModel

func AutoDetectLocalModel(ctx context.Context, baseURL string) string

Model name of a local server at baseURL when exactly one model is loaded, empty otherwise

func AuxCallKwargs

func AuxCallKwargs(ctx context.Context, provider, model string, messages any, baseURL string) (map[string]any, error)

AuxCallKwargs is the auxiliary chat completions request for one provider and model routed at baseURL

func AuxClientCredential

func AuxClientCredential(c AuxClient) any

AuxClientCredential is the rotating key source of an SDK client when it has one, else its static key

func AuxClientCustomHeaders

func AuxClientCustomHeaders(c AuxClient) map[string]string

Copy of the custom default headers a routed SDK client sends, nil when the client keeps none

func AuxClientDefaultHeaders

func AuxClientDefaultHeaders(c AuxClient) map[string]string

AuxClientDefaultHeaders is the header set an SDK client sends on every request, nil for adapters

func AuxClientEffectiveProvider

func AuxClientEffectiveProvider(c AuxClient) string

Provider a routed auxiliary client was stamped with, empty when the client carries no stamp

func AuxExcTypeName

func AuxExcTypeName(err error) string

AuxExcTypeName exposes the Python class name of the outermost auxiliary client error

func AuxFallbackEntryAPIKey

func AuxFallbackEntryAPIKey(ctx context.Context, entry map[string]any) string

Inline or env backed key of a fallback entry through the secret scope aware resolver

func AuxInterruptProtection

func AuxInterruptProtection(ctx context.Context, active bool, cancelCheck AuxCancelCheck, cancelEvent AuxCancelEvent) context.Context

AuxInterruptProtection marks calls under the context interrupt protected, nested scopes inheriting the cancel sources

func AuxIsConnectionError

func AuxIsConnectionError(err error) bool

Python TimeoutError, connection error check of the auxiliary client for summary failure classification

func AuxModelForProvider

func AuxModelForProvider(ctx context.Context, providerID string, preferFast bool) string

Cheap auxiliary model of a provider, the live catalog fast tier first when preferFast is set

func AuxProbeMode

func AuxProbeMode(ctx context.Context) context.Context

AuxProbeMode resolves provider availability under the returned context without building real SDK clients

func AuxProgressHook

func AuxProgressHook(ctx context.Context, hook func() error) context.Context

AuxProgressHook installs the forward progress callback for auxiliary calls under the context

func AuxReadMainModel

func AuxReadMainModel(ctx context.Context) string

AuxReadMainModel exports the main model reader for the plugin LLM facade

func AuxReadMainProvider

func AuxReadMainProvider(ctx context.Context) string

AuxReadMainProvider exports the main provider reader for the plugin LLM facade

func AuxStreamDeadline

func AuxStreamDeadline(ctx context.Context, deadline AuxStreamDeadlineFunc) context.Context

AuxStreamDeadline publishes the host deadline to stream consumers under the context, nil keeping the previous one

func AuxThreadLocalHook

func AuxThreadLocalHook(ctx context.Context, local AuxHookLocal, hook func() error) context.Context

AuxThreadLocalHook installs one timing hook for calls under the context, a nil hook keeping the previous one

func AuxiliaryMaxTokensParam

func AuxiliaryMaxTokensParam(ctx context.Context, value int, model string) map[string]any

Max tokens kwarg for the auxiliary provider, max_completion_tokens for direct OpenAI, declaring profiles and newer OpenAI models

func AuxiliaryTaskConfig

func AuxiliaryTaskConfig(ctx context.Context, task string) (map[string]any, error)

Merged auxiliary task config block for a task name

func AzureLookupContextLength

func AzureLookupContextLength(ctx context.Context, model, baseURL, apiKey string, tokenProvider func(context.Context) (string, error)) int

AzureLookupContextLength returns the known context window for a model on an Azure endpoint or 0 when only a guess exists

func BedrockFoundationModelCount

func BedrockFoundationModelCount(ctx context.Context, region string) (int, error)

Number of foundation models the Bedrock control plane lists for a region, one attempt with a ten second read limit

func BedrockGuardrailConfig

func BedrockGuardrailConfig(ctx context.Context) map[string]any

BedrockGuardrailConfig is the configured Converse guardrail of the home the context serves

func BedrockModelRoutableFromRegion

func BedrockModelRoutableFromRegion(modelID, regionName string) bool

BedrockModelRoutableFromRegion is true when the model id can be invoked from the region's endpoint

func BedrockRegionGeoPrefix

func BedrockRegionGeoPrefix(regionName string) string

BedrockRegionGeoPrefix maps an AWS region name to its inference profile geo prefix, empty when unknown

func BedrockStreamCall

func BedrockStreamCall(ctx context.Context, agent ChatCompletionAgent, apiKwargs map[string]any, onFirstDelta func()) (any, error)

Agent form Bedrock stream, the deltas delivered through the agent fire hooks between the stream emitters

func BindImageTokenCost

func BindImageTokenCost(ctx context.Context, model, baseURL string) context.Context

BindImageTokenCost binds the learned per image price of model and base URL for the rest of the turn

func BindProfileSecretScope

func BindProfileSecretScope(ctx context.Context, h string) context.Context

BindProfileSecretScope binds the built secret scope of a profile home on ctx the way plugin_host bind sets it

func Blake2bSum

func Blake2bSum(data []byte, size int) []byte

BLAKE2b digest of data with the given output size in bytes

func BodyRetryAfter

func BodyRetryAfter(body any) (time.Duration, bool)

Positive cooldown a retry_after field declares at the top of an SDK error body or under its error object

func BotAuthorID

func BotAuthorID(profile, origin string) string

Bot author id, bot:profile on this install and bot:origin/profile for one on another install

func BoundRegistryKey

func BoundRegistryKey(ctx context.Context) (string, int64)

BoundRegistryKey returns the bound home key and registry generation after the periodic plugin check

func BufferConnectExhaustedNotice

func BufferConnectExhaustedNotice(agent StreamDiagAgent, err error, attempts int, baseURL string)

Buffers the connect exhausted notice once per turn however many passes exhaust the same budget

func BuildAnthropicBedrockClient

func BuildAnthropicBedrockClient(ctx context.Context, region string, timeout float64) (any, error)

BuildAnthropicBedrockClient is the Anthropic Bedrock SDK client of a region with the request timeout

func BuildAnthropicClient

func BuildAnthropicClient(ctx context.Context, apiKey any, baseURL string, timeout float64, dropContext1MBeta bool) (any, error)

Anthropic SDK client for a static key or bearer callable, nil with the error when the build fails

func BuildAuxPickerRows

func BuildAuxPickerRows(ctx context.Context, currentProvider, currentModel, currentBaseURL string, maxModels *int) ([]map[string]any, error)

BuildAuxPickerRows lists provider rows for auxiliary task pickers with moa removed

func BuildEntraTokenProviderIn

func BuildEntraTokenProviderIn(ctx context.Context, cfg *EntraIdentityConfig, scope string, excludeInteractiveBrowser bool) (func(context.Context) (string, error), error)

Bearer minter over the credential built now for the context profile, a credential build failure returned at once

func BuildKeepaliveHTTPClient

func BuildKeepaliveHTTPClient(baseURL string, asyncMode bool, verify TLSVerify) *http.Client

BuildKeepaliveHTTPClient is the keepalive client with the environment only proxy policy, nil when it cannot be built

func BuildModelOptionsPayload

func BuildModelOptionsPayload(ctx context.Context, pc PickerConfigContext, explicitOnly, includeUnconfigured, refresh bool) (map[string]any, error)

BuildModelOptionsPayload is the shared API server and TUI payload with limits and usage attached

func BuildModelsPayload

func BuildModelsPayload(ctx context.Context, pc PickerConfigContext, opts ModelsPayloadOptions) (map[string]any, error)

BuildModelsPayload is the picker payload of providers with their model lists

func BuildNvidiaNIMHeaders

func BuildNvidiaNIMHeaders(baseURL string) map[string]string

BuildNvidiaNIMHeaders returns the NIM cloud attribution headers for integrate.api.nvidia.com traffic

func BuildORHeaders

func BuildORHeaders(ctx context.Context, orConfig map[string]any) (map[string]string, error)

BuildORHeaders returns the OpenRouter headers plus response cache headers, env over config over default, nil config read from disk

func BuildOpenAIToolCall

func BuildOpenAIToolCall(callID, name, arguments string) state.ToolCall

OpenAI compatible tool call for downstream handling

func BuildPlanPrompt

func BuildPlanPrompt(task string) string

BuildPlanPrompt builds the plan mode turn prompt, an empty task asking the agent to infer it from context

func BuildProfileSecretScope

func BuildProfileSecretScope(h string) map[string]string

BuildProfileSecretScope assembles a profile's secrets from .env, its secret sources and the managed env

func BuildPromptCachePlan

func BuildPromptCachePlan(apiMessages, tools []map[string]any, o PromptCachePlanOptions) ([]map[string]any, []map[string]any)

Applies the copy on write cache sections to the request messages and tools

func BuiltinAuxTaskKeys

func BuiltinAuxTaskKeys() []string

BuiltinAuxTaskKeys lists the built in auxiliary task keys in picker order

func BuiltinNameUserEntry

func BuiltinNameUserEntry(ctx context.Context, name string, providers map[string]any) (string, bool)

BuiltinNameUserEntry is the one predicate the model switch and the doctor read so validation and the next turn agree on where a built in name runs

func BypassChatSDKRequestTransform

func BypassChatSDKRequestTransform(requestKwargs map[string]any, client any) map[string]any

Chat completions bypass applied only for the real SDK client, which merges extra_body after building the body

func BypassSDKRequestTransform

func BypassSDKRequestTransform(requestKwargs map[string]any, fields []string, keepSlots bool) map[string]any

Moves wire format bulk fields into extra_body, leaving empty list slots when asked, the request itself when nothing moves

func CacheTTLMeansDisabled

func CacheTTLMeansDisabled(ttl any) bool

CacheTTLMeansDisabled reports whether a configured cache_ttl value turns prompt caching off, unknown values never do

func CachedProviderModelIDs

func CachedProviderModelIDs(ctx context.Context, provider string, opts CachedModelsOptions) []string

CachedProviderModelIDs is the disk cached catalog, a fresh row else a live fetch persisting a non empty result

func CalibrateImageTokenCost

func CalibrateImageTokenCost(ctx context.Context, model, baseURL string, anchor *UsageAnchor, messages []*state.Message, promptTokens any) (context.Context, int, bool)

CalibrateImageTokenCost learns the per image price from the residual of a response over the still matching previous anchor

func CallLLM

func CallLLM(ctx context.Context, kwargs map[string]any) (any, error)

CallLLM runs an auxiliary LLM request under the configured task limit and relay identity

func CallableKeyIdentity

func CallableKeyIdentity(v any) (uintptr, bool)

CallableKeyIdentity is the closure identity of a callable credential, false for a static key

func CanonicalAPIMode

func CanonicalAPIMode(apiMode string) string

CanonicalAPIMode maps alias spellings onto the canonical transport name and passes unknown values through

func CanonicalCustomIdentity

func CanonicalCustomIdentity(ctx context.Context, baseURL, configProvider, model, requested string) string

Durable menu identity of a bare custom provider from its endpoint, model or configured provider, empty when none heals it

func CapToRunBudget

func CapToRunBudget(agent any, timeout float64) float64

CapToRunBudget caps an implicit stale timeout at half the remaining run budget, never under sixty seconds

func CaptureLaunchEnv

func CaptureLaunchEnv() map[string]string

Process env frozen as the launch profile's own, the first capture wins and later calls return a copy

func CapturedAuxCancelRequested

func CapturedAuxCancelRequested(check AuxCancelCheck) bool

Reports whether a captured auxiliary cancel check has fired

func CarrierRecord

func CarrierRecord(ctx context.Context, assistantMessage map[string]any) map[string]any

CarrierRecord is the private reasoning_details record of one response message, nil when it carries nothing

func CatalogByID

func CatalogByID() map[string]CatalogEntry

Running catalog keyed by family id

func CatalogCachePath

func CatalogCachePath(ctx context.Context) string

CatalogCachePath is the per profile disk cache file

func CatalogItemIsGeneration

func CatalogItemIsGeneration(item any) bool

CatalogItemIsGeneration fails open unless the row's own type or name proves it is generation only

func CatalogModelIDs

func CatalogModelIDs(rows []CatalogModel) []string

CatalogModelIDs returns the bare ids of a described snapshot

func CatalogProviderAlias

func CatalogProviderAlias(name string) (string, bool)

CatalogProviderAlias resolves a picker alias to its provider with built in aliases beating plugin ones

func CatalogProviderAliases

func CatalogProviderAliases() map[string]string

CatalogProviderAliases returns every alias pair, built in first then plugin declared

func CatalogProviderLabel

func CatalogProviderLabel(slug string) string

CatalogProviderLabel returns the short display label for a slug, empty when unknown

func CatalogRefreshInterval

func CatalogRefreshInterval(ctx context.Context) time.Duration

CatalogRefreshInterval is the configured TTL as the gateway poll cadence, at least one minute

func ChatCatalogIDs

func ChatCatalogIDs(items any) []string

ChatCatalogIDs lists the model ids of a models payload minus generation rows

func ChatWireNeedsKeyOrder

func ChatWireNeedsKeyOrder(msg map[string]any, keys []string) bool

Whether a builder key order puts the keys a chat completions body keeps in another order than the encoder default

func CheckCodexBinary

func CheckCodexBinary(codexBin string, minVersion [3]int) (bool, string, error)

Verifies the codex CLI is installed at the minimum version, the version text or the failure message

func CheckCodexBinaryOK

func CheckCodexBinaryOK(codexBin string) (bool, string)

Codex CLI install and version check, the version on success else the reason

func CheckFallbackEntryLive

func CheckFallbackEntryLive(ctx context.Context, entry map[string]any, result *FallbackEntryCheck, redact FallbackCheckRedactor) error

CheckFallbackEntryLive sends one minimal completion for a statically ready entry on the client the swap builds and records the verdict, an error only for a host abort

func ClaimKeptNotices

func ClaimKeptNotices(ctx context.Context) []string

ClaimKeptNotices takes every notice kept for the active home, for a turn someone sees

func ClaimStreamWriter

func ClaimStreamWriter(agent any) int

Claims the delta sink for a stream attempt, zero when the agent lacks the fence or the claim panics

func ClampEffort

func ClampEffort(effort string, supported []string) string

Nearest weaker supported effort, the request verbatim when supported or outside the ladder

func ClampReasoningEffortToSupported

func ClampReasoningEffortToSupported(effort string, supported []string) string

ClampReasoningEffortToSupported keeps a supported level verbatim else the nearest weaker supported level

func ClampTimeout

func ClampTimeout(seconds float64) (time.Duration, bool)

ClampTimeout maps NaN, infinite, or non positive seconds to unbounded and caps the rest

func ClaudeCodeCredentialsPath

func ClaudeCodeCredentialsPath() string

ClaudeCodeCredentialsPath is Claude Code's shared OAuth file honoring CLAUDE_CONFIG_DIR

func CleanErrorMessage

func CleanErrorMessage(errorMsg string) string

CleanErrorMessage collapses whitespace, hides HTML pages, and caps display text at 150 chars

func CleanupStaleAsyncClients

func CleanupStaleAsyncClients()

CleanupStaleAsyncClients drops and closes every cached async client whose bound loop has closed

func CleanupTaskResources

func CleanupTaskResources(ctx context.Context, agent ChatCompletionAgent, taskID string)

Per turn VM and browser cleanup that leaves persistent terminals and headed browsers to their idle reapers

func ClearAllProviderModelsCache

func ClearAllProviderModelsCache(ctx context.Context)

ClearAllProviderModelsCache wipes the whole cache file under the cache lock

func ClearBitwardenCaches

func ClearBitwardenCaches(homePath string)

ClearBitwardenCaches drops the in process and both disk caches after a token rotation

func ClearCatalogFetchBackoff

func ClearCatalogFetchBackoff(ctx context.Context)

ClearCatalogFetchBackoff forgets the active profile's fetch failures so an explicit refresh retries every URL

func ClearCodexPoolQuotaCooldowns

func ClearCodexPoolQuotaCooldowns(env PoolEnv, accessToken string) int

ClearCodexPoolQuotaCooldowns lifts rate limit cooldowns on persisted Codex pool rows, one token or every row

func ClearOnePasswordCaches

func ClearOnePasswordCaches(homePath string)

ClearOnePasswordCaches drops the in process and disk caches after a token rotation

func ClearProviderModelsCache

func ClearProviderModelsCache(ctx context.Context, provider string)

ClearProviderModelsCache drops one provider's cache row under the cache lock

func ClearWindowOverride

func ClearWindowOverride(modelID string) error

Drops a model's growth state, leaving the file untouched when it has none

func CmdMoA

func CmdMoA(ctx context.Context, out io.Writer, args MoAArgs) error

CmdMoA manages Mixture of Agents presets for the icebath moa command, list when no subcommand is given

func CmdModel

func CmdModel(ctx context.Context, ns map[string]any, w io.Writer) (code int, err error)

CmdModel is icebath model after the terminal check, the cache refresh then the picker under setup navigation

func CmdProxy

func CmdProxy(ctx context.Context, h string, ns map[string]any, w, errw io.Writer) (int, error)

CmdProxy dispatches icebath proxy <subcommand>, a missing or unknown one printing the short help

func CodexCatalogCredentialIdentity

func CodexCatalogCredentialIdentity(ctx context.Context) string

CodexCatalogCredentialIdentity names the principal and route live discovery would use for the cache key

func CodexCatalogURLs

func CodexCatalogURLs(baseURL string) []string

CodexCatalogURLs builds the catalog urls against a gateway base or the hard coded endpoint

func CodexCloudflareHeaders

func CodexCloudflareHeaders(accessToken, baseURL string) map[string]string

Codex backend identity and account headers for an access token and base url

func CodexRuntimeCommand

func CodexRuntimeCommand(ctx context.Context, h string, ns map[string]any, w io.Writer) (int, error)

CodexRuntimeCommand runs the codex config migration for the profile home and prints its report, exit one on any error

func CodexRuntimeParseArgs

func CodexRuntimeParseArgs(argString string) (*string, []string)

Runtime named by the command argument, nil with no argument, an error line for an unknown name

func CodexStaleTimeoutFloor

func CodexStaleTimeoutFloor(estTokens int) float64

Minimum stale timeout for openai-codex by estimated context, zero below 10k tokens

func CodexTokenCountDelta

func CodexTokenCountDelta(source string, counts map[string]any) state.TokenCountDelta

CodexTokenCountDelta maps one queued codex accounting map onto the session store delta, None values left nil

func CodexToolsExposedTools

func CodexToolsExposedTools() []string

CodexToolsExposedTools returns a copy of the curated tool names the codex tools server exposes

func CoerceAPIErrorDetail

func CoerceAPIErrorDetail(value any) string

CoerceAPIErrorDetail renders a structured provider error field as display text

func CoerceFloat

func CoerceFloat(value any, def float64) float64

CoerceFloat reads a config number with a default for malformed values

func CoerceInsecure

func CoerceInsecure(sslVerify any) bool

CoerceInsecure reads an ssl_verify setting as a request to disable verification

func CoerceLLMMessage

func CoerceLLMMessage(response any) any

CoerceLLMMessage pulls the message out of a response or returns a bare message, nil for an empty choices list

func CoercePositiveTimeout

func CoercePositiveTimeout(raw any) (float64, bool)

Positive float timeout of a raw config value, false for missing, non numeric or non positive values

func CoercePrivacyFilter

func CoercePrivacyFilter(value any) string

CoercePrivacyFilter normalizes the MoA privacy filter to off, display or full

func CoerceProviderID

func CoerceProviderID(value any) string

CoerceProviderID renders a provider identity field as a trimmed string

func CoerceToolName

func CoerceToolName(name any, fallback string) string

CoerceToolName coerces a replayed tool name into the API name grammar, the fallback when nothing survives

func CombinedSelectionMessage

func CombinedSelectionMessage(warnings []SelectionWarning) string

CombinedSelectionMessage joins every warning message into one confirm prompt body

func CompatibleCustomProviders

func CompatibleCustomProviders(cfg map[string]any) []map[string]any

CompatibleCustomProviders is the deduplicated list view over custom_providers and providers blocks

func CompressionThresholdForModel

func CompressionThresholdForModel(model, provider string, allowCodexGPT55Autoraise bool) (float64, bool)

Per model and route compaction threshold override, false when the user's value stands

func ConfigFacadeBrowserEnvSources

func ConfigFacadeBrowserEnvSources(h string) config.BrowserEnvSources

ConfigFacadeBrowserEnvSources is the browser env adoption source set of configFacadeMigrationSources

func ConfigFacadeStampHooks

func ConfigFacadeStampHooks() config.StampHooks

ConfigFacadeStampHooks exports configFacadeStampHooks

func ConfigLoader

func ConfigLoader(h string) func() map[string]any

ConfigLoader binds the home's read only config to a PoolEnv, whose context applies a frozen scope first

func ConfigureBedrockOpenAIClientKwargs

func ConfigureBedrockOpenAIClientKwargs(ctx context.Context, clientKwargs map[string]any, timeout *float64) error

ConfigureBedrockOpenAIClientKwargs installs SigV4 on OpenAI client kwargs for a Mantle base url unless a real key is set

func ConfiguredCustomProviderIDs

func ConfiguredCustomProviderIDs(ctx context.Context) map[string]bool

Configured custom provider ids of the active config

func ConfiguredProviderName

func ConfiguredProviderName(ctx context.Context, section string, logger *slog.Logger) string

Configured section provider from the read only config, stripped

func ConnectExhaustedNotice

func ConnectExhaustedNotice(err error, attempts int, baseURL string) string

User facing line for a stream that never opened, naming host, attempts and request size

func ConsumeOAuthHealNotices

func ConsumeOAuthHealNotices() []string

ConsumeOAuthHealNotices returns and clears the notes about forked grant heals run in this process

func ContextCacheKey

func ContextCacheKey(model, baseURL string) string

Exported cache key for tests of other packages

func ContextRouteMismatch

func ContextRouteMismatch(configuredBaseURL, activeBaseURL, configuredProvider, activeProvider string) bool

ContextRouteMismatch reports whether a context pin's configured route differs from the runtime route

func ConversationContext

func ConversationContext(ctx context.Context) string

Conversation lineage root id the context carries, empty when unset

func CoreDeclaredEnvNames

func CoreDeclaredEnvNames() map[string]bool

CoreDeclaredEnvNames lists every name core declares, static entries plus provider profile entries

func CountImages

func CountImages(messages []*state.Message) int

CountImages is the number of image parts across the messages

func CreateAnthropicMessage

func CreateAnthropicMessage(ctx context.Context, client any, apiKwargs map[string]any, logPrefix string, preferStream bool, onResponse func(response any)) (any, error)

Agent Messages call over its anthropic client with the stream preference and the response header hook

func CredentialLabel

func CredentialLabel(key any) string

CredentialLabel is the label for a callable key's source, empty for a non callable

func CredentialPoolEntryServesEndpoint

func CredentialPoolEntryServesEndpoint(entry PooledCredential, baseURL string) bool

CredentialPoolEntryServesEndpoint reports whether a pooled credential may be bound to a session at baseURL

func CredentialPoolMatchesProvider

func CredentialPoolMatchesProvider(ctx context.Context, poolProvider, provider, baseURL string) bool

CredentialPoolMatchesProvider is CredentialPoolMatchesProviderIn under the process config

func CredentialPoolMatchesProviderIn

func CredentialPoolMatchesProviderIn(poolProvider, provider, baseURL string, cfg map[string]any) bool

CredentialPoolMatchesProviderIn reports whether a pool key belongs to the runtime provider under cfg

func CredentialSourceOf

func CredentialSourceOf(key any) string

CredentialSourceOf is the source tag of a callable key, empty for strings and untagged minters

func CtxBytes

func CtxBytes(profile ModelProfile, window int, flashAttention bool) int64

Memory that grows with the window across full, SWA and recurrent layers plus window compute buffers

func CuratedCatalogProviders

func CuratedCatalogProviders() []string

CuratedCatalogProviders returns the curated row names in sorted order

func CuratedCatalogRows

func CuratedCatalogRows() map[string][]string

CuratedCatalogRows returns a copy of every curated row with the xAI rows resolved

func CurrentAuxProgressHook

func CurrentAuxProgressHook(ctx context.Context) func() error

Forward progress hook bound to the calling scope

func CurrentAuxStreamDeadline

func CurrentAuxStreamDeadline(ctx context.Context) (time.Time, bool)

Auxiliary stream deadline bound to the calling scope

func CurrentCachePath

func CurrentCachePath(h, name string) string

CurrentCachePath is the home level cache file, deleting a legacy copy under cache first

func CurrentImageTokenCost

func CurrentImageTokenCost(ctx context.Context) int

CurrentImageTokenCost is the per image price bound to the running turn, else the flat default

func CurrentPromptReadingHook

func CurrentPromptReadingHook(ctx context.Context) func(seconds float64)

Prompt reading hook installed on the context, nil when none

func CurrentSecretScope

func CurrentSecretScope(ctx context.Context) map[string]string

CurrentSecretScope is the active mapping, nil when no scope is installed

func CurrentSecretScopeHome

func CurrentSecretScopeHome(ctx context.Context) string

CurrentSecretScopeHome is the home the active scope was stamped with

func CursesPromptChoice

func CursesPromptChoice(question string, choices []string, def int, description string) (int, error)

CursesPromptChoice is the single choice list, -1 when cancelled, an error when the terminal cannot draw it

func CustomEntryForEndpoint

func CustomEntryForEndpoint(baseURL, providerName string, cfg map[string]any) (string, map[string]any, bool)

CustomEntryForEndpoint is the normalized name and entry of the custom provider owning a base url

func CustomProviderAPIMode

func CustomProviderAPIMode(baseURL string, customProviders []map[string]any, cfg map[string]any) string

CustomProviderAPIMode is the canonical api_mode of the first custom entry serving the base URL or empty

func CustomProviderAliases

func CustomProviderAliases(displayName, providerKey string) map[string]bool

CustomProviderAliases returns every current and legacy identity accepted for one endpoint

func CustomProviderContextLength

func CustomProviderContextLength(model, baseURL string, customProviders []map[string]any, cfg map[string]any) int

CustomProviderContextLength is the per model or entry level context_length override for a route or 0

func CustomProviderExtraBodyForAgent

func CustomProviderExtraBodyForAgent(provider, model, baseURL string, customProviders []map[string]any) map[string]any

CustomProviderExtraBodyForAgent is the extra_body of the custom entry serving a custom route, model pinned entries first

func CustomProviderExtraHeaders

func CustomProviderExtraHeaders(baseURL string, customProviders []map[string]any, cfg map[string]any) map[string]string

CustomProviderExtraHeaders returns the headers of the first route matching entry declaring any

func CustomProviderModelCapability

func CustomProviderModelCapability(model, baseURL, capability string, customProviders []map[string]any, cfg map[string]any) (value bool, known bool)

CustomProviderModelCapability is the explicit boolean capability for one custom model, known false when absent

func CustomProviderSessionAffinityHeader

func CustomProviderSessionAffinityHeader(baseURL string, customProviders []map[string]any, cfg map[string]any) string

CustomProviderSessionAffinityHeader is the header name a route matching entry opted into or empty

func CustomProviderSessionAffinityHeaders

func CustomProviderSessionAffinityHeaders(ctx context.Context, baseURL, sessionID string) map[string]string

CustomProviderSessionAffinityHeaders is the opted in affinity header of the route matching entry, empty when none

func CustomProviderSlug

func CustomProviderSlug(displayName, providerKey string) string

CustomProviderSlug is the stable custom identity, keyed providers entries by their config key

func DaybreakOffered

func DaybreakOffered(model, providerName, baseURL, accessToken string) (bool, error)

DaybreakOffered reports whether the Codex subscription route and the account catalog list daybreak for the model

func DeclaredAuthProviders

func DeclaredAuthProviders(manifest map[string]any) []string

DeclaredAuthProviders lists the requires_auth providers of a manifest whose sign in the plugin uses

func DeclaredConversationScope

func DeclaredConversationScope(a *CacheScopeAgent) string

DeclaredConversationScope hashes the host declared conversation key into a gwk scope, empty when none applies

func DeclaredConversationScopeSafe

func DeclaredConversationScopeSafe(a *CacheScopeAgent) (scope string)

DeclaredConversationScopeSafe resolves the declared scope and turns any panic into an empty scope

func DeclaredModelIDs

func DeclaredModelIDs(value any) []string

Declared model ids of a provider entry's models config in declaration order

func DeclaresModelProviderKind

func DeclaresModelProviderKind(pluginDir string) bool

Whether a plugin manifest declares the model provider kind, the exported form plugins reach through Services

func DecodeJWTClaims

func DecodeJWTClaims(token string) map[string]any

DecodeJWTClaims returns the unverified payload object of a three part JWT or an empty map

func DecodeMoATurn

func DecodeMoATurn(message string) (string, map[string]any, error)

DecodeMoATurn splits a hidden one shot MoA marker into its prompt and normalized preset, nil when not a marker

func DecorateXAIEntitlementError

func DecorateXAIEntitlementError(detail string) string

DecorateXAIEntitlementError appends the Premium+ hint once to an xAI permission denied detail

func DeepinfraBaseURL

func DeepinfraBaseURL(ctx context.Context, section map[string]any) string

DeepinfraBaseURL is the config section base_url, then the env override, then the default

func DeepinfraModelIDs

func DeepinfraModelIDs(ctx context.Context, tag string, forceRefresh bool) []string

DeepinfraModelIDs returns the DeepInfra ids carrying a surface tag, empty on failure

func DefaultCABundlePath

func DefaultCABundlePath() string

DefaultCABundlePath is the bundle the process resolved on first use, re-derived once when its path vanished

func DefaultContextLengths

func DefaultContextLengths() map[string]int

DefaultContextLengths exposes the family fallback table as a map

func DefaultModelFromCatalogCache

func DefaultModelFromCatalogCache(ctx context.Context, provider string) string

DefaultModelFromCatalogCache returns the manifest's labeled default from memory, disk, then the shipped manifest, never a fetch

func DeferStartupNotice

func DeferStartupNotice(ctx context.Context, message string)

DeferStartupNotice logs a message and keeps it for the active home's next watched turn

func DeliveryEnv

func DeliveryEnv(ctx context.Context, env *tools.Env, author *pyjson.Object, profileHome string) (map[string]string, error)

Env of one delivery turn child built from the target profile env, dispatcher author and session identity dropped

func DeriveResponsesFunctionCallID

func DeriveResponsesFunctionCallID(callID, responseItemID string) string

DeriveResponsesFunctionCallID is the valid Responses function_call id starting with fc_

func DescribeActiveEntraCredential

func DescribeActiveEntraCredential(ctx context.Context, cfg *EntraIdentityConfig, scope string, timeout time.Duration) map[string]any

DescribeActiveEntraCredential reports scope, tenant, env sources and token expiry for doctor and preflight

func DescribePrimary

func DescribePrimary(cfg map[string]any) (string, error)

DescribePrimary is the one line model (via provider) of the configured primary, empty for none

func DetectLocalServerType

func DetectLocalServerType(ctx context.Context, baseURL, apiKey string) string

DetectLocalServerType probes known endpoints for ollama, lm-studio, vllm or llamacpp with TTL caching

func DetectProviderForModel

func DetectProviderForModel(ctx context.Context, modelName, currentProvider string) (string, string, bool)

DetectProviderForModel walks the live current catalog, static catalogs, OpenRouter and configured prefixes

func DetectStaticProviderForModel

func DetectStaticProviderForModel(ctx context.Context, modelName, currentProvider string) (string, string, bool)

DetectStaticProviderForModel auto detects a provider from static catalogs only

func DetectVendor

func DetectVendor(model string) string

DetectVendor returns the vendor slug implied by a model name or empty when none is recognisable

func DirectAPICall

func DirectAPICall(ctx context.Context, agent ChatCompletionAgent, apiKwargs map[string]any) (resp any, err error)

Runs the agent's blocking call on the calling goroutine with a heartbeat, one shot stale kill and socket backstop

func DirectAliasAPIKey

func DirectAliasAPIKey(ctx context.Context, alias DirectAlias) (string, error)

DirectAliasAPIKey resolves the alias credential from an env template, a literal key, then key_env

func DirectAliasRuntimeRequest

func DirectAliasRuntimeRequest(ctx context.Context, alias DirectAlias) (string, string, error)

DirectAliasRuntimeRequest returns the provider to resolve and the explicit key, custom whenever the alias names a URL

func DiscoverFlag

func DiscoverFlag(entry map[string]any) bool

Reports whether live model discovery is enabled for a provider entry

func DiscoverUncoveredProviders

func DiscoverUncoveredProviders(availableEnvNames []string) []string

DiscoverUncoveredProviders lists recognized providers the proxy cannot swap

func DispatchCodexToolsMCPServerEntry

func DispatchCodexToolsMCPServerEntry()

DispatchCodexToolsMCPServerEntry runs the tools MCP server and exits when argv names its entry

func DispatchNonstreamingAPIRequest

func DispatchNonstreamingAPIRequest(ctx context.Context, agent ChatCompletionAgent, apiKwargs map[string]any, makeClient func(reason, kind string) (any, error)) (any, error)

Runs one blocking request for the agent's api mode through the per request client the factory builds

func DotenvSetValues

func DotenvSetValues(path string) (map[string]string, error)

Assignments with a value of a utf-8-sig dotenv file interpolated like python-dotenv dotenv_values

func DotenvUnreadable

func DotenvUnreadable(path string) bool

Reports whether the path exists but this process may not read it

func DropExpired

func DropExpired[K comparable, V any](values map[K]V, stamps map[K]time.Time, ttl time.Duration, now time.Time)

Pops every key whose stamp, a missing stamp counting as zero, is ttl old

func DropModelKey

func DropModelKey(ctx context.Context, modelCfg map[string]any, key string) error

DropModelKey removes a model key the block holds, masking it with null under Remote Config

func DropStaleModelRoute

func DropStaleModelRoute(modelCfg map[string]any, provider string, cfg map[string]any) (map[string]any, bool)

DropStaleModelRoute pops base_url and api_mode left by a previous provider and reports an unverifiable route

func DropUnofferableModelIDs

func DropUnofferableModelIDs(rows []any)

DropUnofferableModelIDs removes in place every picker row id validation would refuse for whitespace

func DropsReplayItemIDs

func DropsReplayItemIDs(baseURL string) bool

Endpoint binds replayed Responses item ids to a connection so replay must drop them

func DumpIfModel

func DumpIfModel(value any) any

Plain dict of an SDK model, any other value unchanged

func EagerFallbackStatus

func EagerFallbackStatus(cl *Classified, isUpstream, isTransport bool) string

func EffectiveAuxTimeout

func EffectiveAuxTimeout(ctx context.Context, task string, timeout *float64) float64

Explicit timeout first, then the task config, compression floored so long summaries are not cut off

func EffectiveCacheTTL

func EffectiveCacheTTL(ttl, model, providerName string) string

Cache lifetime the route honours for the configured TTL

func EffectiveRuntimeProvider

func EffectiveRuntimeProvider(entry map[string]any, rt *Runtime) string

EffectiveRuntimeProvider is the identity to persist for a resolved fallback entry, the configured name over bare custom

func EffortDisplayLabel

func EffortDisplayLabel(effort, provider, model, apiMode string) string

EffortDisplayLabel is the picker and reasoning status label for a level on a route

func EffortLadderIndex

func EffortLadderIndex(level string) int

EffortLadderIndex is the position of a reasoning effort on the ladder, -1 when absent

func EgressCommand

func EgressCommand(ctx context.Context, h string, ns map[string]any, w io.Writer) (int, error)

EgressCommand runs icebath egress from the parsed namespace, help when no subcommand was named

func EmitStreamDrop

func EmitStreamDrop(agent StreamDiagAgent, err error, attempt, maxAttempts int, midToolCall bool, diag *StreamDiag)

Buffers one compact status line for a stream drop and retry after logging the full warning

func EnabledSecretSourceNames

func EnabledSecretSourceNames(secretsCfg map[string]any, homePath string) map[string]bool

EnabledSecretSourceNames are the sources an apply would fetch for the home right now

func EnsureAuditLog

func EnsureAuditLog(auditPath string) error

EnsureAuditLog pre-creates the audit log 0600

func EnsureBuiltinSecretSources

func EnsureBuiltinSecretSources()

EnsureBuiltinSecretSources idempotently registers the bundled sources

func EntriesForRoute

func EntriesForRoute(baseURL string, customProviders []map[string]any, cfg map[string]any) []map[string]any

EntriesForRoute exposes the route entry match to the agent capability checks

func EntriesLabel

func EntriesLabel(n int) string

EntriesLabel renders 1 entry or N entries

func EntryDeclaresCredential

func EntryDeclaresCredential(entry map[string]any) bool

EntryDeclaresCredential reports whether a custom entry names its own credential

func EntryModelsDiscovered

func EntryModelsDiscovered(entry any) bool

Reports whether a provider entry marks its models as discovered

func EntryURL

func EntryURL(entry map[string]any) string

Exported entry URL read, api before url before base_url

func EnvWriterLaunchDenylist

func EnvWriterLaunchDenylist() map[string]bool

EnvWriterLaunchDenylist is every external process launch env name plus every left core row's launch env

func EnvelopeToolPartCacheMarkersSupported

func EnvelopeToolPartCacheMarkersSupported(providerName, baseURL string) bool

Reports whether the route accepts cache markers on tool parts

func EstimateMessageTokensRough

func EstimateMessageTokensRough(msg any, imageCost int) int

Memoized rough token weight of one message row at the given per image cost

func EstimateMessagesTokens

func EstimateMessagesTokens(msgs []*state.Message, imageCost int, chargeStaleThinking bool) int

Memoized rough token estimate of a message list for preflight decisions

func EstimateNativeAnthropicMessagesTokens

func EstimateNativeAnthropicMessagesTokens(ctx context.Context, messages []*state.Message) int

EstimateNativeAnthropicMessagesTokens charges replayed readable thinking once over the native Anthropic projection

func EstimateNativeAnthropicRequestTokens

func EstimateNativeAnthropicRequestTokens(ctx context.Context, messages []*state.Message, system string, tools []map[string]any) int

EstimateNativeAnthropicRequestTokens is the request estimate over the native projection, opaque replay never counted as text

func EstimateRequestContextTokens

func EstimateRequestContextTokens(ctx context.Context, payload any) int

Cheap char over four context estimate of a Chat, Responses or bare payload for the stale call detectors

func EstimateRequestTokens

func EstimateRequestTokens(ctx context.Context, msgs []*state.Message, system string, tools []map[string]any, chargeStaleThinking bool) int

Rough token estimate of a whole request, system prompt plus messages plus tool schemas

func EstimateRowsTokens

func EstimateRowsTokens(rows []map[string]any, imageCost int) int

Memoized tokens of dict message rows with every priced key of each dict counted

func EstimateTokens

func EstimateTokens(text string) int

Rough token estimate, CJK codepoints one token each and the rest ceil of UTF8 bytes over four

func EstimateToolsTokens

func EstimateToolsTokens(tools []map[string]any) int

Rough token estimate of tool schemas, names, descriptions and parameters JSON, memoised per tools list

func EvictOldScreenshots

func EvictOldScreenshots(result []map[string]any)

EvictOldScreenshots is the wire pass retiring screenshot payloads past the per request image limit

func EvictOldest

func EvictOldest[K comparable, V any](cache map[K]V, key K, stampOf func(V) time.Time, limit int, siblings ...func(K))

Drops the oldest stamped key from cache and every sibling once a new key would pass the limit

func ExactMoAPresetName

func ExactMoAPresetName(raw any, text string) string

ExactMoAPresetName returns the text when it names an enabled preset, empty otherwise

func ExcStatusCode

func ExcStatusCode(err error) int

HTTP status carried on the error itself or on its response, zero when absent

func ExpandDirectAPIAlias

func ExpandDirectAPIAlias(ctx context.Context, provider, existingBase string) (string, string)

Provider openai expanded onto custom plus the configured OpenAI endpoint, other providers unchanged

func ExternalProcessLaunchEnvNames

func ExternalProcessLaunchEnvNames() map[string]bool

ExternalProcessLaunchEnvNames lists the env names that choose an external provider's executable or argv

func ExtractAPIErrorContext

func ExtractAPIErrorContext(err error) map[string]any

ExtractAPIErrorContext pulls reason, message, and reset_at out of a provider error body, headers, and text

func ExtractCompressFlags

func ExtractCompressFlags(rawArgs string) (string, bool, bool)

Remaining args with preview, dry run and aggressive tokens removed anywhere, plus whether each was present

func ExtractContentOrReasoning

func ExtractContentOrReasoning(response any, maxReasoningChars int) string

ExtractContentOrReasoning is the response content without think blocks, else its reasoning fields bounded when the cap is not negative

func ExtractFallbackFromModelCfg

func ExtractFallbackFromModelCfg(modelCfg any) (map[string]any, bool, error)

ExtractFallbackFromModelCfg pulls provider, model, base_url and api_mode out of a config model snapshot

func ExtractToolCallsFromText

func ExtractToolCallsFromText(text string) ([]state.ToolCall, string, error)

Tool calls of an ACP response and its text minus consumed blocks, bare JSON tried only when no block parsed

func FallbackAPIModeHint

func FallbackAPIModeHint(ctx context.Context, fb map[string]any, fbProvider string, fbBaseURLHint *string) (bool, string, error)

FallbackAPIModeHint is the explicit flag and api mode of a fallback entry read from its original base url

func FallbackAPIModeResolved

func FallbackAPIModeResolved(ctx context.Context, agent FallbackAPIModeAgent, fbProvider, fbModel, fbBaseURL string) (string, error)

FallbackAPIModeResolved re-detects the wire from provider, resolved base url and model after the hint chose chat

func FallbackAdd

func FallbackAdd(ctx context.Context, w io.Writer, h string, store *Store, picker func() error) error

FallbackAdd runs the model picker, restores the primary route, then appends the pick to the chain

func FallbackClear

func FallbackClear(ctx context.Context, w io.Writer, h string, confirm func(out io.Writer, prompt string) (string, error)) error

FallbackClear empties the chain after a y or yes confirmation, an interrupted prompt cancelling

func FallbackCommand

func FallbackCommand(ctx context.Context, h string, ns map[string]any, w, errw io.Writer) (code int, err error)

FallbackCommand is icebath fallback dispatching on fallback_command, 2 for an unknown subcommand

func FallbackList

func FallbackList(ctx context.Context, w io.Writer, h string) error

FallbackList prints the primary and the fallback chain in order

func FallbackReasonText

func FallbackReasonText(reason FailoverReason) string

FallbackReasonText is the concise operator facing explanation for a fallback switch

func FallbackRemove

func FallbackRemove(ctx context.Context, w io.Writer, h string, choose func(question string, choices []string, def int, description string) (int, error)) error

FallbackRemove lets the chooser pick an entry, a cancel or out of range answer leaving the chain alone

func FastModeUnprovisioned

func FastModeUnprovisioned(apiErr *APIError, extraBody map[string]any, headers http.Header) bool

FastModeUnprovisioned reports a 429 on a speed fast request whose fast limit header is zero

func FeatureInUse

func FeatureInUse(f *LeftCoreFeature, h string, processEnv bool) bool

FeatureInUse reports the row predicate or a configured route at one of its hosts

func FetchAPIModels

func FetchAPIModels(ctx context.Context, apiKey, baseURL string, timeout time.Duration, apiMode string, headers map[string]string) ([]string, bool)

FetchAPIModels lists the model ids of a provider's models endpoint, false when no candidate answered

func FetchBitwardenSecrets

func FetchBitwardenSecrets(opts BitwardenFetchOptions) (map[string]string, []string, error)

FetchBitwardenSecrets pulls the project secrets, serving a stale last good entry only after a transport failure

func FetchCodexCatalogEntries

func FetchCodexCatalogEntries(get func(string) (*probeResponse, error), baseURL string) ([]any, int, error)

FetchCodexCatalogEntries returns the models of the first catalog url answering 200 with a non empty list

func FetchEndpointModelMetadata

func FetchEndpointModelMetadata(ctx context.Context, baseURL, apiKey string, forceRefresh bool) map[string]map[string]any

FetchEndpointModelMetadata reads an OpenAI compatible models endpoint, memoized per base url and key

func FetchLMStudioModels

func FetchLMStudioModels(ctx context.Context, apiKey any, baseURL string, timeout time.Duration) ([]string, error)

FetchLMStudioModels lists chat capable LM Studio keys, empty when unreachable, an AuthError on 401 or 403

func FetchModelMetadata

func FetchModelMetadata(ctx context.Context, forceRefresh bool) map[string]map[string]any

FetchModelMetadata returns the OpenRouter catalog, cached for an hour in memory and on disk

func FetchModelsDev

func FetchModelsDev(ctx context.Context, forceRefresh bool) map[string]any

FetchModelsDev returns the registry keyed by provider id, empty on failure, with the network allowed

func FetchOllamaCloudModels

func FetchOllamaCloudModels(ctx context.Context, opts OllamaCloudFetch) []string

FetchOllamaCloudModels returns the fresh disk cache, else live models merged with models.dev, else the stale cache

func FetchOllamaLocalModels

func FetchOllamaLocalModels(ctx context.Context, baseURL string, timeout time.Duration, headers map[string]string) ([]string, bool)

FetchOllamaLocalModels lists local Ollama models keeping a probe failure as false

func FetchOnePasswordSecrets

func FetchOnePasswordSecrets(opts OnePasswordFetchOptions) (map[string]string, []string, error)

FetchOnePasswordSecrets resolves references to values, only a complete pull is cached

func FileLock

func FileLock(lockPath string, timeout time.Duration, timeoutMessage string) (release func(), err error)

FileLock takes the cross process advisory lock at the path, reentrant per goroutine, failing with the message at the deadline

func FillProviderEnvVars

func FillProviderEnvVars()

FillProviderEnvVars reads the table once so its armed provider fill has run

func FindBws

func FindBws(installIfMissing bool) string

FindBws resolves the bws binary from PATH or the tool store, installing on a miss when asked

func FindCustomProviderIdentity

func FindCustomProviderIdentity(baseURL string, cfg map[string]any) string

FindCustomProviderIdentity maps an endpoint URL back to its canonical custom menu key

func FindCustomProviderIdentityByModel

func FindCustomProviderIdentityByModel(model string, cfg map[string]any) string

FindCustomProviderIdentityByModel maps a model id back to the custom entry that serves it

func FindEntryForModel

func FindEntryForModel(modelID string) (*CatalogEntry, *QuantVariant)

Entry and variant owning a staged model id, nil when no catalog build matches

func FindFirstThinkTag

func FindFirstThinkTag(buf []rune, tags [][]rune) (int, int)

Index and length of the earliest case insensitive tag in buf, minus one and zero when none

func FindOp

func FindOp(binaryPath string) string

FindOp resolves a usable op binary, a pinned path is used verbatim and never falls back to PATH

func FindProviderEntry

func FindProviderEntry(providers any, key any) (string, map[string]any)

FindProviderEntry returns the stored key and block matching a provider key by string identity

func FingerprintSecretValue

func FingerprintSecretValue(value any) string

FingerprintSecretValue returns sha256 prefixed sixteen hex digest of a secret or empty for blank input

func FinishAuxCallHooks

func FinishAuxCallHooks(ctx context.Context, hooks *AuxCallHooks, response any, callErr error, normalized *AuxNormalizedReply)

FinishAuxCallHooks closes the attempt with post_auxiliary_call

func FirstChoiceMessage

func FirstChoiceMessage(response any) (any, error)

FirstChoiceMessage is response.choices[0].message, the AttributeError or IndexError Python indexing raises otherwise

func FirstProxyEnvValue

func FirstProxyEnvValue() string

FirstProxyEnvValue is the first non empty proxy variable value, any case

func FixedTemperatureForModel

func FixedTemperatureForModel(model, baseURL, provider string) (omit bool, fixed *float64, err error)

FixedTemperatureForModel is the omit flag or fixed temperature a route sends for the model

func FlattenExceptionChain

func FlattenExceptionChain(err error) string

Renders Outer(msg) <- Inner(msg) walking the wrapped causes, deduplicated and at most four deep

func FlattenMessageText

func FlattenMessageText(content any, sep string) string

FlattenMessageText exports the visible text join of message content shapes

func FloorReasoningConfig

func FloorReasoningConfig(reasoningConfig any) any

FloorReasoningConfig lifts a disabled reasoning config to the floor and returns anything else unchanged

func FootprintBytes

func FootprintBytes(profile ModelProfile, window int, flashAttention bool, overheadBytes int64) int64

Complete estimated footprint of weights, window memory and runtime overhead

func ForceCloseTCPSockets

func ForceCloseTCPSockets(client any) int

ForceCloseTCPSockets aborts in flight TCP reads and writes on every pool socket of the client

func ForgetMessageTokenMemo

func ForgetMessageTokenMemo(messages any, keep any) int

ForgetMessageTokenMemo evicts entries pinning any long string of the messages that keep does not hold

func ForgetPluginGrants

func ForgetPluginGrants(plugin string) error

ForgetPluginGrants drops every grant of a plugin key from the active profile

func FormatAuthError

func FormatAuthError(err *AuthError) string

FormatAuthError maps an auth failure onto concise user facing guidance

func FormatCostLabel

func FormatCostLabel(amount *big.Rat) string

FormatCostLabel renders zero as $0.00, sub cent amounts at four places and everything else at two

func FormatCount

func FormatCount(n int) string

FormatCount renders 7999856 as 8.0M and 33599 as 33.6K

func FormatDurationCompact

func FormatDurationCompact(seconds float64) string

FormatDurationCompact renders seconds as s, m, h m or fractional days

func FormatEgressStatusText

func FormatEgressStatusText(h string, showTokens bool) (string, error)

FormatEgressStatusText is the plain text egress status for slash commands

func FormatFallbackEntry

func FormatFallbackEntry(entry map[string]any) string

FormatFallbackEntry renders one chain entry as model (via provider) with the base URL when set

func FormatModelForDisplay

func FormatModelForDisplay(modelName string) string

FormatModelForDisplay strips opaque proxy prefixes from a model id for status output only

func FormatPercentUsed

func FormatPercentUsed(usedFraction float64) string

FormatPercentUsed floors the used share to a whole percent, a sliver reading below one percent

func FormatPricePerMtok

func FormatPricePerMtok(perToken string) string

FormatPricePerMtok renders a per token price string as dollars per million tokens

func FormatRateLimitCompact

func FormatRateLimitCompact(s *RateLimitState, now time.Time) string

FormatRateLimitCompact renders the one line RPM RPH TPM TPH summary for status bars

func FormatResetWindow

func FormatResetWindow(d time.Duration) string

FormatResetWindow renders a ceilinged ~9h or ~45 min label for quota reopening copy

func FormatResetsIn

func FormatResetsIn(resetsAtMs, nowMs *int64) string

FormatResetsIn reads the reset as resets in a duration, or resets soon when past or unknown

func FormatRetirementIssue

func FormatRetirementIssue(issue RetirementIssue) string

FormatRetirementIssue renders one retirement issue as a single human readable line

func FormatRuntimeProviderError

func FormatRuntimeProviderError(err error) string

FormatRuntimeProviderError renders a resolution failure as concise user facing guidance

func FormatSeconds

func FormatSeconds(seconds float64) string

FormatSeconds renders 58s, 2m 14s, or 1h 2m

func FormatSecretSourceSuffix

func FormatSecretSourceSuffix(h, envVar string) string

FormatSecretSourceSuffix is the from X suffix naming the external source, empty for .env and shell keys

func FrozenRuntimeConfig

func FrozenRuntimeConfig(ctx context.Context) map[string]any

FrozenRuntimeConfig is the frozen session config scoped on the context, nil outside a frozen scope

func GGUFReadSkippable

func GGUFReadSkippable(err error) bool

Reports whether err is one callers treat as an unreadable model, a ValueError or an OS error

func GetAPIKeyProviderStatus

func GetAPIKeyProviderStatus(env PoolEnv, providerID string) map[string]any

GetAPIKeyProviderStatus is the status snapshot for an API key provider

func GetAnthropicKey

func GetAnthropicKey(ctx context.Context) string

First usable Anthropic credential over the registry env vars, the home dotenv beating a stale shell export

func GetAuthStatus

func GetAuthStatus(env PoolEnv, providerID string) map[string]any

GetAuthStatus dispatches to the bespoke builder, then the registry auth type, for the provider or the active one

func GetAuthenticatedProviderSlugs

func GetAuthenticatedProviderSlugs(ctx context.Context, currentProvider string, userProviders map[string]any, customProviders []any) []string

GetAuthenticatedProviderSlugs lists providers holding credentials from cached catalogs without blocking on a fetch

func GetAvailableVisionBackends

func GetAvailableVisionBackends(ctx context.Context) ([]string, error)

GetAvailableVisionBackends lists usable vision backends in auto order, the active provider first

func GetCachedContextLength

func GetCachedContextLength(ctx context.Context, model, baseURL string, bedrockConfirmed bool) (int, bool)

GetCachedContextLength looks up a persisted window, optionally requiring Bedrock confirmation

func GetCatalog

func GetCatalog(ctx context.Context, forceRefresh bool) map[string]any

GetCatalog returns the fetched or cached manifest, else the shipped one, serving a stale disk copy while refreshing off thread

func GetCodexAuthStatus

func GetCodexAuthStatus(env PoolEnv) map[string]any

GetCodexAuthStatus is the read only Codex status snapshot, pool first then the legacy provider state

func GetCodexModelIDs

func GetCodexModelIDs(ctx context.Context, accessToken, baseURL string) ([]string, bool)

GetCodexModelIDs is live discovery with a token, else config default, local cache and defaults as a curated fallback

func GetConfiguredCodexBinary

func GetConfiguredCodexBinary(cfg map[string]any) string

Configured model.codex_bin as one argv element, bare codex from PATH when unset

func GetContextLengthFromProviderError

func GetContextLengthFromProviderError(errorMsg string, current int) (int, bool)

GetContextLengthFromProviderError returns a provider reported limit lower than the current window

func GetCurrentCodexRuntime

func GetCurrentCodexRuntime(cfg map[string]any) string

Configured model.openai_runtime, auto when unset, empty or unrecognized

func GetCustomProviderPoolKey

func GetCustomProviderPoolKey(baseURL, providerName string, cfg map[string]any) string

GetCustomProviderPoolKey is the preferred pool key for a custom provider, durable slug else custom name

func GetDefaultModelForProvider

func GetDefaultModelForProvider(ctx context.Context, provider string) string

GetDefaultModelForProvider is the cost safe non interactive default for a configured provider without a model

func GetEnvPreferDotenv

func GetEnvPreferDotenv(env PoolEnv, key string) string

GetEnvPreferDotenv resolves a credential env var preferring the profile .env over the scope

func GetExternalProcessProviderStatus

func GetExternalProcessProviderStatus(env PoolEnv, providerID string) map[string]any

GetExternalProcessProviderStatus is the structural status of a provider that runs a local subprocess

func GetFallbackChain

func GetFallbackChain(cfg map[string]any) []map[string]any

GetFallbackChain merges fallback_providers then legacy fallback_model entries, dropping same route duplicates

func GetLoadingProgress

func GetLoadingProgress() map[string]LoadProgress

Models loading right now with stage, value and percent, starting the watcher on first use

func GetMinimaxOAuthAuthStatus

func GetMinimaxOAuthAuthStatus(env PoolEnv) map[string]any

GetMinimaxOAuthAuthStatus is the MiniMax OAuth status snapshot

func GetNamedCustomProvider

func GetNamedCustomProvider(ctx context.Context, name string) map[string]any

GetNamedCustomProvider is the named endpoint entry with credentials resolved, nil when none matches

func GetPoolStrategy

func GetPoolStrategy(cfg map[string]any, provider string) string

GetPoolStrategy is the configured selection strategy for a provider

func GetPreferredSilentDefaultModel

func GetPreferredSilentDefaultModel(ctx context.Context, provider string) string

GetPreferredSilentDefaultModel is the cached manifest's labeled default else the shipped constant

func GetPrefillProgress

func GetPrefillProgress(model string) (processed int64, ok bool, err error)

Prompt tokens processed by the busiest processing slot for model, ok false when idle, unreachable or foreign

func GetProviderLabel

func GetProviderLabel(ctx context.Context, providerID string) string

GetProviderLabel returns the label override, else the models.dev or profile name, else the canonical id

func GetProviderRequestTimeout

func GetProviderRequestTimeout(ctx context.Context, providerID, model string) (float64, bool)

Configured provider request timeout in seconds from the home config

func GetProviderStaleTimeout

func GetProviderStaleTimeout(ctx context.Context, providerID, model string) (float64, bool)

Configured provider stale timeout in seconds from the home config

func GetQwenAuthStatus

func GetQwenAuthStatus(env PoolEnv) map[string]any

Qwen OAuth status of the status command, refresh validated so a stale CLI token never reads as logged in

func GetSecret

func GetSecret(ctx context.Context, name string) (string, bool, error)

GetSecret resolves a credential by env var name honoring the scope carried by ctx

func GetSecretStr

func GetSecretStr(ctx context.Context, name, def string) string

GetSecretStr is GetSecret with a default, an unscoped read still panics

func GetXAIOAuthAuthStatus

func GetXAIOAuthAuthStatus(env PoolEnv) map[string]any

GetXAIOAuthAuthStatus is the xAI OAuth status snapshot, device code being the only xAI flow

func Getpass

func Getpass(prompt string) (string, error)

Getpass is the echo free terminal line read with its stdin fallback

func GrokSupportsReasoningEffort

func GrokSupportsReasoningEffort(model string) bool

GrokSupportsReasoningEffort allowlists Grok ids that accept the effort dial

func HandleMaxIterations

func HandleMaxIterations(ctx context.Context, agent ChatCompletionAgent, messages *[]map[string]any) (final string, err error)

Summary of the turn once max iterations is reached, the final response text of the turn

func HasAWSCredentials

func HasAWSCredentials(ctx context.Context, instanceMetadata bool) bool

HasAWSCredentials reports whether any AWS credential source resolves for the process

func HasAccountUsage

func HasAccountUsage(ctx context.Context, provider string) bool

HasAccountUsage reports a provider that can report usage windows through a built in fetcher or a profile hook

func HasCodexContextVariant

func HasCodexContextVariant(modelBare string) bool

HasCodexContextVariant is the picker side alias of the eligibility check

func HasCompactionCheckpoint

func HasCompactionCheckpoint(items []map[string]any) bool

HasCompactionCheckpoint reports whether a reasoning sidecar carries a compaction checkpoint

func HasCuratedCatalog

func HasCuratedCatalog(provider string) bool

HasCuratedCatalog reports whether the curated table has a row for the provider

func HasKnownPricing

func HasKnownPricing(ctx context.Context, modelName, provider, baseURL, apiKey string) bool

HasKnownPricing reports whether any rate card covers the model route

func HasNamedCustomProvider

func HasNamedCustomProvider(ctx context.Context, h, name string) bool

Reports whether the home's config defines a providers or custom_providers entry for the name

func HasRateLimitHeaders

func HasRateLimitHeaders(lowered map[string]string) bool

HasRateLimitHeaders reports any x-ratelimit prefixed header

func HasUsableSecret

func HasUsableSecret(value any, minLength int) bool

True for a string secret of at least minLength characters that is no known placeholder

func HeaderKeys

func HeaderKeys(m map[string]string) []string

HeaderKeys are the keys of a header map in the order a Python dict of them iterates

func HomeRawConfig

func HomeRawConfig(h string) map[string]any

HomeRawConfig is the raw config.yaml of a home, empty when missing, unreadable or not a mapping

func HomeRawConfigForWrite

func HomeRawConfigForWrite(path string) (map[string]any, error)

HomeRawConfigForWrite is the raw config.yaml at a path for a write back, empty when missing, failing on malformed YAML

func HomeYAMLLayers

func HomeYAMLLayers(h string) (map[string]any, error)

HomeYAMLLayers is the config.yaml of a home as the gateway loader reads it, env references expanded and the managed overlay applied

func HookFailed

func HookFailed(p *Profile, hook string, scope any) bool

HookFailed reports whether the profile's hook already failed in scope so asking answers the fallback

func HookJSONable

func HookJSONable(value any, caps HookJSONCaps) any

HookJSONable coerces any value into JSON safe data with redacted secret keys and bounded size

func HookPayloadMaxChars

func HookPayloadMaxChars() int

HookPayloadMaxChars reads the payload cap from the environment with a 1000 char floor

func HostGatedEnvKeyCandidates

func HostGatedEnvKeyCandidates(ctx context.Context, h, baseURL string, ollama bool) []string

Env keys a base URL host would receive, then its host derived vendor key

func HostInstallHint

func HostInstallHint(baseURL string) string

HostInstallHint names the install sentence for a left core host whose providers are all unregistered

func HostMatches

func HostMatches(rawURL, domain string) bool

HostMatches reports whether the URL host equals the domain or is a subdomain of it

func HostSetupFlow

func HostSetupFlow(asker SetupAsker, out io.Writer, fn func() error) (err error)

HostSetupFlow runs fn with every setup prompt put to ask and every printed line written to out

func HostedModelEntry

func HostedModelEntry(entry string) bool

Reports whether a model section can open straight at the named picker row or registered provider profile

func Hostname

func Hostname(rawURL string) string

Hostname returns the lowercase host of a URL without port, userinfo, or trailing dot

func HydrateProfileSecretSources

func HydrateProfileSecretSources(h string) map[string]string

HydrateProfileSecretSources resolves one profile's sources into a private mapping without touching the process env

func IcebathOAuthFile

func IcebathOAuthFile(env PoolEnv) string

The icebath owned Anthropic PKCE credential file of the home

func IcebathOverlays

func IcebathOverlays(ctx context.Context) map[string]IcebathOverlay

IcebathOverlays returns the static overlays plus those the bound home's profiles declare

func ImageCostContext

func ImageCostContext(ctx context.Context, cost *int) context.Context

ImageCostContext scopes a per image price over the returned context, nil restoring the flat default

func ImageDimensionsFromBytes

func ImageDimensionsFromBytes(raw []byte) (int, int, bool)

ImageDimensionsFromBytes is the width and height read from PNG or JPEG headers, false when unreadable

func ImagesAllWithinManyImageLimit

func ImagesAllWithinManyImageLimit(datas []string) bool

Whether every image payload fits the per image limit that applies once many images ride one request

func InstallBws

func InstallBws() (string, error)

InstallBws is the explicit setup or repair install of the pinned bws binary

func InstallOpener

func InstallOpener(opener *Opener)

InstallOpener makes opener the process wide policy credentialed requests clone, nil uninstalls it

func InstallPluginManagerHooks

func InstallPluginManagerHooks(h PluginManagerHooks)

InstallPluginManagerHooks wires the plugin manager into provider resolution and the left core migration

func InstallSafeStdio

func InstallSafeStdio()

Ignores SIGPIPE at agent startup so a vanished stdout or stderr pipe never kills the process

func InstallTrustStore

func InstallTrustStore() bool

InstallTrustStore loads the OS trust store once, false when no platform root could be read

func InterruptibleAPICall

func InterruptibleAPICall(ctx context.Context, agent ChatCompletionAgent, apiKwargs map[string]any) (any, error)

Runs the agent's blocking call inline for nested pool routes, else on a worker the interrupt and stale watchdogs poll

func InterruptibleStreamingAPICall

func InterruptibleStreamingAPICall(ctx context.Context, agent ChatCompletionAgent, apiKwargs map[string]any, onFirstDelta func()) (any, error)

Streaming request on the agent wire firing the delta callbacks, the non streaming response shape on return

func InvalidateBedrockRuntimeClient

func InvalidateBedrockRuntimeClient(ctx context.Context, region string) bool

InvalidateBedrockRuntimeClient evicts every read timeout slot of one region's runtime clients

func InvalidateCachedContextLength

func InvalidateCachedContextLength(ctx context.Context, model, baseURL string)

Exported invalidation for tests of other packages

func IronAllowlistedEnv

func IronAllowlistedEnv() map[string]string

IronAllowlistedEnv is the infrastructure only environment, never the operator's secrets

func IsActualRoute

func IsActualRoute(providerName, baseURL string) bool

IsActualRoute identifies Actual Computer by provider alias or its hosted endpoint

func IsAggregatorModelProvider

func IsAggregatorModelProvider(name string) bool

Whether a provider is one of the aggregators that want vendor prefixed model names

func IsAggregatorProvider

func IsAggregatorProvider(slug string) bool

IsAggregatorProvider reports membership in the catalog aggregator set including plugin admissions

func IsAnthropicFastModeModel

func IsAnthropicFastModeModel(model string) bool

IsAnthropicFastModeModel accepts vendor prefixed, dotted, variant and dated spellings

func IsAnthropicOAuthToken

func IsAnthropicOAuthToken(key string) bool

IsAnthropicOAuthToken is true for OAuth and setup tokens, false for the Console API key families

func IsAvailableSafe

func IsAvailableSafe(provider AvailabilityProvider, logger *slog.Logger, format string, level slog.Level, excInfo bool) bool

Availability of a provider, a panicking probe reading as unavailable and logged at level with its traceback when excInfo

func IsBorrowedCredentialSource

func IsBorrowedCredentialSource(source, providerID string) bool

IsBorrowedCredentialSource reports whether a pool source is reference only and must never persist secrets

func IsCancelled

func IsCancelled(err error) bool

IsCancelled is true for an interrupted prompt, a closed stdin, or a clean exit

func IsCapabilityRejection

func IsCapabilityRejection(err error) bool

IsCapabilityRejection reports whether a structured output rejection speaks to the route capability rather than one schema

func IsClaudeCodeTokenValid

func IsClaudeCodeTokenValid(creds map[string]any) bool

IsClaudeCodeTokenValid is a non expired access token with a 60s buffer, a missing expiry means managed key

func IsCodex900kBase

func IsCodex900kBase(model string) bool

IsCodex900kBase is the single source of truth for 900k eligibility

func IsCodexContextVariant

func IsCodexContextVariant(model string) bool

IsCodexContextVariant requires both the suffix and an eligible base

func IsCodexGPT54OrGPT55

func IsCodexGPT54OrGPT55(model, provider string) bool

True for the 272K capped gpt-5.4 to 5.6 and gpt-6 families on the Codex OAuth route

func IsCodexSpark

func IsCodexSpark(model, provider string) bool

True for gpt-5.3-codex-spark on the Codex OAuth route

func IsCustomRuntime

func IsCustomRuntime(env PoolEnv, provider, requestedProvider, baseURL string) bool

IsCustomRuntime reports a runtime identity that is a custom entry's, whose pool comes from LoadRuntimePool and never a raw LoadPool of a slug a built-in may share

func IsEntitlement403

func IsEntitlement403(agent AuthRecoveryAgent, statusCode int, errorContext map[string]any) bool

IsEntitlement403 is a 403 that looks like an auth failure but refresh cannot fix

func IsEntitlementFailure

func IsEntitlementFailure(errorContext map[string]any, status int) bool

IsEntitlementFailure detects subscription 401 or 403 bodies that a token refresh cannot fix

func IsEnvSettingKey

func IsEnvSettingKey(key string) bool

IsEnvSettingKey reports whether a bare config key is stored in .env rather than config.yaml

func IsExpiring

func IsExpiring(expiresAt any, skew time.Duration) bool

IsExpiring reports whether an ISO expiry is missing, unparseable or within skew of now

func IsExternalProcessProvider

func IsExternalProcessProvider(ctx context.Context, provider string) bool

Provider runs as a local external process rather than an HTTP endpoint

func IsForeignProviderEndpoint

func IsForeignProviderEndpoint(provider, baseURL string) bool

IsForeignProviderEndpoint reports whether the base URL is another built in provider's canonical endpoint

func IsForkCacheScope

func IsForkCacheScope(scope string) bool

IsForkCacheScope reports whether the scope carries a fork tag

func IsGeminiNativeProviderName

func IsGeminiNativeProviderName(name string) bool

IsGeminiNativeProviderName reports a provider name served by the native Gemini client

func IsGlobalEnv

func IsGlobalEnv(name string) bool

IsGlobalEnv is true for process deployment settings that are never profile secrets

func IsGrok46Family

func IsGrok46Family(model string) bool

IsGrok46Family reports whether the id belongs to the Grok 4.6 family

func IsImportSourceName

func IsImportSourceName(name string) bool

IsImportSourceName reports whether name is one of the importers

func IsKnownNonChatModel

func IsKnownNonChatModel(model string) bool

IsKnownNonChatModel is true when the name shape or an already parsed catalog item says not chat

func IsLiveFirstPickerProvider

func IsLiveFirstPickerProvider(provider string) bool

IsLiveFirstPickerProvider reports whether live entries lead the picker for the provider

func IsLlamaCppAlias

func IsLlamaCppAlias(name string) bool

IsLlamaCppAlias reports whether the name addresses the managed llama.cpp runtime

func IsLocalEndpoint

func IsLocalEndpoint(baseURL string) bool

IsLocalEndpoint is true for loopback, container DNS, unqualified, private, link local and Tailscale hosts

func IsLocalValidationError

func IsLocalValidationError(err error) bool

IsLocalValidationError reports a local bug rather than a provider, transport, or stream failure

func IsLoopbackHost

func IsLoopbackHost(host string) bool

IsLoopbackHost reports whether the host names the local machine

func IsManagedEndpoint

func IsManagedEndpoint(baseURL string) bool

True when the URL is the server the managed runtime state file points at

func IsManagedLocalEndpoint

func IsManagedLocalEndpoint(baseURL string) bool

IsManagedLocalEndpoint reports whether a base URL targets the llama-server this install manages

func IsManagedProvider

func IsManagedProvider(provider, baseURL string) (managed bool)

Whether provider and baseURL point at the managed server, custom only when baseURL is that endpoint

func IsMandatoryThinkingClaude

func IsMandatoryThinkingClaude(model string) bool

Claude model that always thinks and rejects a thinking disable

func IsModelsDevPreferred

func IsModelsDevPreferred(provider string) bool

IsModelsDevPreferred reports whether models.dev beats the curated list for the provider

func IsMultiplexActive

func IsMultiplexActive(ctx context.Context) bool

IsMultiplexActive is true in a multiplexing process or for a task under multiplex semantics

func IsNativeAnthropicHost

func IsNativeAnthropicHost(baseURL string) bool

IsNativeAnthropicHost is true when the base URL is exactly api.anthropic.com or empty

func IsNativeCompactionRejection

func IsNativeCompactionRejection(errText string, statusCode int) bool

IsNativeCompactionRejection reports a structured 400 rejection of context_management

func IsNativeGeminiBaseURL

func IsNativeGeminiBaseURL(baseURL string) bool

IsNativeGeminiBaseURL reports whether a base URL is served by the native Gemini adapter

func IsNetworkError

func IsNetworkError(err error) bool

IsNetworkError is true for connection, DNS, and timeout failures from the transport

func IsNetworkResolutionFailure

func IsNetworkResolutionFailure(err error) bool

IsNetworkResolutionFailure walks the unwrap chain for DNS or unreachable network failures

func IsNoninteractive

func IsNoninteractive() bool

IsNoninteractive reports a spawn with no human to answer prompts, ICEBATH_NONINTERACTIVE truthy

func IsOAuthToken

func IsOAuthToken(key string) bool

IsOAuthToken reports an OAuth or setup token shape rather than a Console API key

func IsOfficialOpenAIHost

func IsOfficialOpenAIHost(rawURL string) bool

IsOfficialOpenAIHost reports whether the URL points at api.openai.com or a data residency subdomain

func IsOpencodeTarget

func IsOpencodeTarget(provider, baseURL string) bool

IsOpencodeTarget reports whether the provider or base URL addresses the OpenCode relay

func IsOutputCapError

func IsOutputCapError(errorMsg string) bool

IsOutputCapError reports a max_tokens cap rejection that is not an oversized input

func IsPresetFieldPath

func IsPresetFieldPath(parts []string) bool

IsPresetFieldPath reports whether split config path parts name a preset field or an aggregator slot field

func IsProcessHome

func IsProcessHome(h string) bool

Reports whether a home is the process home, the exported face for pkg/mcp

func IsPromptInterrupt

func IsPromptInterrupt(err error) bool

IsPromptInterrupt reports the KeyboardInterrupt or EOFError a picker prompt raised

func IsProviderEnabled

func IsProviderEnabled(providerCfg any) bool

IsProviderEnabled reports whether a providers block is enabled, with only an explicit false hiding it

func IsProviderExplicitlyConfigured

func IsProviderExplicitlyConfigured(env PoolEnv, providerID string) bool

IsProviderExplicitlyConfigured is true only when the user configured the provider through an explicit flow

func IsProviderStreamParseError

func IsProviderStreamParseError(err error) bool

IsProviderStreamParseError reports a wire level stream frame parse failure rather than local JSON validation

func IsProxyLoopbackHost

func IsProxyLoopbackHost(host string) bool

IsProxyLoopbackHost is true for localhost or any loopback IP literal including the v4 mapped form

func IsRateLimitedAuthError

func IsRateLimitedAuthError(err error) bool

IsRateLimitedAuthError reports an auth failure that is upstream rate limiting rather than a credential problem

func IsReasoningFieldRejection

func IsReasoningFieldRejection(errorMsg string) bool

IsReasoningFieldRejection matches a 400 rejecting a reasoning wire control by name

func IsReasoningLevelRejection

func IsReasoningLevelRejection(errorMsg string) bool

IsReasoningLevelRejection matches a 400 refusing the disabled level against a closed effort set

func IsReasoningRequiredRejection

func IsReasoningRequiredRejection(errorMsg string) bool

IsReasoningRequiredRejection matches a 400 saying reasoning cannot be switched off

func IsRefreshableOAuthProvider

func IsRefreshableOAuthProvider(provider string) bool

IsRefreshableOAuthProvider is the built in refreshable set or a plugin profile shipping refresh_credential

func IsRegisteredEnvName

func IsRegisteredEnvName(name string) bool

IsRegisteredEnvName reports whether icebath itself enumerates the variable name

func IsRepetitionDominated

func IsRepetitionDominated(text string) bool

IsRepetitionDominated reports a contiguous run of exact repeats covering at least half the text

func IsRotationConsumedUncommitted

func IsRotationConsumedUncommitted(secret, sourcePath string) bool

IsRotationConsumedUncommitted is true when the secret belongs to a rotation that was spent but not committed

func IsRoutableProvider

func IsRoutableProvider(ctx context.Context, provider string) bool

Whether a provider name currently resolves to a routable route under the context home config

func IsRoutingAggregator

func IsRoutingAggregator(providerName string) bool

IsRoutingAggregator excludes flat namespace resellers whose catalog is first party

func IsRunawayRepetition

func IsRunawayRepetition(text string) bool

IsRunawayRepetition requires domination plus mostly duplicate lines when the text has line structure

func IsSecretPayloadKey

func IsSecretPayloadKey(key string) bool

Exported payload key secret classification

func IsSensitiveHookKey

func IsSensitiveHookKey(key string) bool

IsSensitiveHookKey reports a credential bearing key such as api_key, authorization, or any _api_key suffix

func IsSetupHiddenEnv

func IsSetupHiddenEnv(name string) bool

IsSetupHiddenEnv reports whether a variable is self configuring and stays out of setup forms

func IsSlotKeyedCacheRoute

func IsSlotKeyedCacheRoute(providerName, model, baseURL string) bool

IsSlotKeyedCacheRoute reports whether the cache key pins one server side slot per conversation as xAI does

func IsStreamEventOrderError

func IsStreamEventOrderError(err error) bool

Whether a stream failed because an event arrived before message_start

func IsStreamStall

func IsStreamStall(err error) bool

Whether a failure is a stream that stopped producing output after it had started

func IsTerminalAnthropicRefreshError

func IsTerminalAnthropicRefreshError(err error) bool

IsTerminalAnthropicRefreshError is true when retrying the same refresh token cannot succeed

func IsTerminalPluginRefreshError

func IsTerminalPluginRefreshError(err error) bool

IsTerminalPluginRefreshError is a structured auth error asking for re-login or carrying a grant dead code

func IsTokenProvider

func IsTokenProvider(value any) bool

IsTokenProvider reports a callable token minter rather than a string key

func IsTruthyValue

func IsTruthyValue(v any) bool

Reports whether a config or env value spells a truthy flag the way is_truthy_value does

func IsValidEnvName

func IsValidEnvName(name string) bool

IsValidEnvName is true for a legal environment variable name

func IsVertexExpressBaseURL

func IsVertexExpressBaseURL(normalized string) bool

Whether an aiplatform base URL speaks the native Gemini API with an API key

func IsZAICodingOverload

func IsZAICodingOverload(baseURL, model string, err error) bool

IsZAICodingOverload matches only the narrow 429 code 1305 shape on the Z.AI coding GLM-5.2 endpoint

func IterationSummaryAPIMessages

func IterationSummaryAPIMessages(agent ChatCompletionAgent, messages []map[string]any) []map[string]any

IterationSummaryAPIMessages are the wire ready summary messages the agent's request builder produces

func JitteredBackoff

func JitteredBackoff(attempt int, opts BackoffOptions) time.Duration

JitteredBackoff returns min(base*2^(attempt-1), max) plus uniform jitter up to ratio times that delay

func KVDtypeFactor

func KVDtypeFactor(flashAttention bool) float64

KV bytes per f16 element factor, q8_0 with flash attention and f16 without

func KillProcessTree

func KillProcessTree(pid int, sig syscall.Signal) bool

KillProcessTree signals a process and every descendant, children first then the group, true when anything was signalled

func KnownReasoningFloor

func KnownReasoningFloor(ctx context.Context, reasoningConfig any, provider, baseURL, model, task string) (any, error)

KnownReasoningFloor lifts a disabled reasoning config to the floor when the route and model refuse a disable

func LMStudioModelReasoningOptions

func LMStudioModelReasoningOptions(ctx context.Context, model, baseURL string, apiKey any, timeout time.Duration) []string

LMStudioModelReasoningOptions lists the reasoning allowed options LM Studio publishes for a model

func Label

func Label(providerID string) string

Label returns the display name for a provider id, alias, or custom slug

func LabelFromToken

func LabelFromToken(token, fallback string) string

LabelFromToken picks the email like claim of a JWT as the display label

func Ladder

func Ladder(native int) []int

Window rungs from the floor growing by half each step, native always last

func LadderReason

func LadderReason(reason FailoverReason) bool

LadderReason reports a transient transport verdict the post exhaustion recovery ladder may wait out

func LadderStopHint

func LadderStopHint(platform string) string

LadderStopHint names how a platform stops a ladder wait, the send stop hint for an unlisted platform

func LanguageCatalog

func LanguageCatalog() config.LanguageCatalog

Language catalog config set display.language validates against

func LatchedRetireCount

func LatchedRetireCount(retire int, carrierIDsNewestFirst []string, retiredIDs map[string]bool) int

Widens the retire count through the newest earlier retired carrier and records the carriers retired now

func LaunchArgs

func LaunchArgs(profile ModelProfile, decision *WindowDecision, flashAttention, mtpCapable bool,
	mtpDraftDepth int, uma, mtpPrefill bool) []string

Per model llama-server flags for a window decision with q8 KV under flash attention and discrete spill placement

func LaunchModelSeed

func LaunchModelSeed(ctx context.Context, sourceCfg map[string]any) map[string]any

Model block plus the endpoint definition it selects, copied as written, empty when the source has no model

func LaunchSecretScope

func LaunchSecretScope(launchHome string) map[string]string

Launch profile secret mapping, its env file and external sources winning over the launch env

func LaunchSecretScopeCtx

func LaunchSecretScopeCtx(ctx context.Context, launchHome string) map[string]string

Launch profile secret mapping with the task's multiplex semantics deciding frozen or live launch env

func LaunchTerminalEnv

func LaunchTerminalEnv() map[string]string

Frozen launch TERMINAL_ overlay for a launch profile turn's terminal scope

func LearnedImageTokenCost

func LearnedImageTokenCost(ctx context.Context, model, baseURL string) int

LearnedImageTokenCost is the learned per image price for model at the base URL host, else the flat default

func LeftCoreFailedRecently

func LeftCoreFailedRecently(h, plugin string) bool

LeftCoreFailedRecently reports a last failure younger than an hour doubled per failure, capped at a week

func LeftCoreFailureStamp

func LeftCoreFailureStamp(h, plugin string) string

LeftCoreFailureStamp is the path of the stamp a failed automatic plugin install leaves in a home

func LeftCoreFirstCause

func LeftCoreFirstCause(errText string) string

LeftCoreFirstCause is the one line of an install error a notice shows

func LeftCoreVersions

func LeftCoreVersions() []int

LeftCoreVersions lists every config version a row left core at, ascending

func ListAgenticModels

func ListAgenticModels(ctx context.Context, provider string, allowNetwork bool) []string

ListAgenticModels returns tool calling model ids minus hidden and noise entries

func ListAuthenticatedProviders

func ListAuthenticatedProviders(ctx context.Context, opts AuthenticatedProvidersOptions) ([]map[string]any, error)

ListAuthenticatedProviders lists the providers holding credentials with their curated or discovered models

func ListCustomPoolProviders

func ListCustomPoolProviders(store *Store) []string

ListCustomPoolProviders lists every custom prefixed pool key that holds rows in auth.json

func ListModelsDevModels

func ListModelsDevModels(ctx context.Context, provider string, allowNetwork bool) []string

ListModelsDevModels returns every model id of a provider minus the hidden Google rows

func ListPickerProviders

func ListPickerProviders(ctx context.Context, opts PickerProvidersOptions) ([]map[string]any, error)

ListPickerProviders is the interactive picker listing, OpenRouter filtered live and empty rows dropped

func LiveLoopTable

func LiveLoopTable[T any](tables map[any]T, loop any, lock sync.Locker, same func(a, b any) bool, closed func(any) bool, newTable func() T) T

Table of the loop under the lock, tables of loops closed since the last call dropped, keys strong on purpose

func LlamacppContext

func LlamacppContext(client *probeClient, serverURL, model string) (int, bool, error)

LlamacppContext reads the runtime n_ctx from props else the router launch ctx size

func LoadConfigSafe

func LoadConfigSafe(ctx context.Context, h string) map[string]any

LoadConfigSafe is the context's frozen runtime config else the home's read only config, nil on any error

func LoadDotenvFile

func LoadDotenvFile(path string, override bool) error

Loads one dotenv file with override as its own pass, the direct reload path

func LoadIcebathDotenv

func LoadIcebathDotenv(ctx context.Context, opts DotenvLoadOptions) ([]string, error)

Loads the home .env over shell exports, the op and project files filling gaps and the managed .env last

func LoadModelMetadataDiskCache

func LoadModelMetadataDiskCache(ctx context.Context) map[string]map[string]any

Model metadata rows of the on disk cache keyed by model id

func LoadWindowOverrides

func LoadWindowOverrides() map[string]int

Model id to granted window, empty on any read problem

func LocalModelsActivate

func LocalModelsActivate(ctx context.Context, modelID string) (map[string]any, error)

LocalModelsActivate starts the job making a downloaded model the default for new chats with the server up

func LocalModelsCatalog

func LocalModelsCatalog(ctx context.Context) (map[string]any, error)

LocalModelsCatalog prices every catalog entry for this machine with the recommended pick marked

func LocalModelsHardware

func LocalModelsHardware(ctx context.Context) (map[string]any, error)

LocalModelsHardware reports the machine budget as plain facts with live NVIDIA readings where present

func LocalModelsHumanGB

func LocalModelsHumanGB(n float64) string

LocalModelsHumanGB renders bytes as gibibytes with one decimal

func LocalModelsJobView

func LocalModelsJobView(jobID string) (map[string]any, error)

LocalModelsJobView is the job view the terminal flow renders, a KeyError for an unknown id

func LocalModelsPauseJob

func LocalModelsPauseJob(jobID string) bool

LocalModelsPauseJob raises a job's pause switch, false when the job has none

func LocalModelsQuickstart

func LocalModelsQuickstart(ctx context.Context, modelID string) (map[string]any, error)

LocalModelsQuickstart starts the one job installing the runtime, downloading this machine's build and making it the default

func LocalModelsRuntimeInstall

func LocalModelsRuntimeInstall(ctx context.Context, backendRequest string) (map[string]any, error)

LocalModelsRuntimeInstall starts the job installing the pinned engine, fetching missing drafts and restarting a stale server

func LocalModelsStatus

func LocalModelsStatus(ctx context.Context) (map[string]any, error)

LocalModelsStatus answers the pane's first paint from config, the installed runtime, staged models and the live router

func LocalOrigin

func LocalOrigin() string

Hostname of this machine as an author id origin, cleaned like any author field and empty when unknown

func LocalRuntimeStatePath

func LocalRuntimeStatePath() string

LocalRuntimeStatePath is the supervisor state file of the managed local runtime

func LockConfigMutation

func LockConfigMutation(ctx context.Context) (context.Context, func())

Serializes config read modify write spans, a ctx already holding the lock passing straight through

func LogStreamRetry

func LogStreamRetry(agent StreamDiagAgent, kind string, err error, attempt, maxAttempts int, midToolCall bool, diag *StreamDiag)

Logs the structured warning for a transient stream drop and retry with the dying attempt's upstream facts

func LoginCommand

func LoginCommand(out io.Writer)

LoginCommand prints the removal notice of the retired login command

func LoginMinimaxOAuth

func LoginMinimaxOAuth(env PoolEnv, out io.Writer, args MinimaxLoginArgs) error

LoginMinimaxOAuth runs the MiniMax OAuth login, printing the formatted auth error and exiting 1 on failure

func LoginOpenAICodex

func LoginOpenAICodex(env PoolEnv, out io.Writer, args CodexLoginArgs, forceNewLogin bool) error

LoginOpenAICodex runs the Codex login, device code by default and browser PKCE when opted in

func LoginXAIOAuth

func LoginXAIOAuth(env PoolEnv, out io.Writer, args XAILoginArgs, forceNewLogin bool) error

LoginXAIOAuth signs in to xAI Grok OAuth through the device code flow and makes it the provider

func LogoutCommand

func LogoutCommand(env PoolEnv, providerID string, out io.Writer) error

LogoutCommand clears the auth state of the named, active, or config selected provider

func LongDecodeStaleMultiplier

func LongDecodeStaleMultiplier(apiPayload map[string]any) int

Hop count that scales the non streaming stale budget of one api payload

func LongestDefaultContextMatch

func LongestDefaultContextMatch(modelLower string) (int, bool)

Context length of the longest default table key contained in the lowercase model name

func LooksLikeOpenRouterKey

func LooksLikeOpenRouterKey(value string) bool

Reports whether a credential has the sk-or- shape of an OpenRouter key

func LookupModelsDevContext

func LookupModelsDevContext(ctx context.Context, provider, model string, allowNetwork bool) (int, bool)

LookupModelsDevContext returns the context window with explicit overrides first and _default filling catalog misses

func LowerHeaders

func LowerHeaders(h http.Header) map[string]string

LowerHeaders flattens a header set to lowercase names with first values

func LowerKey

func LowerKey(name string) string

Registry key of a name stripped of whitespace and lowercased for case insensitive registries

func ManagedDotenvKeys

func ManagedDotenvKeys() []string

Names the administrator managed .env loaded into the process

func ManagedLocalNetloc

func ManagedLocalNetloc() string

ManagedLocalNetloc is the cached host and port of the managed llama-server, empty without one

func ManagedModelSupportsVision

func ManagedModelSupportsVision(ctx context.Context, modelID string) (vision *bool)

Ground truth vision capability of a model staged with the managed runtime, nil when it is not ours

func MarkRotationConsumedUncommitted

func MarkRotationConsumedUncommitted(sourcePath string, secrets ...string)

MarkRotationConsumedUncommitted records the pre rotation pair of a refresh whose replacement never committed

func MaskAPIKeyForLogs

func MaskAPIKeyForLogs(key any) string

MaskAPIKeyForLogs hides a key to its head and tail and names a bearer callable instead of invoking it

func MaskedSecretPrompt

func MaskedSecretPrompt(prompt string) (string, error)

Masked terminal prompt for a secret value, the exported form plugins reach through Services

func MatchesReasoningEchoFamily

func MatchesReasoningEchoFamily(family, provider, model, baseURL string) (bool, error)

MatchesReasoningEchoFamily reports membership in one must echo family, a KeyError text for an unknown family

func MaterializeBearerForHTTP

func MaterializeBearerForHTTP(ctx context.Context, value any) (string, error)

MaterializeBearerForHTTP mints one bearer from a token provider or returns a non empty string key

func MaxPartialThinkSuffix

func MaxPartialThinkSuffix(buf []rune, tags [][]rune) int

Length of the longest buf suffix that is a proper prefix of a tag

func MaybeGrowWindow

func MaybeGrowWindow(modelID, baseURL string, sessionTokens, currentWindow int, measuredDecodeTokS *float64) (int, bool, error)

Evaluates and executes one growth step, returning the new window when the ladder granted one

func MergeEndpointSeed

func MergeEndpointSeed(ctx context.Context, dstCfg, seed map[string]any, claimed map[string]bool) map[string]any

Copy of the destination config with the seeded endpoint first and every entry claiming its identities dropped, nil claims resolved here

func MergeHeaderMaps

func MergeHeaderMaps(maps ...map[string]string) map[string]string

MergeHeaderMaps is the dict merge of header maps left to right, later values keeping earlier slots and new keys appended

func MergeInterimReasoningItems

func MergeInterimReasoningItems(prior, newer []map[string]any) []map[string]any

MergeInterimReasoningItems keeps prior checkpoints when a continuation carries none of its own

func MergeModelCooldowns

func MergeModelCooldowns(maps ...any) map[string]float64

MergeModelCooldowns keeps the latest reset per model across snapshots

func MergeSessionAffinityHeaders

func MergeSessionAffinityHeaders(ctx context.Context, kwargs map[string]any, provider, baseURL, sessionID string) map[string]any

MergeSessionAffinityHeaders adds the affinity headers under kwargs extra_headers in place, caller pinned values winning

func MergeSnapshotAuthPreservingLiveSingleUseGrants

func MergeSnapshotAuthPreservingLiveSingleUseGrants(snapshot, live map[string]any) map[string]any

MergeSnapshotAuthPreservingLiveSingleUseGrants restores a snapshot store without reviving spent single use OAuth generations

func MessageField

func MessageField(message any, field string) any

MessageField reads a field from a dict shaped message or the matching attribute of a struct, nil when absent

func MessageFingerprint

func MessageFingerprint(m *state.Message) string

MessageFingerprint is a stable digest of one message over its provider visible persisted fields

func MigrateAllLeftCoreHomes

func MigrateAllLeftCoreHomes(ctx context.Context, say func(string)) ([]string, error)

MigrateAllLeftCoreHomes migrates every profile home sharing the install, grouped by plugin and consent, the enumeration error unhandled like Python

func MigrateCommand

func MigrateCommand(ctx context.Context, h string, ns map[string]any, w, errw io.Writer) (code int, err error)

Dispatches icebath migrate, with the xai, relay and agent subtypes

func MigrateFromAgents

func MigrateFromAgents(ctx context.Context, icebathHome, sourceName string, opts AgentImportOptions) (int, error)

MigrateFromAgents runs setup's import step on demand, a named agent imported, bare offering what was found

func MinSwitchResetFromConfig

func MinSwitchResetFromConfig(cfg config.Tree) time.Duration

MinSwitchResetFromConfig reads fallback.min_switch_reset_seconds, zero or unreadable means off

func MintProxyToken

func MintProxyToken(prefix string) string

MintProxyToken is an opaque token with a recognizable prefix and a 128 bit random hex suffix

func MissingCredentialsSuffix

func MissingCredentialsSuffix(ctx context.Context, provider string) string

A space led hint from the provider's profile for a missing credentials message, else empty

func MissingProviderCredentialsMessage

func MissingProviderCredentialsMessage(ctx context.Context, providerID string) string

MissingProviderCredentialsMessage is the remedy for an explicit provider with no credentials, from the registry

func MoAUsage

func MoAUsage() string

MoAUsage is the usage line of the moa slash command

func ModelAliasCanonical

func ModelAliasCanonical(model string) string

ModelAliasCanonical returns the canonical public slug for a bare wire id alias

func ModelChoiceSaveCount

func ModelChoiceSaveCount() int

ModelChoiceSaveCount is how many picks were saved in this process

func ModelCommitBytes

func ModelCommitBytes(modelBytes int64) int64

What Windows charges to commit for a model estimated at modelBytes of device memory

func ModelConsumesThoughtSignature

func ModelConsumesThoughtSignature(model, baseURL, provider string) bool

Whether a Gemini route reads the tool call extra_content thought signature, exported for the agent strict sanitizer

func ModelCooldownUntil

func ModelCooldownUntil(entry PooledCredential, model string) (float64, bool)

ModelCooldownUntil is the active cooldown blocking the entry for model, any model when unscoped

func ModelDerivedAPIMode

func ModelDerivedAPIMode(ctx context.Context, provider, model, apiKey string) (string, bool)

ModelDerivedAPIMode is the api mode re-derived from the final model, false when the endpoint fixes the wire

func ModelIDFromStem

func ModelIDFromStem(stem string) string

Model id from a GGUF file stem with any split part suffix removed

func ModelIDIsGeneration

func ModelIDIsGeneration(modelID any) bool

ModelIDIsGeneration reports whether the id names an image or video generation surface

func ModelSearchText

func ModelSearchText(model string) string

ModelSearchText is the haystack for substring model search and never changes the wire id

func ModelSectionHasCredentials

func ModelSectionHasCredentials(ctx context.Context, cfg map[string]any) (bool, error)

ModelSectionHasCredentials reports usable inference credentials from the auth store, the registry keys or the OpenRouter env vars

func ModelSelectionConfigUpdates

func ModelSelectionConfigUpdates(result ModelSwitchResult, currentModelCfg any) []config.KeyValue

ModelSelectionConfigUpdates is the ordered model section change a persisted selection makes, a nil value clearing the key

func ModelSupportsFastMode

func ModelSupportsFastMode(model string) bool

ModelSupportsFastMode reports whether the fast toggle is exposed for the model

func ModelSupportsUltrafast

func ModelSupportsUltrafast(model string) bool

ModelSupportsUltrafast reports whether OpenAI publishes the ultrafast tier for the exact slug

func ModelsConfigIsAllowlist

func ModelsConfigIsAllowlist(value any, discovered bool) bool

Reports whether a models config acts as an allowlist over discovered models

func ModelsDevIDFor

func ModelsDevIDFor(provider string) (string, bool)

The models.dev id for an exact icebath provider id

func ModelsDevProviderMap

func ModelsDevProviderMap() map[string]string

Icebath provider id to models.dev id, static map then profile declarations

func ModelsNormalizeProvider

func ModelsNormalizeProvider(provider string) string

Is, aliases collapsed and an empty name meaning openrouter

func MovedCommandHint

func MovedCommandHint(ctx context.Context, prog, value, action string) string

MovedCommandHint says where a command a left core plugin took over went and how to get it, else empty

func MultiplexProcess

func MultiplexProcess() bool

MultiplexProcess reports the process wide multiplex flag

func NamedCustomProvider

func NamedCustomProvider(ctx context.Context, h, name string) (map[string]any, error)

Resolved named endpoint entry with credentials, nil when no entry matches

func NamedCustomProviderEntry

func NamedCustomProviderEntry(ctx context.Context, name string, cfg map[string]any) map[string]any

Named endpoint entry a provider name selects in cfg without reading credentials, nil when none matches

func NativeAnthropicAccountingProjection

func NativeAnthropicAccountingProjection(messages any) (any, []string)

NativeAnthropicAccountingProjection returns the native Anthropic wire shadow of the messages and the replayed thinking texts

func NativeAnthropicPreservesPriorThinking

func NativeAnthropicPreservesPriorThinking(baseURL, model string) bool

NativeAnthropicPreservesPriorThinking reports whether the route replays and the model keeps signed prior thinking

func NativeCompactionContextManagement

func NativeCompactionContextManagement(g NativeCompactionGate, route ResponsesRoute) []map[string]any

NativeCompactionContextManagement is the context_management payload of the route, nil when it must not be sent

func NativeResponsesReplayInput

func NativeResponsesReplayInput(msgs []*state.Message, route ResponsesRoute, baseURL, model string, replayEncryptedReasoning bool) ([]map[string]any, error)

NativeResponsesReplayInput is the Responses input a native compaction eligible route replays for the messages

func NeedsReasoningEcho

func NeedsReasoningEcho(provider, model, baseURL string) bool

NeedsReasoningEcho reports whether the route 400s on a tool call turn without reasoning_content

func NegotiateRequestTier

func NegotiateRequestTier(route Route, overrides map[string]any)

NegotiateRequestTier clamps the requested speed tier to what the request credential's catalog advertises

func NewAuxChatStreamAccumulator

func NewAuxChatStreamAccumulator(ctx context.Context, model string, totalCeiling *float64) *auxChatStreamAccumulator

NewAuxChatStreamAccumulator is the exported form of the chat stream accumulator constructor

func NewBedrockOpenAISigV4Auth

func NewBedrockOpenAISigV4Auth(ctx context.Context, region string, base http.RoundTripper) (http.RoundTripper, error)

Round tripper signing Mantle requests with SigV4 that owns Authorization over the aws-sdk sentinel bearer

func NoProxyEntries

func NoProxyEntries(value *string) []string

NoProxyEntries splits a NO_PROXY value, reading both environment casings when nil is passed

func NoProxyEntryMatches

func NoProxyEntryMatches(entry, host string, port int, hasPort bool) bool

NoProxyEntryMatches reports whether one NO_PROXY entry covers the host and port

func NonretryableLabel

func NonretryableLabel(reason FailoverReason) (string, bool)

NonretryableLabel names a non retryable reason in the fallback status line, false for an unlabelled reason

func NormalizeActualBaseURL

func NormalizeActualBaseURL(baseURL string) string

NormalizeActualBaseURL gives hosted or loopback Actual roots their /v1 surface and the default when empty

func NormalizeAuxProvider

func NormalizeAuxProvider(ctx context.Context, provider string) string

Canonical auxiliary provider slug of a configured provider name

func NormalizeBaseURLForMatch

func NormalizeBaseURLForMatch(value any) string

Exported base URL match form, trimmed, lowercased and without trailing slashes

func NormalizeCustomProviderEntry

func NormalizeCustomProviderEntry(raw any, providerKey string) map[string]any

NormalizeCustomProviderEntry returns the runtime shape of one providers or custom_providers block or nil

func NormalizeExtraHeaders

func NormalizeExtraHeaders(extraHeaders any) map[string]string

NormalizeExtraHeaders renders a raw extra_headers mapping as string pairs in declaration order, dropping nil values

func NormalizeFinishReason

func NormalizeFinishReason(raw any) any

NormalizeFinishReason folds a wire finish reason to the lowercase OpenAI value, passing non strings and empty through

func NormalizeGeminiBaseURL

func NormalizeGeminiBaseURL(baseURL string) string

NormalizeGeminiBaseURL strips the OpenAI compatibility suffix and trailing slashes from a Gemini base URL

func NormalizeMainModelAssignment

func NormalizeMainModelAssignment(ctx context.Context, provider, model string) (string, string)

Main slot provider and model as persisted for the home in ctx

func NormalizeMoAConfig

func NormalizeMoAConfig(raw any) map[string]any

Normalized moa config block with presets, default preset and settings

func NormalizeModelForProvider

func NormalizeModelForProvider(model, targetProvider string) string

NormalizeModelForProvider is NormalizeModelForProviderCtx for a caller holding no context

func NormalizeModelForProviderCtx

func NormalizeModelForProviderCtx(ctx context.Context, model, targetProvider string) string

NormalizeModelForProviderCtx rewrites a model name into the target provider's form, profile hooks reading the call's home

func NormalizeOpenCodeBaseURL

func NormalizeOpenCodeBaseURL(providerID string, mode APIMode, baseURL string) string

NormalizeOpenCodeBaseURL heals the relay path and the /v1 tail for the wire protocol on opencode.ai hosts

func NormalizeOpenCodeModelID

func NormalizeOpenCodeModelID(providerID, modelID string) string

NormalizeOpenCodeModelID strips the family prefix from an OpenCode config model id

func NormalizeProvider

func NormalizeProvider(name string) string

NormalizeProvider lowercases a provider name and collapses every alias onto its canonical id

func NormalizeProviderDef

func NormalizeProviderDef(ctx context.Context, name string) string

NormalizeProviderDef resolves aliases and casing to the canonical models.dev keyed provider id

func NormalizeRouteBaseURL

func NormalizeRouteBaseURL(baseURL string) string

NormalizeRouteBaseURL canonicalizes only the URL components proven equivalent for route identity

func NoteCatalogItem

func NoteCatalogItem(item any) bool

NoteCatalogItem remembers a generation row and reports whether it must leave the chat catalog

func NoteGenerationModel

func NoteGenerationModel(modelID any)

NoteGenerationModel remembers an id a live catalog row proved to be generation only

func NoteLeftCoreFailure

func NoteLeftCoreFailure(h, plugin string)

NoteLeftCoreFailure bumps the failed install stamp whose mtime and count gate the next startup attempt

func NoteLeftCoreSuccess

func NoteLeftCoreSuccess(h, plugin string)

NoteLeftCoreSuccess removes the failed install stamp, so a later failure starts the backoff from an hour

func OAuthAdmissionProblems

func OAuthAdmissionProblems(manifest map[string]any, pluginDir string) []string

OAuthAdmissionProblems adds catalog admission checks to the shape, declared variables and no core id clash

func OAuthAdmissionWarnings

func OAuthAdmissionWarnings(manifest map[string]any, pluginDir string) []string

OAuthAdmissionWarnings flags hosts outside the IdP domains and plugin code naming a token URL

func OAuthNotice

func OAuthNotice(manifest map[string]any) string

OAuthNotice is the install and show text for the declared clients, empty when none are declared

func OAuthReloginCommand

func OAuthReloginCommand(provider string) string

OAuthReloginCommand is the exact re-login command for a rejected OAuth grant

func OAuthSurface

func OAuthSurface(manifest map[string]any) map[string]bool

OAuthSurface is one line per client for the re-pin consent delta

func OfferAgentImport

func OfferAgentImport(ctx context.Context, icebathHome string, fromSetup bool) (string, error)

OfferAgentImport offers to import the agents found on this computer and returns the labels whose import changed config.yaml or .env

func OfferedModelIDs

func OfferedModelIDs(models []any, provider, baseURL string) []any

OfferedModelIDs drops the ids a picker may not offer because validation refuses their whitespace

func OllamaModelSupportsThinking

func OllamaModelSupportsThinking(ctx context.Context, model, baseURL string, apiKey any, timeout time.Duration) (supported, known bool)

OllamaModelSupportsThinking reads thinking from native api show capabilities, known false when the probe failed

func OpEnvAllowlist

func OpEnvAllowlist() []string

Copy of the environment names an op child process may inherit

func OpScrub

func OpScrub(text string) string

Sanitized stderr text of an op invocation with escape sequences removed

func OpenAIModelRejectsReasoning

func OpenAIModelRejectsReasoning(model string) bool

OpenAIModelRejectsReasoning is true for chat era ids that 400 on any reasoning field

func OpenAIReasoningFamily

func OpenAIReasoningFamily(model string) string

OpenAIReasoningFamily is the all_turns family a model belongs to, empty for every other model

func OpenBrowserTab

func OpenBrowserTab(target string) error

Opens a URL in a new tab through the browser registry for callers outside the package

func OpenCodeFamily

func OpenCodeFamily(providerID string) string

OpenCodeFamily resolves a provider id or a custom name extending a family slug to its OpenCode family

func OpenCredentialedURL

func OpenCredentialedURL(req *http.Request, timeout time.Duration, openerFactory OpenerFactory, tlsCfg *tls.Config) (*http.Response, error)

OpenCredentialedURL opens a request without forwarding credentials across origins

func OpenRouterModelIDs

func OpenRouterModelIDs(ctx context.Context, forceRefresh bool) []string

OpenRouterModelIDs returns just the OpenRouter model id strings

func OpenRouterVariantBase

func OpenRouterVariantBase(model string) string

OpenRouterVariantBase returns the base id of a routing variant suffix or empty

func OpencodeFamilyForCustom

func OpencodeFamilyForCustom(requestedProvider, baseURL string) string

OpencodeFamilyForCustom is the OpenCode family by provider name or opencode.ai host, empty for none

func OpencodeSessionHeaders

func OpencodeSessionHeaders(ctx context.Context, provider, baseURL, sessionID string) map[string]string

OpencodeSessionHeaders is the session header for OpenCode targets, an ephemeral oneshot key when none resolves

func OpenrouterPKCELogin

func OpenrouterPKCELogin(env PoolEnv, out io.Writer, openBrowser bool, timeout time.Duration) (map[string]any, error)

OpenrouterPKCELogin runs the OpenRouter PKCE flow and returns the minted API key for the pool add path

func OrderRecordedMessages

func OrderRecordedMessages(v any) any

List of request messages with every message that carries a recorded key order turned into its ordered dict

func OrderedHeaders

func OrderedHeaders(m map[string]string, keys []string) map[string]string

OrderedHeaders records the key order of a header map and returns the map

func OutboundImageRetireCount

func OutboundImageRetireCount(carrierBlocks []int, reservedBlocks int, carrierBytes []int, reservedBytes int, manyImageSafe bool) int

Count of newest image carriers to retire so the outbound request stays under the image ceilings

func OverrideContextWindow

func OverrideContextWindow(ctx context.Context, provider, model string) (int, bool)

OverrideContextWindow is the explicit model_overrides context window for the bound home

func OwnerSecretScope

func OwnerSecretScope(ctx context.Context, h string) map[string]string

Secret mapping for a body owned by the home, the launch scope for this process's own home

func ParseAbsoluteTimestamp

func ParseAbsoluteTimestamp(value any) (float64, bool)

ParseAbsoluteTimestamp converts epoch seconds, epoch milliseconds or ISO 8601 text into epoch seconds

func ParseAvailableOutputTokensFromError

func ParseAvailableOutputTokensFromError(errorMsg string) (int, bool)

ParseAvailableOutputTokensFromError extracts the output budget from a max_tokens too large error

func ParseCodexVersion

func ParseCodexVersion(output string) ([3]int, bool)

Major, minor and patch of codex --version output, false when no version is present

func ParseContextLimitFromError

func ParseContextLimitFromError(errorMsg string) (int, bool)

ParseContextLimitFromError returns the context window a provider error quotes

func ParseExactServiceTier

func ParseExactServiceTier(raw string) (string, error)

ParseExactServiceTier pins normal for an empty word and rejects an unknown word instead of reading it as normal

func ParseISOTimestamp

func ParseISOTimestamp(value any) (float64, bool)

ParseISOTimestamp returns epoch seconds for ISO 8601 text and false for anything else

func ParseModelInput

func ParseModelInput(ctx context.Context, raw, currentProvider string, customIDs map[string]bool) (string, string)

ParseModelInput splits model command input into provider and model, the colon delimits only a known provider

func ParsePartialCompressArgs

func ParsePartialCompressArgs(rawArgs string) (bool, int, *string)

Partial flag, keep count and focus topic from the text after compress, nil focus for the partial forms

func ParseReasoningEffort

func ParseReasoningEffort(effort any) map[string]any

Reasoning effort config of a level, nil for empty or unrecognized input and enabled false for a disable spelling

func ParseRetryAfter

func ParseRetryAfter(value string) (time.Duration, bool)

ParseRetryAfter reads a numeric or HTTP date Retry-After value into a duration clamped at zero

func ParseServiceTier

func ParseServiceTier(raw string) string

ParseServiceTier maps a user or config word to a stored tier, empty for normal and unknown words

func ParseTurnAuthor

func ParseTurnAuthor(raw any) *pyjson.Object

Normalizes a dict or JSON string into id, name and is_bot, nil for anything else or without id and name

func PersistModelSelection

func PersistModelSelection(ctx context.Context, result ModelSwitchResult, configPath string) error

PersistModelSelection writes a successful switch into the config at path, the active profile config when empty

func PersistPoolEntries

func PersistPoolEntries(env PoolEnv, provider string, payloads []map[string]any, removedIDs, statusClearedIDs []string, tokenBases map[string]TokenPair) ([]map[string]any, bool)

PersistPoolEntries writes a provider's rows to the store that owns them, false when a borrowed write failed

func PersistedAnchorTokens

func PersistedAnchorTokens(ctx context.Context, store UsageAnchorStore, sessionID string, messages []*state.Message, haveMessages bool) (int, bool)

PersistedAnchorTokens is the anchored token figure from a session row anchor for callers without an agent

func PersistedProviderID

func PersistedProviderID(ctx context.Context, provider string, providers map[string]any) string

PersistedProviderID is the model.provider a switch saves, a bare built in name that resolved to the user's providers entry becoming that entry's custom identity

func PinnedTag

func PinnedTag(backend string) (string, error)

Returns b plus the PM pinned llama.cpp version of backend

func PlanCacheSectionsForDestination

func PlanCacheSectionsForDestination(ctx context.Context, messages, tools []map[string]any, provider, baseURL, apiMode, model string,
	cacheDisabled *bool, cacheTTL string, staticSystemPrefix *string) ([]map[string]any, []map[string]any)

PlanCacheSectionsForDestination plans request local cache sections for a MoA or auxiliary destination

func PlatformConfiguredOn

func PlatformConfiguredOn(h, name string) bool

PlatformConfiguredOn reports a platform switched on, or holding a token without an enabled key, in the merged gateway config

func PlatformInstallHint

func PlatformInstallHint(ctx context.Context, platform string) string

PlatformInstallHint names the install command for an unknown platform that left core, else empty

func PlatformTLSConfig

func PlatformTLSConfig() *tls.Config

PlatformTLSConfig is the process wide client context with an SSL_CERT_FILE bundle unioned on top

func PluginAuthHandler

func PluginAuthHandler(provider string) func(action string, args []string, provider string) (bool, error)

PluginAuthHandler is the profile's auth action handler, nil when none

func PluginHomeLabel

func PluginHomeLabel(h string) string

PluginHomeLabel names a home by its profile, else by its path

func PluginInstallCommand

func PluginInstallCommand(name, h string) string

PluginInstallCommand is the exact command installing a plugin into a home, bare only for the sticky default

func PluginKey

func PluginKey(pluginDir string) string

PluginKey is the plugin's path under the plugins root it lives in, the store key of its grants

func PluginLoadError

func PluginLoadError(ctx context.Context, plugin string) string

PluginLoadError returns the import error a home plugin dir raised, empty when it loaded

func PluginOAuthKey

func PluginOAuthKey(pluginDir string) string

Grant store key of a plugin directory, the key plugins remove forgets its sign ins under

func PluginPresent

func PluginPresent(plugin, h string) bool

PluginPresent reports the plugin installed in the home, enabled or not

func PluginRefreshHookExists

func PluginRefreshHookExists(provider string) bool

PluginRefreshHookExists reports whether a plugin profile ships refresh_credential for the provider

func PluginRowIsExpiring

func PluginRowIsExpiring(entry PooledCredential) bool

PluginRowIsExpiring reports an expiry stamped OAuth row due within the skew of expires_at_ms

func PluginSecretSources

func PluginSecretSources() plugins.SecretSources

Orchestrator the plugin manager re-pulls enabled plugin secret sources through after discovery

func PollUntil

func PollUntil[T any](pred func() (T, bool), timeout, interval time.Duration) T

PollUntil calls pred every interval until it holds or the timeout passes, the last sleep cut to the time left

func PoolBillingMessage

func PoolBillingMessage(ctx context.Context, providerID, model string, pool interface{ Entries() []PooledCredential }) (string, bool)

PoolBillingMessage names a pool burned by a billing verdict, reading persisted rows when no pool is loaded

func PoolCooldownMessage

func PoolCooldownMessage(ctx context.Context, providerID string) (string, bool)

PoolCooldownMessage names a fully benched pool and its next reset, empty when a credential is usable

func PoolFailureReason

func PoolFailureReason(reason FailoverReason, errorContext map[string]any, billingUnverified bool) string

PoolFailureReason is the reason persisted for a rotation, usage window and unverified billing sized apart

func PoolKeySource

func PoolKeySource() tools.PoolKeySource

Pool key reader the tool layer installs as tools.PoolKeys

func PoolSockets

func PoolSockets(client any) []net.Conn

PoolSockets returns the raw sockets of the client pools, only the own in flight requests on a shared pool

func PreAgentFallbackNotice

func PreAgentFallbackNotice(primaryProvider, primaryModel, fallbackProvider, fallbackModel string) string

PreAgentFallbackNotice is the one shot line for a provider switch made during credential resolution

func PredictedDecodeTokS

func PredictedDecodeTokS(entry CatalogEntry, variant QuantVariant, budget HardwareBudget, spilled bool, backend string) float64

Shipped measured baseline where matched, otherwise bandwidth over bytes read per token

func PreflightKwargs

func PreflightKwargs(t Transport, apiKwargs map[string]any, allowStream, dropReplayItemIDs, sanitizeHarmony bool) (map[string]any, error)

Responses transport preflight of outgoing kwargs, an AttributeError for every transport lacking it

func PrepareInheritedEndpointSeed

func PrepareInheritedEndpointSeed(ctx context.Context, sourceCfg map[string]any) (map[string]any, map[string]bool)

Seed and the identities it claims, both fixed in the source scope so a merge never resolves them in the destination's

func PrewarmPickerCacheAsync

func PrewarmPickerCacheAsync(ctx context.Context) <-chan struct{}

Runs the picker listing once per process in the background so the disk catalog cache is warm

func PricingCacheScope

func PricingCacheScope(ctx context.Context, provider, baseURL string) string

PricingCacheScope is the current endpoint identity a provider's pricing cache is keyed on, resolved locally

func PrimaryFailureWording

func PrimaryFailureWording(err *AuthError) (string, string)

PrimaryFailureWording returns the log phrase and user phrase of a primary provider failure that triggers the fallback chain

func PrimaryModelConfig

func PrimaryModelConfig(ctx context.Context, h string) map[string]any

Model section of the home's config as the runtime resolver reads it

func PrintSetupBanner

func PrintSetupBanner(lines ...string)

PrintSetupBanner prints the magenta box banner, top border, the body lines and bottom border

func PrintSetupHeader

func PrintSetupHeader(title string, gap bool)

PrintSetupHeader prints a cyan section header, gap adding an extra blank line before it

func ProbeLMStudioModels

func ProbeLMStudioModels(ctx context.Context, apiKey any, baseURL string, timeout time.Duration) ([]string, bool, error)

ProbeLMStudioModels lists chat capable LM Studio keys, false when unreachable, an AuthError on 401 or 403

func ProbeOllamaLocalModels

func ProbeOllamaLocalModels(ctx context.Context, baseURL string, timeout time.Duration, headers map[string]string) ([]string, bool)

ProbeOllamaLocalModels lists the native api tags catalog, false when the endpoint is unreachable or malformed

func ProfileCLISelector

func ProfileCLISelector(h string) string

ProfileCLISelector is the -p name selector pinning copy pasteable guidance to the active named profile

func ProfileConfigScope

func ProfileConfigScope(ctx context.Context, h, launchHome string) context.Context

Context bound to the home, secret and terminal scope of a home whose config a body reads and writes, launchHome empty meaning the process home

func ProfileEnvVars

func ProfileEnvVars(p Profile) []string

Key env names then the base URL env name of a profile, the order its env_vars tuple lists them

func ProfileModelAPIMode

func ProfileModelAPIMode(ctx context.Context, profile Profile, model string) (string, bool)

Per model wire of a profile, false when it answers none and the declared mode when its hook raises

func ProfileSecretSource

func ProfileSecretSource() tools.ProfileSecretSource

ProfileSecretSource is the secret scope reader cmd/icebath installs as tools.ProfileSecrets

func PromptAPIKey

func PromptAPIKey(env PoolEnv, out io.Writer, pconfig Profile, existingKey, providerID, existingSource string) (string, bool, error)

PromptAPIKey asks for an api key, keep replace or clear when one exists, abort true when the caller must return

func PromptCacheBytes

func PromptCacheBytes(live *HardwareBudget, modelBytes int64, residents int) *int64

Prompt cache size beside a model of modelBytes per resident model, nil when the engine default applies

func PromptCachingDisabledFromConfig

func PromptCachingDisabledFromConfig(ctx context.Context) bool

PromptCachingDisabledFromConfig reports whether the bound config turns prompt caching off

func PromptChecklist

func PromptChecklist(title string, items []string, preSelected []int) []int

PromptChecklist asks for several items, returning sorted picked indices, cancel keeping the preselection

func PromptChoice

func PromptChoice(question string, choices []string, def int, description string) int

PromptChoice asks for one of the choices with arrow keys, a cancel outside setup keeping the default

func PromptReadingHook

func PromptReadingHook(ctx context.Context, hook func(seconds float64)) context.Context

Context whose work hears each stretch of prompt reading through the hook, nil uninstalling it

func PromptYesNo

func PromptYesNo(question string, def bool, description string) bool

Yes or no answer, headless runs taking the default, inside setup and the TUI through the menu

func ProviderAllowsModelWhitespace

func ProviderAllowsModelWhitespace(provider, baseURL string) bool

ProviderAllowsModelWhitespace reports whether a spaced id is a real selection rather than a cloud catalog typo

func ProviderAuthKind

func ProviderAuthKind(provider string) string

ProviderAuthKind is oauth for providers whose credential is an OAuth grant, api_key for everything else

func ProviderCatalogBySlug

func ProviderCatalogBySlug() map[string]ProviderDescriptor

ProviderCatalogBySlug keys the catalog by slug

func ProviderEnvEntries

func ProviderEnvEntries() []config.NamedEnvVar

ProviderEnvEntries returns the bundled provider profiles' env entries in profile order, computed once and config free

func ProviderGroupForSlug

func ProviderGroupForSlug(slug string) string

ProviderGroupForSlug returns the group id a slug belongs to, empty when ungrouped

func ProviderHasCredentials

func ProviderHasCredentials(ctx context.Context, provider string) bool

ProviderHasCredentials reports whether a provider can be switched to without typing a key

func ProviderInstallHint

func ProviderInstallHint(ctx context.Context, name string) string

ProviderInstallHint names the install, enable or update command for a provider a left core plugin supplies

func ProviderLabel

func ProviderLabel(provider string) string

ProviderLabel is the human friendly label for a provider id or alias

func ProviderLeftCore

func ProviderLeftCore(name string) bool

ProviderLeftCore reports a provider a plugin supplies that no registered profile serves now

func ProviderOwnsRoute

func ProviderOwnsRoute(provider, baseURL string) (owned bool, known bool)

ProviderOwnsRoute reports whether a base URL is the provider's own endpoint and whether that can be known

func ProviderResetDelay

func ProviderResetDelay(resetAt any, now time.Time) (time.Duration, bool)

ProviderResetDelay converts a provider declared reset instant into a positive wait or reports none

func ProviderRetiredAliases

func ProviderRetiredAliases(provider string) []string

ProviderRetiredAliases returns the retired ids a provider still auto detects

func ProviderRetryAfter

func ProviderRetryAfter(e *APIError) (time.Duration, bool)

ProviderRetryAfter returns the positive provider declared cooldown from header or retry_after body field

func ProviderSetupFailureLines

func ProviderSetupFailureLines(err error, retryCommand string) []string

ProviderSetupFailureLines are the lines to print when the setup wizard's provider step fails

func ProviderSource

func ProviderSource(ctx context.Context, name string) string

ProviderSource names where the current registration of a provider came from, empty when unregistered

func ProviderStateIn

func ProviderStateIn(data AuthData, providerID string) map[string]any

ProviderStateIn returns a shallow copy of one provider entry

func ProvidersDictToCustomProviders

func ProvidersDictToCustomProviders(providersDict any) []map[string]any

ProvidersDictToCustomProviders normalizes enabled providers blocks into the legacy list shape

func PublishLRU

func PublishLRU[K comparable, V any](table map[K]V, order *[]K, key K, value V, limit int, siblings ...func(K)) []K

Stores key as most recently used and drops least recently used keys past limit from table and siblings, returning them

func QueryOllamaNumCtx

func QueryOllamaNumCtx(ctx context.Context, model, baseURL, apiKey string) (int, bool)

QueryOllamaNumCtx returns the Ollama show context, Modelfile num_ctx before the GGUF max

func QueryOllamaSupportsVision

func QueryOllamaSupportsVision(ctx context.Context, model, baseURL, apiKey string) (supported, known bool)

QueryOllamaSupportsVision reports Ollama vision support, known false when the server answered without it

func ReadClaudeCodeCredentials

func ReadClaudeCodeCredentials(env PoolEnv) map[string]any

ReadClaudeCodeCredentials reads the borrowed login from Keychain and file, preferring the only valid one

func ReadEnvSetting

func ReadEnvSetting(h, key string) (string, bool)

ReadEnvSetting resolves .env first, then a stale top level config.yaml copy which is reported on stderr

func ReadFallbackChain

func ReadFallbackChain(cfg map[string]any) []map[string]any

ReadFallbackChain is the normalized chain merged with the legacy fallback_model, always fresh copies

func ReadIcebathOAuthCredentials

func ReadIcebathOAuthCredentials(env PoolEnv) map[string]any

Reads the icebath managed PKCE credentials of the home

func ReadStreamingErrorBody

func ReadStreamingErrorBody(response *http.Response, maxBytes int, timeout time.Duration) string

Reads a non OK streaming body under a byte cap and a hard deadline, partial text and never an error

func ReasoningConfigForWire

func ReasoningConfigForWire(ctx context.Context, agent ChatCompletionAgent) map[string]any

Agent reasoning config with the one shot off override and the route's rejection rules, recorded as what went out

func ReasoningEchoFamily

func ReasoningEchoFamily(provider, model, baseURL string) string

ReasoningEchoFamily names the first must echo family the route matches in table order, empty for none

func ReasoningStaleTimeoutFloor

func ReasoningStaleTimeoutFloor(model string) (time.Duration, bool)

ReasoningStaleTimeoutFloor returns the stale detector floor for a known reasoning model slug

func RecordAuxUsage

func RecordAuxUsage(ctx context.Context, response map[string]any, task, provider, baseURL string)

Records an auxiliary response's usage against the ambient session, never failing the auxiliary call

func RecordCodexAppServerCompaction

func RecordCodexAppServerCompaction(agent CodexRuntimeAgent, turn *CodexTurnResult, approxTokens int, force bool) bool

Records a server side or forced codex compaction and reports whether one happened

func RecordCodexAppServerUsage

func RecordCodexAppServerUsage(agent CodexRuntimeAgent, turn *CodexTurnResult, messages []map[string]any) map[string]any

Folds a codex turn's token usage into the agent, compressor and session row

func RecordCoreUse

func RecordCoreUse(h string, cfg map[string]any, version int) bool

RecordCoreUse marks every row leaving core at the config version that the home uses, reporting a change

func RecordManagedDotenvKeys

func RecordManagedDotenvKeys(keys []string)

RecordManagedDotenvKeys remembers the keys the administrator managed .env loaded

func RecoverAuthFailure

func RecoverAuthFailure(agent AuthRecoveryAgent, pool *Pool, req AuthRecoveryRequest) (bool, bool)

RecoverAuthFailure refreshes or rotates the dispatched credential after a 401 or 403, returning recovered and the 429 flag

func RecoverLeftCoreAtStartup

func RecoverLeftCoreAtStartup(ctx context.Context, say func(string), gatewayStart bool) []string

RecoverLeftCoreAtStartup makes one migration attempt per process per home, delivering or keeping every outcome

func RecoverLeftCoreForCommand

func RecoverLeftCoreForCommand(ctx context.Context, name string)

RecoverLeftCoreForCommand migrates the active home first when a command names a left core plugin it uses and lacks

func RecoverSetupExit

func RecoverSetupExit(code *int)

RecoverSetupExit turns a SetupExit panic into the exit code, re-panicking anything else

func RecurrentSpillBlocks

func RecurrentSpillBlocks(profile ModelProfile, spillBytes *int64) []int

Fewest lowest recurrent blocks whose FFN bytes cover the spill, all of them when unknown or short

func RefreshAccountUsageAsync

func RefreshAccountUsageAsync(ctx context.Context, providers []string) []<-chan struct{}

RefreshAccountUsageAsync background refreshes the provider wide slot of each provider not tried recently

func RefreshAccountUsageEntriesAsync

func RefreshAccountUsageEntriesAsync(ctx context.Context, requests []AccountUsageRefreshRequest) []<-chan struct{}

RefreshAccountUsageEntriesAsync refreshes due per credential slots serially on one worker, read only

func RefreshAnthropicOAuthPure

func RefreshAnthropicOAuthPure(env PoolEnv, refreshToken string, useJSON bool) (map[string]any, error)

RefreshAnthropicOAuthPure refreshes an Anthropic OAuth token without touching local credential files

func RefreshBoundHome

func RefreshBoundHome(ctx context.Context)

RefreshBoundHome rescans the bound home's plugin dirs now and forgets its remembered misses

func RefreshCatalog

func RefreshCatalog(force bool) bool

Fetches the repo catalog and swaps it in memory, false when throttled or on any failure

func RefreshCatalogSoon

func RefreshCatalogSoon()

Starts a background refresh unless one was attempted within the TTL

func RefreshCatalogs

func RefreshCatalogs(ctx context.Context, secrets *config.Secrets) bool

RefreshCatalogs force refreshes the manifest and the OpenRouter live list

func RefreshInstalledSecretScope

func RefreshInstalledSecretScope(ctx context.Context, h string) bool

RefreshInstalledSecretScope replaces the bound mapping with a fresh build of the home's secrets

func RefreshReasoningCapsAsync

func RefreshReasoningCapsAsync(ctx context.Context, provider string)

RefreshReasoningCapsAsync forces a background refetch of a provider's capability catalog

func RegisterFactory

func RegisterFactory(mode APIMode, f Factory)

RegisterFactory binds a wire protocol to its adapter constructor

func RegisterProvider

func RegisterProvider(p Profile)

RegisterProvider registers a profile process wide by name and aliases, later registrations replacing earlier ones

func RegisterSecretSource

func RegisterSecretSource(source SecretSource, replace, builtin bool, scope string) bool

RegisterSecretSource registers a source, true on success, rejections are logged never raised

func RegisterStablePrefix

func RegisterStablePrefix(prefix string)

RegisterStablePrefix records the static scaffold of a just built user message for cache boundary placement

func RegisterTransport

func RegisterTransport(apiMode string, newTransport func() Transport)

RegisterTransport binds an api mode to the constructor of its transport, the seam a provider plugin dialect uses

func RegisteredAPIModes

func RegisteredAPIModes() map[string]bool

RegisteredAPIModes lists every api mode with a registered transport, built in and plugin supplied

func RegistryGeneration

func RegistryGeneration() int64

RegistryGeneration counts provider registrations so memos over profile answers can key on it

func RegistryInferenceBaseURL

func RegistryInferenceBaseURL(id string) (string, bool)

Inference base URL of a provider registry id and whether the id is registered

func RegistryInferenceBaseURLs

func RegistryInferenceBaseURLs() []string

Every provider registry entry's inference base URL in registry order

func RegistryInferenceRoutes

func RegistryInferenceRoutes(ctx context.Context) [][2]string

Registry ids paired with their inference base URL in registry order, hidden rows left out

func RegistryKeys

func RegistryKeys(ctx context.Context) []string

Keys of the provider registry of the bound home in storage order, alias keys included

func RejectedReasoningFields

func RejectedReasoningFields(errorBody any, sentMessages any) map[string]bool

RejectedReasoningFields lists the reasoning keys to drop after an unknown field rejection naming one the request carried

func RejectedThinkingFingerprints

func RejectedThinkingFingerprints(store RejectedThinkingStore, sessionID string) map[string]bool

RejectedThinkingFingerprints returns the persisted rejection fingerprints of a session

func RejoinCompressedHeadAndTail

func RejoinCompressedHeadAndTail(compressedHead, tail []map[string]any) []map[string]any

Compressed head followed by the verbatim tail, merging or bridging a same role user or assistant seam

func RelayCompleteLogicalCall

func RelayCompleteLogicalCall(ctx context.Context, apiRequestID string, o RelayLogicalCompletion) error

Completes the active turn's logical LLM call after caller validation

func RelayExecute

func RelayExecute(ctx context.Context, request map[string]any, callback func(ctx context.Context, request map[string]any) (any, error), o RelayExecuteOptions) (any, error)

Runs one non streaming provider attempt through Relay under the session or the inherited turn

func RelayExecuteAsync

func RelayExecuteAsync(ctx context.Context, request map[string]any, callback func(ctx context.Context, request map[string]any) (any, error), o RelayExecuteOptions) (any, error)

Async twin of RelayExecute awaiting an awaitable callback result on the caller's loop

func RelayStreamCurrent

func RelayStreamCurrent(ctx context.Context, request map[string]any, streamFactory func(ctx context.Context, request map[string]any) (any, error), o RelayStreamOptions) (any, error)

Streams under the inherited turn, returning a completed response a stream ignoring factory produced as is

func ReloadSetupConfig

func ReloadSetupConfig(ctx context.Context, cfg config.Tree, save bool) error

ReloadSetupConfig replaces cfg in place with the config on disk, saving it back when save is set

func ReloginCommandHint

func ReloginCommandHint(h, provider string) string

ReloginCommandHint is the re-sign-in command for a rejected credential on surfaces that may not know the provider

func RememberAccountUsage

func RememberAccountUsage(ctx context.Context, provider string, snapshot *AccountUsageSnapshot, identityID, baseURL string, started time.Time)

RememberAccountUsage lands one fetch result, never erasing with an empty fetch or replacing a fresher one

func RememberReasoningFloor

func RememberReasoningFloor(provider, baseURL string, rejectedKwargs map[string]any, _ error) error

RememberReasoningFloor records that the route refuses to disable reasoning for the rejected request model

func RememberStructuredOutputRejection

func RememberStructuredOutputRejection(provider, baseURL string, rejectedKwargs map[string]any, err error) error

RememberStructuredOutputRejection records the rejected response format type when the error names the capability

func RememberTemperatureRejection

func RememberTemperatureRejection(provider, baseURL string, rejectedKwargs map[string]any, _ error) error

RememberTemperatureRejection omits temperature from the next request of the route and rejected model

func RemoteModelSelectionGuard

func RemoteModelSelectionGuard(ctx context.Context, before, after any) error

RemoteModelSelectionGuard refuses a model assignment changing any model key an upper config level locks

func RemoveCacheFile

func RemoveCacheFile(h, name string)

RemoveCacheFile deletes the cache file and any legacy copy

func RemoveEnvSetting

func RemoveEnvSetting(ctx context.Context, h, key string) (bool, error)

RemoveEnvSetting removes the .env entry and any stale config.yaml copy and reports whether either existed

func RenameToolSearchBridgeForXAI

func RenameToolSearchBridgeForXAI(tools []map[string]any) ([]map[string]any, map[string]string)

RenameToolSearchBridgeForXAI aliases the tool_search bridge declaration xAI reserves, with the alias to original map

func RenderAccountUsageLines

func RenderAccountUsageLines(snapshot *AccountUsageSnapshot, markdown bool) []string

RenderAccountUsageLines renders a snapshot as usage lines, the stacked bar layout for usage window plans

func RenderBar

func RenderBar(fraction float64, width int) string

RenderBar draws a bracketed bar whose filled cells show the fraction, never empty above zero or full below one

func RenderCodexTOMLSection

func RenderCodexTOMLSection(servers map[string]*pyjson.Object, plugins []map[string]any, defaultPermissionProfile string) (string, error)

Managed block of default permissions, mcp_servers tables and plugins tables between the two markers

func RenderHistorySeed

func RenderHistorySeed(messages []map[string]any) string

Prior turns as one text block newest last, never the trailing user row being submitted

func RenderPresets

func RenderPresets(entries []*PresetEntry) string

INI text with a decision comment per model and a section for each admitted one

func RenderToolBridgeSections

func RenderToolBridgeSections(tools []any, toolChoice any, allowlist []string) ([]string, error)

Prompt sections carrying the forwarded tool schemas and the tool choice hint, empty when neither applies

func RepairToolCallArguments

func RepairToolCallArguments(rawArgs, toolName string) string

RepairToolCallArguments fixes truncated, trailing comma, or control character argument JSON, else returns {}

func RequiresAuthNotice

func RequiresAuthNotice(manifest map[string]any) string

RequiresAuthNotice is the install and show line naming the sign ins and oauth clients a plugin uses

func ResetBedrockProbeFailureCache

func ResetBedrockProbeFailureCache()

Empties the failed probe memo, the in memory state a process restart drops

func ResetCatalogCache

func ResetCatalogCache()

ResetCatalogCache clears the in process copy and every fetch failure backoff

func ResetDelayFromMessage

func ResetDelayFromMessage(message string) (time.Duration, bool)

ResetDelayFromMessage parses seconds until reset out of free text provider error copy

func ResetEntraCredentialCache

func ResetEntraCredentialCache()

ResetEntraCredentialCache clears the cached credentials for tests and profile switches

func ResetHint

func ResetHint(err error, now time.Time) string

ResetHint renders ~13m until the reset_at of an error, empty without a usable future reset

func ResetLaunchEnvSnapshotForTests

func ResetLaunchEnvSnapshotForTests()

Drops the frozen launch env so the next capture reads the process env again

func ResetSecretSourceCache

func ResetSecretSourceCache(h string)

ResetSecretSourceCache forgets applied homes so the next load re-pulls, one home or all

func ResolveAWSAuthEnvVar

func ResolveAWSAuthEnvVar(ctx context.Context) string

ResolveAWSAuthEnvVar names the active AWS auth source of the process, empty when none

func ResolveAffinityKey

func ResolveAffinityKey(ctx context.Context, sessionID string) string

ResolveAffinityKey is the rotation stable conversation affinity key, empty when nothing names the conversation

func ResolveAnthropicPromptCachePolicy

func ResolveAnthropicPromptCachePolicy(ctx context.Context, agent *CachePolicyAgent, dest CacheDestination) (bool, bool)

ResolveAnthropicPromptCachePolicy returns should cache and native layout for the agent and destination overrides

func ResolveAnthropicToken

func ResolveAnthropicToken(env PoolEnv, model string) string

ResolveAnthropicToken resolves an Anthropic token from env, pool and the borrowed Claude Code login in order

func ResolveAuthProvider

func ResolveAuthProvider(env PoolEnv, requested string) (string, error)

Canonical provider id auth resolution picks for a requested provider name

func ResolveAuxTaskProvider

func ResolveAuxTaskProvider(ctx context.Context, task string) string

Configured provider of a task with no explicit args, auto when nothing is configured

func ResolveBackend

func ResolveBackend(requested string, gpuVendor *string, target string) (string, error)

Strict for explicit backends, auto detects the GPU without vendor or target and falls back to compatible pins

func ResolveBedrockRegion

func ResolveBedrockRegion() string

ResolveBedrockRegion is the AWS region the environment and shared config select

func ResolveBedrockRuntimeRegion

func ResolveBedrockRuntimeRegion(ctx context.Context) string

ResolveBedrockRuntimeRegion is the region every Bedrock endpoint of the home must use

func ResolveCacheHome

func ResolveCacheHome(homePath string) string

ResolveCacheHome is the given home else the process home

func ResolveCodexCredentialAndBase

func ResolveCodexCredentialAndBase(ctx context.Context) (string, string, error)

ResolveCodexCredentialAndBase is the Codex token and the base url of the same authority

func ResolveCodexRuntimeCredentials

func ResolveCodexRuntimeCredentials(env PoolEnv, opts CodexResolveOptions) (map[string]any, error)

Exported Codex runtime credential resolution for the agent client refresh

func ResolveDirectStaleTimeout

func ResolveDirectStaleTimeout(ctx context.Context, agent ChatCompletionAgent, apiKwargs map[string]any) (float64, error)

Inline stale budget from the agent resolver with the hosted openai-codex floor and cap, inf for a non numeric answer

func ResolveDisplayContextLength

func ResolveDisplayContextLength(ctx context.Context, req DisplayContextRequest) (int, bool)

ResolveDisplayContextLength prefers the provider aware resolver and falls back to the catalog window

func ResolveEffectiveModel

func ResolveEffectiveModel(sessionOverrides, channelConfig, globalConfig any) string

ResolveEffectiveModel picks the session override, then the channel, then the global model

func ResolveEntryAPIKey

func ResolveEntryAPIKey(ctx context.Context, entry map[string]any) string

Inline or env backed key of a fallback entry through the secret scope aware resolver

func ResolveEnvCredentials

func ResolveEnvCredentials(env PoolEnv, providerID, requestedProvider string) (apiKey, baseURL, defaultBase string, ok bool)

Current .env key, base url and registry default of an api key or named custom provider, ok false when none

func ResolveFallbackEntryAPIKey

func ResolveFallbackEntryAPIKey(ctx context.Context, h string, entry map[string]any) string

Fallback entry key, inline api_key else key_env through the home's secret scope

func ResolveFastModeOverrides

func ResolveFastModeOverrides(model, providerName, baseURL, tier string) map[string]any

ResolveFastModeOverrides returns the fast or priority request overrides, nil when unsupported

func ResolveMoAPreset

func ResolveMoAPreset(raw any, name string) (map[string]any, error)

ResolveMoAPreset returns a copy of the named preset, the configured default when name is empty

func ResolveNativeCompactionCapability

func ResolveNativeCompactionCapability(model, baseURL, providerName string, isCodexBackend bool) bool

Whether the route serves the native Responses compaction endpoint for the model

func ResolvePersistBehavior

func ResolvePersistBehavior(ctx context.Context, isGlobal, isSession, isOnce bool, explicitProvider string) bool

ResolvePersistBehavior decides whether a model switch persists to config.yaml

func ResolvePricingProvider

func ResolvePricingProvider(provider, baseURL string) string

ResolvePricingProvider returns the canonical pricing source for a provider, empty when a custom entry is unproven

func ResolvePromptCacheScope

func ResolvePromptCacheScope(a *CacheScopeAgent) string

ResolvePromptCacheScope returns the rotation stable cache scope, memoized per session id and store presence

func ResolvePromptCacheScopeSafe

func ResolvePromptCacheScopeSafe(a *CacheScopeAgent) (scope string)

ResolvePromptCacheScopeSafe resolves the scope and turns any panic into an empty scope meaning the physical id

func ResolveRequestedProvider

func ResolveRequestedProvider(ctx context.Context, h, requested string) (string, error)

Explicit provider, then the config provider, then ICEBATH_INFERENCE_PROVIDER, else auto

func ResolveResponsesReasoning

func ResolveResponsesReasoning(ctx context.Context, model, providerName, baseURL string, isCodexBackend, isXAI, disabled bool, effort string) (string, bool)

Clamped effort and enabled flag a Responses route sends, empty effort when the route takes no reasoning field

func ResolveRuntimePoolKey

func ResolveRuntimePoolKey(provider, baseURL string, cfg map[string]any) string

ResolveRuntimePoolKey is the pool key for a runtime provider identity, the normalized identity when no scoped key fits

func ResolveTimeout

func ResolveTimeout(cfg config.Tree, key string, def time.Duration, hasDefault bool, envVar string) (time.Duration, bool)

ResolveTimeout picks timeouts.<key> over the env var over the default, invalid values fall through with a warning

func ResolveXAIOAuthRuntimeCredentials

func ResolveXAIOAuthRuntimeCredentials(env PoolEnv, forceRefresh, refreshIfExpiring bool, refreshSkew time.Duration) (map[string]any, error)

Exported xAI OAuth runtime credential resolution for the agent client refresh

func ResponseStopDetails

func ResponseStopDetails(resp *Response) any

ResponseStopDetails returns the stop_details object a Messages reply carried, nil when it carried none

func ResponsesRouteIsCodexBackend

func ResponsesRouteIsCodexBackend(providerName, baseURL string) bool

Route is the ChatGPT codex backend by exact provider name or chatgpt.com codex path

func RestoreAuthActiveProvider

func RestoreAuthActiveProvider(store *Store, value any, present bool) error

RestoreAuthActiveProvider writes a snapshotted active_provider back, removing the key when it was absent

func RestoreModelCfg

func RestoreModelCfg(ctx context.Context, h string, modelBefore any) error

RestoreModelCfg puts the config model section back to a captured snapshot, re inserted last like a dict

func RestorePrimaryRoute

func RestorePrimaryRoute(ctx context.Context, h string, store *Store, modelBefore, activeBefore any, activePresent bool) error

RestorePrimaryRoute attempts both halves of the temporary picker route restoration

func RestoreSecretRegistration

func RestoreSecretRegistration(name string, current, previous SecretSource, scope string) bool

RestoreSecretRegistration restores a host owned registration when it is still current

func RetryAfterFrom

func RetryAfterFrom(value string) time.Duration

RetryAfterFrom parses a Retry-After header value in seconds or HTTP date form

func RetryAfterFromHeaders

func RetryAfterFromHeaders(h http.Header) (time.Duration, bool)

RetryAfterFromHeaders reads Retry-After from a header set trying both casings

func RootIcebathOAuthFile

func RootIcebathOAuthFile(env PoolEnv) string

The global root PKCE file inside a named profile, empty in classic mode

func RotateRuntimeMainAPIKey

func RotateRuntimeMainAPIKey(ctx context.Context, old, new any)

Swaps a revoked main key for its replacement inside the published runtime map in place

func RoughFit

func RoughFit(totalBytes int64, budget HardwareBudget) string

Coarse pre download verdict from file size alone, fits-gpu, needs-ram or too-big

func RouteAnswer

func RouteAnswer(ctx context.Context, hook, providerName string, scope any, kwargs map[string]any) any

RouteAnswer is the first truthy answer of hook across the route profiles, nil when no profile claims the endpoint

func RouteKey

func RouteKey(value any) string

RouteKey is the endpoint compared for identity with scheme and host folded

func RouteSupportedEfforts

func RouteSupportedEfforts(provider, model, apiMode string) []string

Reasoning efforts the route of a provider, model and API mode accepts

func RoutedCustomIdentity

func RoutedCustomIdentity(baseURL, model string, cfg map[string]any, held string) string

RoutedCustomIdentity names the configured entry a bare custom pick on a URL or model resolves to

func RoutedModelRejectsVisionToolMessages

func RoutedModelRejectsVisionToolMessages(ctx context.Context, provider, model string) bool

Whether the route or the aggregator targeted model's profile rejects image tool parts

func RouterLaunchCtx

func RouterLaunchCtx(client *probeClient, serverURL, model string) (int, bool, error)

RouterLaunchCtx reads the ctx size flag from the router launch args of the model

func RoutesAtHosts

func RoutesAtHosts(h string, hosts []string) bool

RoutesAtHosts reports a configured route whose base url is at one of the hosts or a subdomain

func RoutingProcessHome

func RoutingProcessHome() string

RoutingProcessHome is the pinned launch home, else the process home

func RowOwnedByEntry

func RowOwnedByEntry(row PooledCredential, entry map[string]any) bool

RowOwnedByEntry is ownership by provenance, manual rows and rows seeded from the entry's own key env

func RunCodexAppServerTurn

func RunCodexAppServerTurn(agent CodexRuntimeAgent, userMessage string, originalUserMessage any, messages []map[string]any, effectiveTaskID string, shouldReviewMemory bool, turnID any) (map[string]any, error)

Hands the turn to the codex app server and projects its events into messages in the chat completions shape

func RunCodexStream

func RunCodexStream(ctx context.Context, agent ChatCompletionAgent, apiKwargs map[string]any, client any, onFirstDelta func()) (any, error)

Runs one streaming Responses API request over raw create events with one physical retry

func RunCodexToolsMCPServer

func RunCodexToolsMCPServer(argv []string) int

RunCodexToolsMCPServer is the tools MCP server entry, 2 when it cannot start and 1 when it crashes

func RunIcebathOAuthLoginPure

func RunIcebathOAuthLoginPure(env PoolEnv, prompt func(label string) (string, bool)) map[string]any

Runs the icebath native PKCE flow and returns the credential state

func RunOAuthSetupToken

func RunOAuthSetupToken(env PoolEnv) (string, error)

RunOAuthSetupToken runs claude setup-token interactively and returns the resulting token

func RunSetupActionWithNavigation

func RunSetupActionWithNavigation(ctx context.Context, label string, action func(ctx context.Context) error, cancelledMessage string) error

RunSetupActionWithNavigation runs a setup style menu flow with Escape and nested Left navigation outside the wizard

func RunSetupSteps

func RunSetupSteps(steps []SetupStep) error

RunSetupSteps runs labelled sections with left arrow navigation between and inside them

func RunWithSetupNavigation

func RunWithSetupNavigation(fn func() error, cancelledMessage string) error

RunWithSetupNavigation runs fn under a navigation scope, a cancel printing the message instead of unwinding

func RunWizardWithSetupNavigation

func RunWizardWithSetupNavigation(fn func() error, cancelledMessage string) error

RunWizardWithSetupNavigation is the navigation scope of the whole wizard, where leaving takes a second Escape

func RuntimeEntryOwner

func RuntimeEntryOwner(ctx context.Context, provider, requestedProvider, baseURL string, cfg map[string]any) map[string]any

RuntimeEntryOwner is the credential provenance of the entry owning a custom runtime, names only

func RuntimeHasCredentials

func RuntimeHasCredentials(rt *Runtime) bool

RuntimeHasCredentials reports a resolved runtime carrying a credential a request can use, a usable secret, a token source, an SDK or keyless placeholder or an external process command

func RuntimeMainOf

func RuntimeMainOf(ctx context.Context) map[string]any

RuntimeMainOf is the live main runtime bound to the context, nil outside a binding

func RuntimesRoot

func RuntimesRoot() string

Machine scoped presets and server state directory, binaries live in the PM store

func SDKStatusClass

func SDKStatusClass(status int) string

SDKStatusClass is the openai SDK error class an HTTP status raises

func SameAuthStore

func SameAuthStore(a, b string) bool

SameAuthStore reports whether two paths name one store including hardlinks and bind mounts

func SameCredentialSurface

func SameCredentialSurface(a, b BackendIdentity) bool

SameCredentialSurface reports two identities sharing the credential a 401 or 402 just invalidated

func SameDeploymentIn

func SameDeploymentIn(ctx context.Context, a, b BackendIdentity) bool

SameDeploymentIn reports the exact same model deployment with first class providers read from the context home

func SameEndpoint

func SameEndpoint(a, b BackendIdentity) bool

SameEndpoint reports two identities behind the endpoint that just went unreachable

func SanitizeBorrowedCredentialPayload

func SanitizeBorrowedCredentialPayload(payload map[string]any, providerID string) map[string]any

SanitizeBorrowedCredentialPayload strips raw secret fields from borrowed pool rows and leaves owned rows unchanged

func SanitizeConsumerCodexRequest

func SanitizeConsumerCodexRequest(agent any, request map[string]any) map[string]any

func SanitizeHookPayload

func SanitizeHookPayload(value any) any

SanitizeHookPayload returns JSON safe data under the size cap, retrying with tighter caps then a preview

func SanitizeLoadedCredentials

func SanitizeLoadedCredentials()

SanitizeLoadedCredentials strips non ASCII from credential env vars, warning once per key

func SaveContextLength

func SaveContextLength(ctx context.Context, model, baseURL string, length int, source string)

SaveContextLength persists a discovered window under model at base url, source marks Bedrock provenance

func SaveEnvSetting

func SaveEnvSetting(ctx context.Context, h, key, value string) error

SaveEnvSetting writes an environment setting to .env and drops stale config.yaml copies

func SaveProviderContextLength

func SaveProviderContextLength(ctx context.Context, model, baseURL string, length int, providerName string)

SaveProviderContextLength persists a provider confirmed window, Bedrock routes get their provenance marker

func SaveWindowOverride

func SaveWindowOverride(modelID string, window int) error

Records a model's granted window, keeping every other model's grant

func ScopedFallbackChain

func ScopedFallbackChain(inherited []map[string]any, declared any, declaredSet bool, pinned bool, owner string) []map[string]any

ScopedFallbackChain picks the chain for a route owner that can pin its own primary, nil disabling fallback

func ScopedRuntimeMain

func ScopedRuntimeMain(ctx context.Context, mainRuntime map[string]any) (context.Context, map[string]any)

Binds a sanitized copy of an explicit runtime, an empty one clearing the binding

func ScrubANSI

func ScrubANSI(text string) string

ScrubANSI strips ANSI escape sequences from helper output

func SecretFingerprint

func SecretFingerprint(material string) string

SecretFingerprint is a SHA-256 prefix used as a cache key, never logged or displayed

func SecretHomeApplied

func SecretHomeApplied(h string) bool

Reports whether every external secret source of a home applied, the exported face for pkg/mcp

func SecretScopeBound

func SecretScopeBound(ctx context.Context) bool

True while a secret scope is bound to the context

func SecretSourceEnabled

func SecretSourceEnabled(cfg map[string]any) bool

SecretSourceEnabled reads the enabled flag of a section

func SecretSourceFetchTimeout

func SecretSourceFetchTimeout(cfg map[string]any) time.Duration

SecretSourceFetchTimeout is the wall clock budget enforced around a fetch

func SecretSourceLabel

func SecretSourceLabel(h, name string) string

SecretSourceLabel is the " (from X)" suffix naming the external source that supplied the env var

func SecretSourceNames

func SecretSourceNames() []string

SecretSourceNames are the env var names some profile's external source applied

func SecretSourceOf

func SecretSourceOf(h, envVar string) string

SecretSourceOf is the source label that supplied the env var, empty for .env and shell keys

func SecretSourceOverrideExisting

func SecretSourceOverrideExisting(spec SecretSourceSpec, cfg map[string]any) bool

SecretSourceOverrideExisting reports whether the source may overwrite .env and shell values

func SecretSourceProtectedEnvVars

func SecretSourceProtectedEnvVars(spec SecretSourceSpec, cfg map[string]any) map[string]bool

SecretSourceProtectedEnvVars are the names no source may overwrite

func SecretSourceRemediation

func SecretSourceRemediation(spec SecretSourceSpec, kind SecretErrorKind, cfg map[string]any) string

SecretSourceRemediation is the one line fix for a failed fetch, empty suppresses the hint

func SecretSourceRestoreValues

func SecretSourceRestoreValues(h string) map[string]string

SecretSourceRestoreValues is the subset of a home's snapshot a dotenv reload may re-assert

func SecretSourceScopedRegistry

func SecretSourceScopedRegistry() plugins.ScopedRegistry

Plugin context view of the secret source registry that register_secret_source drives

func SecretSourceTokenEnv

func SecretSourceTokenEnv(spec SecretSourceSpec, cfg map[string]any) string

SecretSourceTokenEnv is the env var holding the source's bootstrap credential

func SecretSourceValues

func SecretSourceValues(h string) map[string]string

SecretSourceValues is the external secret value snapshot for a home

func SecretsCommand

func SecretsCommand(ctx context.Context, h string, ns map[string]any, w io.Writer) (int, error)

SecretsCommand runs icebath secrets from the parsed namespace, printing help when no integration was named

func SeedCatalogCacheFromCheckout

func SeedCatalogCacheFromCheckout(ctx context.Context, projectRoot string) bool

SeedCatalogCacheFromCheckout overwrites the disk cache with the checkout's shipped manifest

func SelectProviderAndModel

func SelectProviderAndModel(ctx context.Context, ns map[string]any) error

SelectProviderAndModel runs the provider picker, the provider's credential and model flow, and the effort step

func SelectedConfigBackendName

func SelectedConfigBackendName(h string) string

Config backend kind a load would select for the home, decided without loading or booting anything

func SelectionRouteChanged

func SelectionRouteChanged(modelCfg map[string]any, result ModelSwitchResult) bool

SelectionRouteChanged reports whether the provider or endpoint differs between a model section and the switch target

func SendWithParameterRungs

func SendWithParameterRungs(ctx context.Context, send func(ctx context.Context, client AuxClient, kwargs map[string]any) (any, error),
	client AuxClient, kwargs map[string]any, task string) (any, error)

Sends once and retries a parameter 400 through the parameter rungs, other errors propagating unchanged

func SendWithParameterRungsAsync

func SendWithParameterRungsAsync(ctx context.Context, send func(ctx context.Context, client AuxClient, kwargs map[string]any) (any, error),
	client AuxClient, kwargs map[string]any, task string) (any, error)

Async twin of the parameter rung send, tagging its log lines as async

func ServeNoticesOnStderr

func ServeNoticesOnStderr()

ServeNoticesOnStderr declares a terminal front end whose provider recovery outcomes print to stderr

func ServerChildEnv

func ServerChildEnv(base map[string]string) map[string]string

Returns a copy of base without any variable whose uppercased name carries a credential marker

func ServesRoutedProfile

func ServesRoutedProfile(ctx context.Context) bool

ServesRoutedProfile is true when the task runs for a profile other than the process's own

func ServiceTierWord

func ServiceTierWord(tier string) string

ServiceTierWord is the user facing word for a stored tier

func SessionAuxiliaryScope

func SessionAuxiliaryScope(ctx context.Context, auxiliary any) context.Context

SessionAuxiliaryScope publishes a gateway session's frozen auxiliary section for the turn, a non mapping becomes empty

func SessionProviderIdentity

func SessionProviderIdentity(ctx context.Context, provider, requestedProvider, baseURL, model string, cfg map[string]any) string

Identity of a session route, the requested entry while it still serves base URL, else the endpoint owner, else the adapter

func SessionSourceFor

func SessionSourceFor(env *tools.Env, platform string) string

Session row source from the bound session context, a one shot run getting oneshot, else the platform or cli

func SetAccountingContext

func SetAccountingContext(ctx context.Context, db AuxUsageRecorder, sessionID string) context.Context

Context carrying the active session's accounting handles, cleared when either handle is missing

func SetAnthropicLiveBlocks

func SetAnthropicLiveBlocks(m *state.Message, blocks []any)

SetAnthropicLiveBlocks replaces the ordered Messages block sidecar of a live message

func SetAuxLifecycleHooks

func SetAuxLifecycleHooks(has func(ctx context.Context, name string) bool, invoke func(ctx context.Context, name string, kwargs map[string]any) []any)

Routes auxiliary hook presence and dispatch through the lifecycle the built in observers and plugins share

func SetCodexQuotaProbe

func SetCodexQuotaProbe(fn func(env PoolEnv, token, baseURL string) (bool, bool)) func()

SetCodexQuotaProbe swaps the live quota probe and returns the function that puts the previous one back

func SetCodexRuntime

func SetCodexRuntime(cfg map[string]any, newValue string) (string, error)

Stores the runtime in the config in place and returns the previous one

func SetFallbackCheckCommand

func SetFallbackCheckCommand(check func(ctx context.Context, h string, ns map[string]any, w io.Writer) (int, error))

SetFallbackCheckCommand installs the handler icebath fallback check dispatches to

func SetMultiplexActive

func SetMultiplexActive(active bool)

SetMultiplexActive marks the process a profile multiplexer and pins the launch home while it is

func SetPoolClock

func SetPoolClock(fn func() time.Time) func()

SetPoolClock swaps the pool wall clock and returns the function that puts the previous one back

func SetRuntimeMain

func SetRuntimeMain(ctx context.Context, provider, model string, opts RuntimeMainOptions) context.Context

Binds the live main runtime for auxiliary routing under the returned context

func SetdefaultDict

func SetdefaultDict(cfg map[string]any, key string) (map[string]any, error)

SetdefaultDict is the section under key, created when absent, a SetupTypeError when the value is not a mapping

func SetupConsole

func SetupConsole() *cliui.Console

SetupConsole is the console setup prompts read and print on

func SetupInfo

func SetupInfo(lines ...any)

SetupInfo prints each line as info in order, a nil line printing a bare blank line

func SetupModelProvider

func SetupModelProvider(ctx context.Context, cfg config.Tree) error

SetupModelProvider runs the shared provider and model picker, then reloads and resaves the config it wrote

func SetupModuleInstalled

func SetupModuleInstalled(ctx context.Context, name string) (found bool)

SetupModuleInstalled reports whether the dependency environment finds a Python module, false when the probe fails

func SetupOutput

func SetupOutput() io.Writer

SetupOutput is the writer the setup console prints on

func SetupPrintError

func SetupPrintError(text string)

SetupPrintError prints a red cross line on the setup console

func SetupPrintInfo

func SetupPrintInfo(text string)

SetupPrintInfo prints a dim indented line on the setup console

func SetupPrintSuccess

func SetupPrintSuccess(text string)

SetupPrintSuccess prints a green check line on the setup console

func SetupPrintWarning

func SetupPrintWarning(text string)

SetupPrintWarning prints a yellow warning line on the setup console

func SetupPrompt

func SetupPrompt(question, def string, password bool) string

SetupPrompt reads a line with an optional default, a password through the masked prompt, Ctrl-C or EOF exiting 1

func SetupSectionRule

func SetupSectionRule(title string)

SetupSectionRule prints the blank padded cyan divider of the key entry screens

func SetupSystemExit

func SetupSystemExit(err error) (code int, message string, ok bool)

SetupSystemExit is the exit code and message of a Python SystemExit leaving a setup flow, false for any other error

func SetupToolsEnv

func SetupToolsEnv(ctx context.Context) *tools.Env

SetupToolsEnv is the tool environment the setup sections run their tool configuration in

func ShapeWireCarriers

func ShapeWireCarriers(ctx context.Context, messages []map[string]any, model, baseURL string, scope any) []map[string]any

ShapeWireCarriers is the wire copy of messages with each carrier only on the route that reads it

func ShouldBypassProxy

func ShouldBypassProxy(targets []string, noProxyValue *string) bool

ShouldBypassProxy is true when NO_PROXY matches at least one target host URL or host port

func ShouldClearContextPin

func ShouldClearContextPin(configuredModel, activeModel, configuredBaseURL, activeBaseURL, configuredProvider, activeProvider string) (clear bool)

ShouldClearContextPin reports whether a configured context_length pin no longer matches its runtime route

func ShouldSkipCandidateIn

func ShouldSkipCandidateIn(ctx context.Context, candidate, failed BackendIdentity, scope FailureScope) bool

ShouldSkipCandidateIn is the skip test with first class providers read from the context home

func ShouldUseDirectAPICall

func ShouldUseDirectAPICall(ctx context.Context, provider, platform string, mode APIMode) bool

True when a request runs inline on the caller instead of an abandonable worker, for cron turns and delegated children

func ShouldUseOllamaNativeCatalog

func ShouldUseOllamaNativeCatalog(ctx context.Context, provider, baseURL string, headers map[string]string) bool

ShouldUseOllamaNativeCatalog reports whether discovery should read the native api tags catalog of an endpoint

func ShutdownCachedClients

func ShutdownCachedClients(ctx context.Context)

ShutdownCachedClients closes and clears every cached client outside the lock, a live foreign loop's clients only neutered

func ShutdownLocalRuntime

func ShutdownLocalRuntime() error

Stops the process local server and forgets the engine it served

func SignInFailureLines

func SignInFailureLines(err error, serviceHost, retryCommand string) []string

SignInFailureLines are the lines to print when a device code or browser sign in fails for a non timeout reason

func SkipDeepMerge

func SkipDeepMerge(prefix, key string) bool

SkipDeepMerge reports whether the missing config recursion must not descend into the named preset map

func SnapshotAuthActiveProvider

func SnapshotAuthActiveProvider(store *Store) (any, bool, error)

SnapshotAuthActiveProvider returns the active_provider of auth.json under the store lock and whether it exists

func SnapshotProviderRegistryForTests

func SnapshotProviderRegistryForTests() func()

Captures the process wide provider registry and returns the closure that restores it and drops the caches built over it

func SourceChildEnv

func SourceChildEnv(environ *SourceEnvironment) map[string]string

SourceChildEnv is the environment for a helper child, the scrubbed process env or only the per fetch view

func SourceSuppliedNames

func SourceSuppliedNames() []string

SourceSuppliedNames are the names an external source supplied for any home, applied or skipped

func SpentRotationSourcePath

func SpentRotationSourcePath(env PoolEnv, source string) string

SpentRotationSourcePath maps a pool entry source to the shared singleton file it borrows from

func SpillOverrides

func SpillOverrides(profile ModelProfile, spillBytes *int64) []string

Override flags moving expert or recurrent block FFN weights to host so attention and KV stay on GPU

func SplitHistoryForPartialCompress

func SplitHistoryForPartialCompress(history []map[string]any, keepLast int) ([]map[string]any, []map[string]any)

Summarized head and verbatim tail of the last keep exchanges, whole history and no tail when the head is empty

func SplitHostPort

func SplitHostPort(value string) (string, int, bool)

SplitHostPort is the lowercased host and optional port of a URL, a bracketed v6, a host with port or a bare host

func SplitParts

func SplitParts(path string) []string

Every on disk part of the split path belongs to, first first, nil unless another part exists

func SplitResponsesToolID

func SplitResponsesToolID(raw string) (string, string)

SplitResponsesToolID splits a stored tool id into the call id and the response item id

func SpotifyAuthStatus

func SpotifyAuthStatus(h string) (map[string]any, error)

SpotifyAuthStatus reports whether the home holds a usable Spotify login and its stored fields

func SpotifyHTTPDo

func SpotifyHTTPDo(ctx context.Context, method, rawURL string, body io.Reader, headers map[string]string, timeoutSeconds float64) (*pyhttpx.Response, error)

SpotifyHTTPDo sends one Spotify request like a default httpx call, failures named as the httpx exception

func SpotifyLogin

func SpotifyLogin(ctx context.Context, h string, opts SpotifyLoginOptions, out io.Writer) error

SpotifyLogin runs the loopback PKCE login, first time setup included, and stores the tokens under providers.spotify

func SpotifyLogout

func SpotifyLogout(h string) (bool, error)

SpotifyLogout drops the stored Spotify login and reports whether anything was removed

func SpotifyResolveRuntimeCredentials

func SpotifyResolveRuntimeCredentials(ctx context.Context, h string, forceRefresh, refreshIfExpiring bool) (map[string]any, error)

SpotifyResolveRuntimeCredentials reads the stored login, refreshing it when forced or expiring, and returns the API credentials

func StampCreatedConfig

func StampCreatedConfig(h string, cfg map[string]any)

StampCreatedConfig stamps a config.yaml an automatic step creates as current with its rows in use noted

func StateAuxiliaryUsage

func StateAuxiliaryUsage(u AuxiliaryUsage) state.AuxiliaryUsage

Session store row of one auxiliary call, an empty provider or base URL stored as NULL like None

func StaticCatalog

func StaticCatalog(ctx context.Context, provider string) []string

StaticCatalog returns a provider's built in curated row else the bound home's plugin static models

func StaticCatalogProviders

func StaticCatalogProviders(ctx context.Context) []string

StaticCatalogProviders lists every provider with a static row in the bound home, built ins then plugin profiles

func StreamCodexPassthrough

func StreamCodexPassthrough(ctx context.Context, agent ChatCompletionAgent, apiKwargs map[string]any, onFirstDelta func()) (any, error)

Streams a codex turn through the blocking call with the first delta callback parked on the agent

func StreamDiagCaptureResponse

func StreamDiagCaptureResponse(diag *StreamDiag, resp *http.Response)

Snapshots the HTTP status and the known headers at stream open so they survive an early drop

func StreamWriterIsCurrent

func StreamWriterIsCurrent(agent any, token int) bool

True while token is the active writer, a zero token or a fenceless agent cannot prove supersession

func StringifyProviderMap

func StringifyProviderMap(providers any) map[string]any

StringifyProviderMap copies a providers mapping so every key is a string

func StripAnthropicCacheControl

func StripAnthropicCacheControl(messages []map[string]any) []map[string]any

Removes cache control markers from the request messages

func StripAnthropicToolCacheControl

func StripAnthropicToolCacheControl(tools []map[string]any) []map[string]any

Removes cache control markers from the tool schemas

func StripCodexContextVariantSuffix

func StripCodexContextVariantSuffix(model string) string

StripCodexContextVariantSuffix removes a valid 900k suffix, an ineligible alias is returned unchanged

func StripOpaqueReplayItems

func StripOpaqueReplayItems(items any) any

Opaque replay items with encrypted payloads removed, the shape the budget estimator charges

func StripOrphanThinkCloseTags

func StripOrphanThinkCloseTags(text string) string

Text with close tags lacking a matching open removed with their trailing whitespace

func StripProviderPrefix

func StripProviderPrefix(model string) string

Model id with a known provider prefix such as openrouter or local removed

func StripRejectedThinking

func StripRejectedThinking(message map[string]any, rejected map[string]bool) int

StripRejectedThinking drops rejected thinking blocks from one request copy, every block when rejected is nil

func StripThinkBlocks

func StripThinkBlocks(content string) string

StripThinkBlocks removes reasoning blocks and stray tool call XML from assistant text

func StripUnverifiedReasoningItems

func StripUnverifiedReasoningItems(msgs []*state.Message, issuerKind, issuerModel string) int

StripUnverifiedReasoningItems drops replayed items without an exact issuer and model stamp, returning the count

func SuggestPrefixedModelID

func SuggestPrefixedModelID(provider, model string) string

SuggestPrefixedModelID returns the unambiguous catalogue id for a bare model name or empty

func SummarizeAPIError

func SummarizeAPIError(err error, provider string) string

SummarizeAPIError extracts a human readable one liner from a provider failure

func SummarizeCompressPreview

func SummarizeCompressPreview(history []map[string]any, partial bool, keepLast int, focusTopic *string, approxTokens int) map[string]any

Preview report with head, tail and total counts, the effective partial flag and printable lines, history untouched

func SummarizeTimeoutError

func SummarizeTimeoutError(err error, provider string) (string, bool)

SummarizeTimeoutError names the timeout phase and the setting to raise, false for other errors

func SummarizeUserMessageForLog

func SummarizeUserMessageForLog(content any, sep string) string

SummarizeUserMessageForLog flattens content to text with an image count marker

func SwapBedrockProbe

func SwapBedrockProbe(fn func(context.Context, string, string) int) (prev func(context.Context, string, string) int)

Installs a context probe for tests of other packages and returns the previous one

func SwapDetectServerForTests

func SwapDetectServerForTests(fn func([]int) (*DetectedServer, error)) func()

Replaces the local server probe for a case of another package and hands back the restore

func SwapDirectWatchdogArmForTests

func SwapDirectWatchdogArmForTests(arm func(time.Duration, func()) *time.Timer) func()

Replaces the inline stale watchdog timer for a test in another package, the returned function restoring it

func SwapLeftCoreTableForTests

func SwapLeftCoreTableForTests(rows []LeftCoreFeature) func()

SwapLeftCoreTableForTests replaces the rows and returns the restore of the previous table

func SwapNoticesOnStderrForTests

func SwapNoticesOnStderrForTests(on bool) bool

Sets whether kept notices are served on stderr and returns the previous setting, for tests that restore it

func SwapResolveBedrockRegion

func SwapResolveBedrockRegion(fn func() string) (prev func() string)

Installs a region lookup for tests of other packages and returns the previous one

func SwapSetupChecklist

func SwapSetupChecklist(fn func(title string, items []string, pre map[int]bool) (map[int]bool, error)) func()

SwapSetupChecklist replaces the setup checklist, the returned func restoring the previous one

func SwapSetupRadiolist

func SwapSetupRadiolist(fn func(question string, choices []string, def int, description string) int) func()

SwapSetupRadiolist replaces the setup menu, the returned func restoring the previous one

func SyncRegisteredProviders

func SyncRegisteredProviders(profiles []Profile)

SyncRegisteredProviders adds the env vars of the process wide plugin provider profiles discovery registered

func TakeTurnAuthorFromEnv

func TakeTurnAuthorFromEnv(environ map[string]string) *pyjson.Object

Reads and removes the turn author variable so subprocesses started during the turn do not inherit it

func ThinkCloseTags

func ThinkCloseTags() [][]rune

Lowercase closing think tags the stream scrubbers recognise

func ThinkOpenTags

func ThinkOpenTags() [][]rune

Lowercase opening think tags the stream scrubbers recognise

func TimeoutPhase

func TimeoutPhase(err error) string

TimeoutPhase reports connect or read for a timeout in the cause chain, empty for other errors

func TimeoutsSection

func TimeoutsSection(cfg config.Tree) map[string]any

TimeoutsSection reads the timeouts root section of the config, empty when absent or malformed

func ToOpenAIBaseURL

func ToOpenAIBaseURL(baseURL string) string

ToOpenAIBaseURL is the OpenAI compatible sibling of a dual surface Anthropic URL

func TokenPairsByID

func TokenPairsByID(entries []map[string]any) map[string]TokenPair

TokenPairsByID snapshots the token generation of every row including blank pairs for token less rows

func ToolModelContextLength

func ToolModelContextLength(ctx context.Context, q tools.ContextLengthQuery) int

Context window the tool search gate sizes against, the full resolver over the routed provider credentials

func ToolRuntimeCredentials

func ToolRuntimeCredentials(ctx context.Context, env *tools.Env, requested, targetModel string) (string, string, error)

ToolRuntimeCredentials resolves the live base URL and api key of a requested provider for a tool model lookup

func ToolSpecsFromOpenAITools

func ToolSpecsFromOpenAITools(tools []any, allowlist []string) []*pyjson.Object

Flattens OpenAI tools into name, description and parameters specs, skipping malformed entries and those outside a non nil allowlist

func TrackPoolConns

func TrackPoolConns(t *http.Transport, conns ...net.Conn) *http.Transport

TrackPoolConns tracks the transport's pool and seeds it with conns for tests that sweep a known socket

func TurnAuthorEnv

func TurnAuthorEnv(author *pyjson.Object) (map[string]string, error)

Environment entry a dispatcher merges into a child env with the compact JSON author

func TurnAuthorFromEnv

func TurnAuthorFromEnv(environ map[string]string) *pyjson.Object

Author the dispatcher placed in the turn author variable of environ, nil environ reading the process environment

func URLPath

func URLPath(rawURL string) string

URLPath returns the URL path lowercased without a trailing slash, empty for a bare host or a bad netloc

func UbLogitsBytes

func UbLogitsBytes(nVocab int64, mtpCapable, mtpPrefill bool) int64

GPU logits buffer bytes of the microbatch posture launch flags choose, priced from the vocab

func UltrafastOffered

func UltrafastOffered(model, providerName, baseURL, accessToken string) (bool, error)

UltrafastOffered reports whether ultrafast is offered on the route, the Codex plan gated by its own catalog

func UnavailableReason

func UnavailableReason(backend, target string) (string, error)

Why backend cannot run on target, empty when built upstream and pinned, empty target meaning this host

func UnlistedProviderNames

func UnlistedProviderNames(ctx context.Context) map[string]bool

UnlistedProviderNames returns registered profiles discovery surfaces must not offer, a failing gate hiding its profile

func UnquoteDotenvValue

func UnquoteDotenvValue(raw string) string

UnquoteDotenvValue strips one layer of matching surrounding quotes from a dotenv value

func UnregisterProvider

func UnregisterProvider(name string)

UnregisterProvider drops a runtime registered profile and its aliases, the restore step of a test registration

func UnsetReasoningDefault

func UnsetReasoningDefault(ctx context.Context, agent ChatCompletionAgent) (out map[string]any)

Profile default reasoning for an unset effort on chat completions, nil when the model or local server cannot reason

func UsableBesidePromptCache

func UsableBesidePromptCache(live HardwareBudget, residents int) (int64, error)

Device memory a model may plan with on Windows unified memory leaving each resident the smallest cache

func UsageCommand

func UsageCommand(ctx context.Context, env PoolEnv, ns map[string]any, w io.Writer) (int, error)

UsageCommand prints the configured or requested account's usage windows, exit 1 when nothing could be fetched

func UsageSnapshotDocument

func UsageSnapshotDocument(snapshot *AccountUsageSnapshot) map[string]any

UsageSnapshotDocument is the icebath usage --json document, keys stable and extended only by adding keys

func UserAgent

func UserAgent(product string) string

UserAgent builds the attribution header value sent to aggregators, the product and its base version

func UsesSilentCatalogDefault

func UsesSilentCatalogDefault(provider string) bool

UsesSilentCatalogDefault reports whether a provider's silent default comes from the catalog label

func ValidateBaseURL

func ValidateBaseURL(baseURL string) error

ValidateBaseURL rejects an http or https custom endpoint URL whose port cannot be parsed

func ValidateCatalogManifest

func ValidateCatalogManifest(data any) bool

ValidateCatalogManifest reports whether data has the minimum manifest shape at a known schema version

func ValidateOAuthPKCEConfig

func ValidateOAuthPKCEConfig(provider string, cfg OAuthPKCEConfig) error

ValidateOAuthPKCEConfig refuses a misdeclared config before any network request of login or refresh

func ValidateProxyEnvURLs

func ValidateProxyEnvURLs() error

ValidateProxyEnvURLs fails fast on a malformed proxy env URL after normalizing the proxy variables

func ValidatedOpenRouterProviderSort

func ValidatedOpenRouterProviderSort(raw any) (string, bool)

ValidatedOpenRouterProviderSort is the normalized provider.sort value, false when absent or invalid

func VertexGetConfig

func VertexGetConfig(ctx context.Context) (string, string)

Access token and base URL for the active profile, both empty when either cannot be resolved

func WaitNoticeText

func WaitNoticeText(model string, silenceSecs float64, phase string, watchdog *WatchdogDeadline) string

One neutral status line naming the wait phase and the watchdog that would reconnect

func WaitReasoningCapsWarms

func WaitReasoningCapsWarms()

WaitReasoningCapsWarms blocks until every background capability refresh has finished

func WarmOpenRouterReasoningCapsAsync

func WarmOpenRouterReasoningCapsAsync(ctx context.Context)

WarmOpenRouterReasoningCapsAsync warms the OpenRouter capability cache in the background

func WindowOverridesPath

func WindowOverridesPath() string

Path of the machine scoped file holding each model's granted window

func WithAffinityScope

func WithAffinityScope(ctx context.Context, scope string) context.Context

Child context publishing the declared routing affinity scope, an empty scope clears it

func WithAuxiliaryEventLoop

func WithAuxiliaryEventLoop(ctx context.Context, loop interface{ IsClosed() bool }) context.Context

WithAuxiliaryEventLoop binds the event loop async auxiliary clients built under the context belong to

func WithCodexWatchdogState

func WithCodexWatchdogState(ctx context.Context, s *CodexWatchdogState) context.Context

Context whose codex stream reports its event, progress and reconnect markers to the state

func WithConversationContext

func WithConversationContext(ctx context.Context, conversationID string) context.Context

Child context publishing the conversation lineage root id for sticky routing, an empty id clears it

func WithDeferredTokenMint

func WithDeferredTokenMint(ctx context.Context) context.Context

WithDeferredTokenMint resolves routes without exchanging short lived OAuth tokens up front

func WithFrozenRuntimeConfig

func WithFrozenRuntimeConfig(ctx context.Context, cfg map[string]any) context.Context

WithFrozenRuntimeConfig scopes resolution under the returned context to a session's frozen config over the defaults

func WithLaunchBody

func WithLaunchBody(ctx context.Context) context.Context

Marks a standalone launch profile body so a mid body fail closed flip resolves from the launch scope

func WithLaunchBodyScope

func WithLaunchBodyScope(ctx context.Context, resolver func() map[string]string) context.Context

WithLaunchBodyScope records the launch profile mapping a body entered before multiplexing started

func WithLaunchProfileRuntimeScope

func WithLaunchProfileRuntimeScope(ctx context.Context, launchHome string) context.Context

Binds the launch home override, launch secret scope and terminal policy over the frozen launch overlay

func WithLaunchProfileScopeIfMultiplexed

func WithLaunchProfileScopeIfMultiplexed(ctx context.Context) context.Context

Exported form of the launch profile scope binding for the gateway and serve hosts

func WithLeftCoreInstallsHeld

func WithLeftCoreInstallsHeld(ctx context.Context) context.Context

WithLeftCoreInstallsHeld marks a context whose resolutions never attempt a left core migration

func WithMultiplexContext

func WithMultiplexContext(ctx context.Context, active bool) context.Context

WithMultiplexContext runs the task under multiplex semantics regardless of the process flag

func WithPromptProgressKwargs

func WithPromptProgressKwargs(kwargs map[string]any) map[string]any

Copy of chat completions kwargs asking llama server for prompt progress chunks through extra_body

func WithReasoningFloor

func WithReasoningFloor(kwargs map[string]any) map[string]any

WithReasoningFloor copies kwargs with every thinking off encoding lifted to the floor, nil when nothing was disabled

func WithSecretScope

func WithSecretScope(ctx context.Context, secrets map[string]string, profileHome string) context.Context

WithSecretScope installs the profile secret mapping on the context, nil clears it

func WithSetupConsole

func WithSetupConsole(c *cliui.Console) func()

WithSetupConsole makes c the console setup prompts read and print on, the returned func restores the previous one

func WithSetupOutput

func WithSetupOutput(w io.Writer) func()

WithSetupOutput routes setup prints to w for a command's duration, the returned func restores the previous console

func WithStreamEmitters

func WithStreamEmitters(emitters StreamEmitters, run func() (any, error)) (any, error)

Runs one stream between the start and end hooks, the end carrying the final text or the error string

func WithoutGenerationModels

func WithoutGenerationModels(models []string) []string

WithoutGenerationModels drops generation ids and returns the same slice when none were dropped

func WithoutUnsupportedResponseFormat

func WithoutUnsupportedResponseFormat(ctx context.Context, extraBody *pyjson.Object, provider, baseURL, model, task string) (*pyjson.Object, error)

WithoutUnsupportedResponseFormat drops a response_format the route and model are known to reject

func WriteClaudeCodeCredentials

func WriteClaudeCodeCredentials(env PoolEnv, accessToken, refreshToken string, expiresAtMS int64, scopes []any, spentRefreshToken string) error

WriteClaudeCodeCredentials commits refreshed credentials to the Claude Code file and mirrors them into the Keychain

func WriteFallbackChain

func WriteFallbackChain(cfg map[string]any, chain []map[string]any)

WriteFallbackChain stores the chain under fallback_providers and drops the legacy fallback_model key

func WriteIcebathOAuthCredentials

func WriteIcebathOAuthCredentials(env PoolEnv, accessToken, refreshToken string, expiresAtMS int64, target string) error

Commits refreshed PKCE tokens to the home file or the borrowed root target

func WritePresets

func WritePresets(entries []*PresetEntry, presetPath string) error

Atomically writes the rendered INI with owner only permissions

func XAICredentialPoolSource

func XAICredentialPoolSource() tools.CredentialPoolSource

Pool source the tool layer installs as tools.CredentialPools

func XAIOAuthSectionLogin

func XAIOAuthSectionLogin(env PoolEnv, out io.Writer) bool

XAIOAuthSectionLogin runs the xAI Grok OAuth device login printing to out, saving the tokens without making xAI the active provider

func ZAICodingOverloadRetryCeiling

func ZAICodingOverloadRetryCeiling() int

ZAICodingOverloadRetryCeiling is one past the last long entry so the loop exhausts the full schedule

func ZAIPolicyNote

func ZAIPolicyNote(policy string) string

ZAIPolicyNote is the status suffix naming a Z.AI Coding overload backoff policy, empty for any other policy

Types

type APIError

type APIError struct {
	Provider   string
	Model      string
	StatusCode int
	Code       string
	Type       string
	Message    string
	Body       string
	RequestID  string
	RetryAfter time.Duration
	Kind       ErrorKind
	Err        error
	// Parsed Retry-After header of the failed response, nil when it carried none that parses
	RetryAfterHeader *time.Duration
}

APIError is a failed inference call classified for retry and fallback decisions

func Classify

func Classify(provider, model string, status int, body string, err error) *APIError

Classify builds an APIError whose Kind drives retry and fallback decisions

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Retryable

func (e *APIError) Retryable() bool

Retryable reports whether the same route may be tried again after a backoff

func (*APIError) SetRetryAfterHeader

func (e *APIError) SetRetryAfterHeader(raw string)

Records the Retry-After header of the failed response beside the cooldown the retry loop reads

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

type APIKeySecretResolver

type APIKeySecretResolver func(ctx context.Context) (apiKey, source string, ok bool)

APIKeySecretResolver is a provider owned credential resolution returning the runtime key and its source

type APIMode

type APIMode string

Wire protocol a route speaks

const (
	ModeChatCompletions   APIMode = "chat_completions"
	ModeAnthropicMessages APIMode = "anthropic_messages"
	ModeCodexResponses    APIMode = "codex_responses"
	ModeGeminiNative      APIMode = "gemini_native"
)

func AzureFoundryModelMode

func AzureFoundryModelMode(model string) APIMode

AzureFoundryModelMode returns codex_responses for Responses only Azure deployments or empty

func DetectAPIModeForURL

func DetectAPIModeForURL(baseURL string) APIMode

DetectAPIModeForURL is the api mode a base url implies by its path and host, empty when none

func DetermineModeCtx

func DetermineModeCtx(ctx context.Context, providerName, baseURL, model string) APIMode

DetermineModeCtx is DetermineMode resolving the route and the provider table under ctx

func HostMandatedMode

func HostMandatedMode(baseURL string) APIMode

HostMandatedMode returns the wire protocol an endpoint requires or empty when any works

func OpenCodeModelMode

func OpenCodeModelMode(providerID, modelID string) APIMode

OpenCodeModelMode picks the wire protocol an OpenCode Zen or Go model is served on

func OpencodeTransport

func OpencodeTransport(ctx context.Context, provider, model, baseURL string) (APIMode, string)

OpencodeTransport is the api mode and base URL rederived per model for an OpenCode relay target, empty mode otherwise

type AWSCredentialError

type AWSCredentialError struct {
	Provider string
	Message  string
	Err      error
}

AWSCredentialError is a credential source that applied but could not produce credentials

func (*AWSCredentialError) Error

func (e *AWSCredentialError) Error() string

func (*AWSCredentialError) PyModule

func (e *AWSCredentialError) PyModule() string

Python module of botocore's CredentialRetrievalError

func (*AWSCredentialError) Unwrap

func (e *AWSCredentialError) Unwrap() error

type AWSEventStreamException

type AWSEventStreamException struct {
	MessageType   string
	ExceptionType string
	Message       string
	Payload       []byte
	Headers       []awsEventStreamHeader
}

Exception or error frame Bedrock sends mid stream

type AWSEventStreamFrameError

type AWSEventStreamFrameError struct {
	Kind   string
	Detail string
}

Botocore parser error class of a malformed frame

func (*AWSEventStreamFrameError) Error

func (e *AWSEventStreamFrameError) Error() string

type AWSReadTimeoutError

type AWSReadTimeoutError struct {
	Endpoint string
	Limit    time.Duration
}

AWSReadTimeoutError is a socket read that waited longer than the client read timeout

func (*AWSReadTimeoutError) Error

func (e *AWSReadTimeoutError) Error() string

func (*AWSReadTimeoutError) PyModule

func (e *AWSReadTimeoutError) PyModule() string

Python module of botocore's ReadTimeoutError

func (*AWSReadTimeoutError) Temporary

func (e *AWSReadTimeoutError) Temporary() bool

func (*AWSReadTimeoutError) Timeout

func (e *AWSReadTimeoutError) Timeout() bool

type AWSServiceError

type AWSServiceError struct {
	Service    string
	Operation  string
	StatusCode int
	Code       string
	Message    string
	RequestID  string
	Body       string
	Headers    http.Header
}

AWSServiceError is an AWS API error response with its code and HTTP status

func (*AWSServiceError) Error

func (e *AWSServiceError) Error() string

func (*AWSServiceError) PyModule

func (e *AWSServiceError) PyModule() string

Python module of botocore's ClientError

func (*AWSServiceError) ResponseHeaders

func (e *AWSServiceError) ResponseHeaders() http.Header

ResponseHeaders exposes the error response headers to the classifier

type AccountUsageFetchOptions

type AccountUsageFetchOptions struct {
	BaseURL    string
	APIKey     string
	ReadOnly   bool
	IdentityID string
}

AccountUsageFetchOptions selects the credential a usage fetch reads and the cache slot it lands in

type AccountUsageRefreshRequest

type AccountUsageRefreshRequest struct {
	Provider   string
	IdentityID string
	BaseURL    string
	APIKey     string
}

AccountUsageRefreshRequest is one live credential whose usage slot a background refresh reads

type AccountUsageSnapshot

type AccountUsageSnapshot struct {
	Provider          string
	Source            string
	FetchedAt         time.Time
	Title             string
	Plan              string
	Windows           []AccountUsageWindow
	Details           []string
	UnavailableReason string
	Identity          string
	Raw               map[string]any
	UsageWindow       bool
}

AccountUsageSnapshot is one provider account usage reading for usage surfaces and the picker

func CachedAccountUsage

func CachedAccountUsage(ctx context.Context, provider, identityID, baseURL string) *AccountUsageSnapshot

CachedAccountUsage is the remembered snapshot of one usage slot, nil when none landed

func FetchAccountUsage

func FetchAccountUsage(ctx context.Context, provider string, opts AccountUsageFetchOptions) *AccountUsageSnapshot

FetchAccountUsage fetches a provider account usage snapshot and remembers it, nil on any failure

func NewAccountUsageSnapshot

func NewAccountUsageSnapshot(provider, source string, windows []AccountUsageWindow, details []string) *AccountUsageSnapshot

NewAccountUsageSnapshot stamps a snapshot fetched now with the default title

func (*AccountUsageSnapshot) Available

func (s *AccountUsageSnapshot) Available() bool

Available reports windows or details to show and no unavailable reason

type AccountUsageWindow

type AccountUsageWindow struct {
	Label       string
	UsedPercent *float64
	ResetAt     *time.Time
	Detail      string
	Scope       string
}

AccountUsageWindow is one quota window, scope account or model

type ActiveLoginSource

type ActiveLoginSource interface {
	ActiveLoggedInProvider() string
}

ActiveLoginSource names the auth store active provider when it reports logged in

type AgentImportOptions

type AgentImportOptions struct {
	Agent            string
	Source           string
	DryRun           bool
	Overwrite        bool
	Yes              bool
	ActivateRoutines bool
	MigrateSecrets   bool
	FromSetup        bool
	Bot              []string
}

AgentImportOptions are the import-agent flags of one native import run

type AgentNotice

type AgentNotice struct {
	Text  string
	Level string
	Kind  string
	TTLMs int
	Key   string
	ID    string
}

AgentNotice is an out of band notice each driver renders its own way

type AliasMatch

type AliasMatch struct {
	Provider string
	Model    string
	Alias    string
}

AliasMatch is the provider, resolved model id and alias name a short alias resolved to

func ResolveAlias

func ResolveAlias(ctx context.Context, rawInput, currentProvider string, userProviders map[string]any, customProviders []any) (*AliasMatch, error)

ResolveAlias resolves direct aliases, process provider ids and short family aliases against the provider catalog

type AmbiguousAliasError

type AmbiguousAliasError struct {
	Alias      string
	Provider   string
	Candidates []string
}

AmbiguousAliasError reports an alias matching several catalog models, candidates best guess first

func (*AmbiguousAliasError) Error

func (e *AmbiguousAliasError) Error() string

type AnthropicAuxiliaryClient

type AnthropicAuxiliaryClient struct {
	// contains filtered or unexported fields
}

OpenAI client compatible wrapper over a native Anthropic client

func NewAnthropicAuxiliaryClient

func NewAnthropicAuxiliaryClient(ctx context.Context, model string, apiKey any, baseURL string, isOAuth bool) (*AnthropicAuxiliaryClient, error)

Builds the Anthropic SDK client for the key and base URL and wraps it

func (*AnthropicAuxiliaryClient) APIKey

func (c *AnthropicAuxiliaryClient) APIKey() string

Static key, empty for a callable bearer provider

func (*AnthropicAuxiliaryClient) BaseURL

func (c *AnthropicAuxiliaryClient) BaseURL() string

func (*AnthropicAuxiliaryClient) Close

func (c *AnthropicAuxiliaryClient) Close() error

Closes the wrapped SDK client when it has one

func (*AnthropicAuxiliaryClient) CreateChatCompletion

func (c *AnthropicAuxiliaryClient) CreateChatCompletion(ctx context.Context, kwargs map[string]any) (any, error)

Runs the request through the Anthropic adapter

type AnthropicConnectionError

type AnthropicConnectionError struct{ Err error }

AnthropicConnectionError is the Anthropic SDK APIConnectionError wrapping a request that never got a response

func (*AnthropicConnectionError) Error

func (e *AnthropicConnectionError) Error() string

func (*AnthropicConnectionError) Unwrap

func (e *AnthropicConnectionError) Unwrap() error

type AnthropicOAuthError

type AnthropicOAuthError struct {
	Status      int
	Code        string
	Description string
	What        string
}

AnthropicOAuthError is a token endpoint rejection carrying the OAuth error code

func (*AnthropicOAuthError) Error

func (e *AnthropicOAuthError) Error() string

func (*AnthropicOAuthError) ReloginRequired

func (e *AnthropicOAuthError) ReloginRequired() bool

ReloginRequired is a 400 or 401 whose code says the grant is dead

type AnthropicStreamAccumulator

type AnthropicStreamAccumulator struct {
	// contains filtered or unexported fields
}

Rebuilds an Anthropic Message from post intercept SSE events

func NewAnthropicStreamAccumulator

func NewAnthropicStreamAccumulator() *AnthropicStreamAccumulator

func (*AnthropicStreamAccumulator) Finalize

func (a *AnthropicStreamAccumulator) Finalize() map[string]any

Message dict with content blocks in index order and partial tool JSON parsed into input

func (*AnthropicStreamAccumulator) Observe

func (a *AnthropicStreamAccumulator) Observe(event any) error

Feeds one stream event into the message being rebuilt

func (*AnthropicStreamAccumulator) Response

func (a *AnthropicStreamAccumulator) Response(base any) any

Attribute shaped response merged over base

type AppliedVar

type AppliedVar struct {
	Name          string
	Source        string
	Shape         string
	OverrodeEnv   bool
	Authoritative bool
}

AppliedVar is the provenance record for one env var the orchestrator set

type ApplyReport

type ApplyReport struct {
	Sources    []*SourceReport
	Provenance map[string]AppliedVar
	Conflicts  []string
}

ApplyReport is the merged outcome of one orchestrated apply pass

func ApplyAllSecretSources

func ApplyAllSecretSources(secretsCfg map[string]any, homePath string, environ *SourceEnvironment) (*ApplyReport, error)

ApplyAllSecretSources fetches from every enabled source and applies the merged result to the environment

func (*ApplyReport) AppliedAny

func (r *ApplyReport) AppliedAny() bool

AppliedAny reports whether any var was set

type AssetFile

type AssetFile struct {
	Path      string
	SizeBytes int64
	Local     string
	Repo      string
	Revision  string
}

One downloadable file with its repo relative path, exact size, local name override and source repo

func (AssetFile) LocalName

func (a AssetFile) LocalName() string

On disk name, the override when set or the final path component

type AsyncAnthropicAuxiliaryClient

type AsyncAnthropicAuxiliaryClient struct {
	// contains filtered or unexported fields
}

Async twin of the Anthropic auxiliary client

func NewAsyncAnthropicAuxiliaryClient

func NewAsyncAnthropicAuxiliaryClient(sync *AnthropicAuxiliaryClient) *AsyncAnthropicAuxiliaryClient

Wraps a sync Anthropic client for async callers

func (*AsyncAnthropicAuxiliaryClient) APIKey

func (c *AsyncAnthropicAuxiliaryClient) APIKey() string

func (*AsyncAnthropicAuxiliaryClient) BaseURL

func (c *AsyncAnthropicAuxiliaryClient) BaseURL() string

func (*AsyncAnthropicAuxiliaryClient) Close

func (c *AsyncAnthropicAuxiliaryClient) Close() error

The async wrapper owns no transport so closing it releases nothing

func (*AsyncAnthropicAuxiliaryClient) CreateChatCompletion

func (c *AsyncAnthropicAuxiliaryClient) CreateChatCompletion(ctx context.Context, kwargs map[string]any) (any, error)

Runs the sync adapter body

type AsyncBedrockAuxiliaryClient

type AsyncBedrockAuxiliaryClient struct {
	// contains filtered or unexported fields
}

Async twin of the Bedrock auxiliary client

func NewAsyncBedrockAuxiliaryClient

func NewAsyncBedrockAuxiliaryClient(sync *BedrockAuxiliaryClient) *AsyncBedrockAuxiliaryClient

Wraps a sync Bedrock client for async callers

func (*AsyncBedrockAuxiliaryClient) APIKey

func (c *AsyncBedrockAuxiliaryClient) APIKey() string

func (*AsyncBedrockAuxiliaryClient) BaseURL

func (c *AsyncBedrockAuxiliaryClient) BaseURL() string

func (*AsyncBedrockAuxiliaryClient) Close

func (c *AsyncBedrockAuxiliaryClient) Close() error

The async wrapper owns no transport so closing it releases nothing

func (*AsyncBedrockAuxiliaryClient) CreateChatCompletion

func (c *AsyncBedrockAuxiliaryClient) CreateChatCompletion(ctx context.Context, kwargs map[string]any) (any, error)

Runs the sync adapter body

type AsyncCodexAuxiliaryClient

type AsyncCodexAuxiliaryClient struct {
	// contains filtered or unexported fields
}

Async twin of the Codex auxiliary client

func NewAsyncCodexAuxiliaryClient

func NewAsyncCodexAuxiliaryClient(sync *CodexAuxiliaryClient) *AsyncCodexAuxiliaryClient

Wraps a sync Codex client for async callers

func (*AsyncCodexAuxiliaryClient) APIKey

func (c *AsyncCodexAuxiliaryClient) APIKey() string

func (*AsyncCodexAuxiliaryClient) BaseURL

func (c *AsyncCodexAuxiliaryClient) BaseURL() string

func (*AsyncCodexAuxiliaryClient) Close

func (c *AsyncCodexAuxiliaryClient) Close() error

The async wrapper owns no transport so closing it releases nothing

func (*AsyncCodexAuxiliaryClient) CreateChatCompletion

func (c *AsyncCodexAuxiliaryClient) CreateChatCompletion(ctx context.Context, kwargs map[string]any) (any, error)

Runs the sync adapter body

type AuthData

type AuthData map[string]any

AuthData is the parsed auth.json document in its exact on disk schema

type AuthEpisode

type AuthEpisode struct {
	Refreshes int
	Last      time.Time
}

AuthEpisode is the per turn auth failure state for one pool entry

type AuthError

type AuthError struct {
	Message         string
	Provider        string
	Code            string
	ReloginRequired bool
	RetryAfter      time.Duration
	HasRetryAfter   bool
	Retryable       *bool
	Err             error
}

AuthError is a structured credential failure carrying relogin and retry hints

func (*AuthError) Error

func (e *AuthError) Error() string

func (*AuthError) Unwrap

func (e *AuthError) Unwrap() error

type AuthExitError

type AuthExitError struct {
	Code    int
	Message string
}

AuthExitError is the SystemExit an auth subcommand raises, a message exits 1 and a bare code exits with it

func (*AuthExitError) Error

func (e *AuthExitError) Error() string

type AuthKind

type AuthKind string

Credential style a route authenticates with

const (
	AuthNone     AuthKind = "none"
	AuthAPIKey   AuthKind = "api_key"
	AuthOAuth    AuthKind = "oauth"
	AuthAWSSigV4 AuthKind = "aws_sigv4"
	AuthGCPOAuth AuthKind = "gcp_oauth"
)

func AuthKindOf

func AuthKindOf(authType string) AuthKind

Maps an auth_type literal onto the route credential style

type AuthRecoveryAgent

type AuthRecoveryAgent interface {
	Provider() string
	APIMode() APIMode
	// Adopts the entry as the live credential, false when its route cannot serve the model
	SwapCredential(entry PooledCredential) bool
	AuthEpisodes() map[string]*AuthEpisode
}

AuthRecoveryAgent is the live session the credential recovery acts on

type AuthRecoveryRequest

type AuthRecoveryRequest struct {
	StatusCode    int
	HasRetried429 bool
	ErrorContext  map[string]any
	APIKeyHint    string
	CredentialID  string
	// Rotates away from the failed credential, true when a new entry was swapped in
	RotateAndSwap func(defaultStatus int, label string) bool
}

AuthRecoveryRequest carries the failed request identity into the recovery

type AuthenticatedProvidersOptions

type AuthenticatedProvidersOptions struct {
	CurrentProvider            string
	CurrentBaseURL             string
	CurrentModel               string
	UserProviders              map[string]any
	CustomProviders            []any
	MaxModels                  *int
	Refresh                    bool
	SkipCustomProviderProbe    bool
	ProbeCurrentCustomProvider bool
	ForPicker                  bool
	ExcludedProviders          []string
	NonBlockingCatalogs        bool
	FastCustomProbe            *bool
}

AuthenticatedProvidersOptions mirrors the list_authenticated_providers keyword arguments

type AuthoritativeAuxiliaryTask

type AuthoritativeAuxiliaryTask string

AuthoritativeAuxiliaryTask is a task name whose config keeps its policy but drops every route field

func NewAuthoritativeAuxiliaryTask

func NewAuthoritativeAuxiliaryTask(task any) AuthoritativeAuxiliaryTask

NewAuthoritativeAuxiliaryTask returns the task as route authoritative, an absent task becoming the empty name

func (AuthoritativeAuxiliaryTask) RouteAuthoritative

func (AuthoritativeAuxiliaryTask) RouteAuthoritative() bool

RouteAuthoritative marks the task as naming a complete route of its own

type AuxAdapter

type AuxAdapter struct{}

AuxAdapter serves tools.Aux and the MCP sampling chat surface through CallLLM

func (AuxAdapter) Complete

func (AuxAdapter) Complete(ctx context.Context, messages []*state.Message, opts tools.AuxOptions) (string, error)

Complete runs one auxiliary completion of transcript messages and returns its text

func (AuxAdapter) CompleteChat

func (AuxAdapter) CompleteChat(ctx context.Context, messages []map[string]any, toolDefs []map[string]any, opts tools.AuxOptions) (map[string]any, error)

CompleteChat runs one auxiliary chat completion forwarding tool definitions and returns the completion dict

func (AuxAdapter) ResolvesVision

func (AuxAdapter) ResolvesVision(ctx context.Context, provider string) (bool, error)

Whether the vision task resolves a client for the provider in probe mode, the check_video_requirements probe

type AuxCallHookArgs

type AuxCallHookArgs = auxCallHookArgs

AuxCallHookArgs exposes the auxiliary hook arguments

type AuxCallHooks

type AuxCallHooks = auxCallHooks

AuxCallHooks exposes the hook pair of one auxiliary attempt

func StartAuxCallHooks

func StartAuxCallHooks(ctx context.Context, a AuxCallHookArgs) *AuxCallHooks

StartAuxCallHooks fires pre_auxiliary_call for one side call attempt

type AuxCancelCheck

type AuxCancelCheck interface {
	CancelRequested() (bool, error)
}

AuxCancelCheck is an explicit host cancel source polled by protected auxiliary calls

func CaptureAuxCancelCheck

func CaptureAuxCancelCheck(ctx context.Context) AuxCancelCheck

Captures the auxiliary cancel check bound to the calling scope

type AuxCancelEvent

type AuxCancelEvent interface {
	IsSet() bool
}

AuxCancelEvent is a host event whose set state means an explicit cancel

type AuxCancelFunc

type AuxCancelFunc func() (bool, error)

AuxCancelFunc adapts a plain function into a cancel source

func (AuxCancelFunc) CancelRequested

func (f AuxCancelFunc) CancelRequested() (bool, error)

CancelRequested runs the function

type AuxChatStream

type AuxChatStream interface {
	Next(ctx context.Context) (map[string]any, error)
	Close() error
}

AuxChatStream yields OpenAI shaped chunks until io.EOF

type AuxClient

type AuxClient interface {
	BaseURL() string
	APIKey() string
	CreateChatCompletion(ctx context.Context, kwargs map[string]any) (any, error)
	Close() error
}

AuxClient is one resolved auxiliary chat client, the OpenAI SDK client or a wire adapter

func GetTextAuxiliaryClient

func GetTextAuxiliaryClient(ctx context.Context, task string, mainRuntime map[string]any) (AuxClient, string, error)

GetTextAuxiliaryClient is the client and model for a text auxiliary task under its auxiliary.<task> overrides

func NewOpenAIClient

func NewOpenAIClient(apiKey any, baseURL string, opts OpenAIClientOptions) AuxClient

NewOpenAIClient is the OpenAI SDK client with a static or callable key, the env key and base URL when none is given

func ResolveProviderClient

func ResolveProviderClient(ctx context.Context, provider, model string, opts ProviderClientOptions) (AuxClient, string, error)

ResolveProviderClient builds the configured client and model for a provider, nil and empty when unavailable

func ResolveVisionProviderClient

func ResolveVisionProviderClient(ctx context.Context, provider, model, baseURL string, apiKey any, asyncMode bool, mainRuntime map[string]any) (string, AuxClient, string, error)

ResolveVisionProviderClient resolves the provider, client and model vision tasks use, empty provider and model for None

func TryConfiguredFallbackForUnavailableClient

func TryConfiguredFallbackForUnavailableClient(ctx context.Context, task, failedProvider string) (AuxClient, string, string, error)

Task fallback chain client, model and label for an explicit provider that cannot build a client

type AuxHookLocal

type AuxHookLocal int

AuxHookLocal names one of the per call auxiliary timing hooks

const (
	// AuxProgressLocal is the forward progress hook
	AuxProgressLocal AuxHookLocal = iota
	// AuxDispatchLocal records an actual provider dispatch
	AuxDispatchLocal
	// AuxProviderResponseLocal records any provider frame including content free ones
	AuxProviderResponseLocal
)

type AuxNormalizedReply

type AuxNormalizedReply = auxNormalizedReply

AuxNormalizedReply exposes the normalized auxiliary reply

type AuxPickerEntry

type AuxPickerEntry struct {
	Slug   string
	Label  string
	Models []string
}

AuxPickerEntry is one rendered auxiliary picker row

func FormatAuxPickerEntries

func FormatAuxPickerEntries(rows []map[string]any, currentProvider, currentBaseURL string) []AuxPickerEntry

FormatAuxPickerEntries renders rows as slug, label with model count and current marker, and models

type AuxReplyFault

type AuxReplyFault int

Way an auxiliary completion was unusable

const (
	// The provider returned no response object
	AuxReplyMissing AuxReplyFault = iota + 1
	// The response holds no choices[0].message
	AuxReplyMalformed
)

type AuxRuntimeError

type AuxRuntimeError struct {
	Message       string
	ProviderError map[string]any
	// Fault of the completion the error reports, zero for other failures
	Fault AuxReplyFault
}

AuxRuntimeError is a Python RuntimeError raised by the auxiliary client, carrying an HTTP 200 provider error object

func (*AuxRuntimeError) Error

func (e *AuxRuntimeError) Error() string

func (*AuxRuntimeError) PyRuntimeError

func (e *AuxRuntimeError) PyRuntimeError()

Marks the error as a Python RuntimeError for callers that branch on the exception class

type AuxSDKError

type AuxSDKError struct {
	StatusCode int
	Body       any
	Headers    http.Header
	Message    string
	Code       string
	Type       string
	Class      string
	Err        error
	// Raw response body text the way httpx response.text reads it, empty without a response
	ResponseText string
}

AuxSDKError is the OpenAI SDK APIError shape an auxiliary SDK client raises, status zero when status less

func (*AuxSDKError) Error

func (e *AuxSDKError) Error() string

func (*AuxSDKError) PyExceptionMRO

func (e *AuxSDKError) PyExceptionMRO() []string

Class names of the SDK exception through BaseException as type(exc).__mro__ lists them

func (*AuxSDKError) PyModule

func (e *AuxSDKError) PyModule() string

Python module of the SDK exception classes

func (*AuxSDKError) PyTypeName

func (e *AuxSDKError) PyTypeName() string

Python exception class the SDK raised, APIError when unclassified

func (*AuxSDKError) ResponseHeaders

func (e *AuxSDKError) ResponseHeaders() http.Header

Headers of the failed response, nil without a response

func (*AuxSDKError) Unwrap

func (e *AuxSDKError) Unwrap() error

type AuxStreamDeadlineFunc

type AuxStreamDeadlineFunc func() (time.Time, bool)

AuxStreamDeadlineFunc reads the waiting host's absolute deadline live, false when none applies

type AuxTimeoutError

type AuxTimeoutError struct {
	Message string
	Err     error
	// What ran out of time, zero for a full budget or deadline timeout
	Kind AuxTimeoutKind
	// Raised by the chat stream watchdog
	Watchdog bool
}

AuxTimeoutError is the Python TimeoutError an auxiliary stream raises when its progress window lapses

func (*AuxTimeoutError) Error

func (e *AuxTimeoutError) Error() string

func (*AuxTimeoutError) Unwrap

func (e *AuxTimeoutError) Unwrap() error

type AuxTimeoutKind

type AuxTimeoutKind int

What ran out of time in an auxiliary stream

const (
	// The stream produced no output within its first output window
	AuxTimeoutNoOutput AuxTimeoutKind = iota + 1
	// Output stopped after the stream had started
	AuxTimeoutStalled
)

type AuxTransportError

type AuxTransportError struct {
	Class   string
	Message string
	Err     error
	Doc     string
	Request *FailedStreamRequest
}

AuxTransportError is an httpx transport failure raised while a streamed response is consumed

func (*AuxTransportError) Error

func (e *AuxTransportError) Error() string

func (*AuxTransportError) FailedRequest

func (e *AuxTransportError) FailedRequest() *FailedStreamRequest

func (*AuxTransportError) PyExceptionMRO

func (e *AuxTransportError) PyExceptionMRO() []string

Class names of the httpx transport exception through BaseException as type(exc).__mro__ lists them

func (*AuxTransportError) PyModule

func (e *AuxTransportError) PyModule() string

Python module of the raised class, json.decoder for a JSONDecodeError and httpx for every transport class

func (*AuxTransportError) PyTypeName

func (e *AuxTransportError) PyTypeName() string

func (*AuxTransportError) Timeout

func (e *AuxTransportError) Timeout() bool

func (*AuxTransportError) Unwrap

func (e *AuxTransportError) Unwrap() error

type AuxUsageRecorder

type AuxUsageRecorder interface {
	RecordAuxiliaryUsage(ctx context.Context, sessionID, task string, usage AuxiliaryUsage) error
}

AuxUsageRecorder is the session store that keeps auxiliary usage rows per session and task

type AuxiliaryClientUnavailable

type AuxiliaryClientUnavailable struct {
	Message string
	// No provider is configured at all, as opposed to one lacking credentials
	NoProvider bool
}

AuxiliaryClientUnavailable reports that no auxiliary client could be built for the task

func (*AuxiliaryClientUnavailable) Error

type AuxiliaryExplicitCancellation

type AuxiliaryExplicitCancellation struct{}

AuxiliaryExplicitCancellation is the host hard cancel of one auxiliary attempt, never a transport failure

func (*AuxiliaryExplicitCancellation) Cause

Cause names the explicit host cancel so nothing re-queries a mutable host event after unwinding

func (*AuxiliaryExplicitCancellation) Error

type AuxiliaryUsage

type AuxiliaryUsage struct {
	Model            string
	BillingProvider  string
	BillingBaseURL   string
	InputTokens      int
	OutputTokens     int
	CacheReadTokens  int
	CacheWriteTokens int
	ReasoningTokens  int
	EstimatedCostUSD *float64
}

AuxiliaryUsage is one auxiliary call's token and cost row for a session's usage ledger

type AvailabilityProvider

type AvailabilityProvider = providerregistry.AvailabilityProvider

Provider whose availability probe is_available_safe guards

type AvailableProvider

type AvailableProvider struct {
	ID            string
	Label         string
	Aliases       []string
	Authenticated bool
}

AvailableProvider is one row of the provider list shared by icebath model and the model command

func ListAvailableProviders

func ListAvailableProviders(ctx context.Context) []AvailableProvider

ListAvailableProviders returns id, label, aliases and credential presence per listed provider plus custom

type AzureDetection

type AzureDetection struct {
	APIMode       APIMode
	Models        []string
	Hostname      string
	Reason        string
	ModelsProbeOK bool
	IsAnthropic   bool
}

AzureDetection is everything auto detection could gather from a base URL and credential

func DetectAzureEndpoint

func DetectAzureEndpoint(ctx context.Context, baseURL, apiKey string, tokenProvider func(context.Context) (string, error)) AzureDetection

DetectAzureEndpoint runs auto detection with the default client

type AzureDetector

type AzureDetector struct {
	Client    *http.Client
	UserAgent string
}

AzureDetector probes an Azure endpoint for its transport and model list

func (*AzureDetector) Detect

func (d *AzureDetector) Detect(ctx context.Context, baseURL, apiKey string, tokenProvider func(context.Context) (string, error)) AzureDetection

Detect inspects an Azure endpoint and describes its transport and models, advisory when api mode stays empty

type BackendIdentity

type BackendIdentity struct {
	Provider string
	Model    string
	BaseURL  string
}

BackendIdentity is the normalized provider, model, and endpoint of one deployment with empty meaning unknown

func BuildBackendIdentity

func BuildBackendIdentity(provider, model, baseURL string) BackendIdentity

BuildBackendIdentity normalizes the three axes of a candidate route

func FallbackEntryIdentity

func FallbackEntryIdentity(entry map[string]any) BackendIdentity

FallbackEntryIdentity builds the backend identity of a provider, model and base_url chain entry

type BackoffOptions

type BackoffOptions struct {
	BaseDelay   time.Duration
	MaxDelay    time.Duration
	JitterRatio float64
}

BackoffOptions tunes the exponential schedule and its jitter ratio

type BearerValueError

type BearerValueError struct{ Message string }

BearerValueError is an unusable key or an empty mint, the one failure the bearer hook sends without auth

func (*BearerValueError) Error

func (e *BearerValueError) Error() string

type BedrockAuxiliaryClient

type BedrockAuxiliaryClient struct {
	// contains filtered or unexported fields
}

OpenAI client compatible wrapper over the Bedrock Converse API

func NewBedrockAuxiliaryClient

func NewBedrockAuxiliaryClient(region, model string) *BedrockAuxiliaryClient

Wraps Converse for the region and model

func (*BedrockAuxiliaryClient) APIKey

func (c *BedrockAuxiliaryClient) APIKey() string

func (*BedrockAuxiliaryClient) BaseURL

func (c *BedrockAuxiliaryClient) BaseURL() string

func (*BedrockAuxiliaryClient) Close

func (c *BedrockAuxiliaryClient) Close() error

Converse holds no client side transport so closing releases nothing

func (*BedrockAuxiliaryClient) CreateChatCompletion

func (c *BedrockAuxiliaryClient) CreateChatCompletion(ctx context.Context, kwargs map[string]any) (any, error)

Runs the request through the Converse adapter

type BedrockBinding

type BedrockBinding struct {
	Region          string
	GuardrailConfig map[string]any
	APIKey          string
	BaseURL         string
	IsOAuth         bool
	Client          Client
}

BedrockBinding is the agent state one Bedrock wire binds, the aws-sdk sentinel never a credential

func BindBedrockRuntime

func BindBedrockRuntime(ctx context.Context, baseURL string, mode APIMode, model string) (*BedrockBinding, error)

BindBedrockRuntime points an agent at a non Mantle Bedrock wire, building the Messages client for Claude

type BedrockModel

type BedrockModel struct {
	ID               string
	Name             string
	Provider         string
	InputModalities  []string
	OutputModalities []string
	Streaming        bool
}

BedrockModel is one discovered foundation model or inference profile

func DiscoverBedrockModels

func DiscoverBedrockModels(ctx context.Context, region string, providerFilter []string) []BedrockModel

DiscoverBedrockModels lists foundation models and inference profiles, cached an hour per region and filter

type BedrockOpenAINoCredentialsError

type BedrockOpenAINoCredentialsError struct{ Err error }

BedrockOpenAINoCredentialsError is a Mantle call with neither a key nor resolvable AWS credentials

func (*BedrockOpenAINoCredentialsError) Error

func (*BedrockOpenAINoCredentialsError) Unwrap

type BedrockScopedCredentialError

type BedrockScopedCredentialError struct{}

BedrockScopedCredentialError refuses a multiplexed profile that would borrow the launch identity

func (BedrockScopedCredentialError) Error

type BillingBlock

type BillingBlock struct {
	Provider      string
	ProviderLabel string
	Model         string
	BillingURL    string
	Message       string
}

BillingBlock is the structured billing wall descriptor every surface renders

func BuildBillingBlock

func BuildBillingBlock(provider, baseURL, model, message string) BillingBlock

BuildBillingBlock describes a billing classified failure with the provider add credits page

func BuildBillingBlockErr

func BuildBillingBlockErr(provider, baseURL, model, message string) (BillingBlock, error)

BuildBillingBlockErr describes a billing classified failure, the urlparse ValueError of a malformed base url returned

func (BillingBlock) ToDict

func (b BillingBlock) ToDict() map[string]any

ToDict is the wire form of the billing block with a null url when none is known

type BillingRoute

type BillingRoute struct {
	Provider    string
	Model       string
	BaseURL     string
	BillingMode string
}

BillingRoute names the pricing source a model request is billed through

func ResolveBillingRoute

func ResolveBillingRoute(modelName, provider, baseURL string) BillingRoute

ResolveBillingRoute maps a model, provider and base URL onto the pricing source that bills it

type BinaryResolutionError

type BinaryResolutionError struct{ Message string }

BinaryResolutionError means the requested backend has no pinned or installed engine

func (*BinaryResolutionError) Error

func (e *BinaryResolutionError) Error() string

type BitwardenFetchOptions

type BitwardenFetchOptions struct {
	AccessToken            string
	ProjectID              string
	Binary                 string
	CacheTTL               float64
	UseCache               bool
	ServerURL              string
	HomePath               string
	EncryptedCacheEnabled  bool
	EncryptedCacheMaxStale float64
	Environ                *SourceEnvironment
	InstallBinaryIfMissing bool
}

BitwardenFetchOptions parameterize one pull of a BSM project

type BitwardenSource

type BitwardenSource struct{}

BitwardenSource is Bitwarden Secrets Manager as a bulk source

func (*BitwardenSource) ConfigSchema

func (s *BitwardenSource) ConfigSchema() map[string]map[string]any

func (*BitwardenSource) Fetch

func (s *BitwardenSource) Fetch(cfg map[string]any, homePath string, environ *SourceEnvironment) *SecretFetchResult

func (*BitwardenSource) Spec

type BoundedResult

type BoundedResult = pydeadline.Result

BoundedResult is the outcome of a bounded operation, operation errors never land here

func RunBounded

func RunBounded(ctx context.Context, fn func(ctx context.Context) (any, error), timeout time.Duration, bounded bool, label string, onTimeout func(), backend any) (BoundedResult, error)

RunBounded runs fn on a worker keeping the caller context values, abandoning the worker uncancelled on expiry

func RunBoundedAsync

func RunBoundedAsync(ctx context.Context, fn func(ctx context.Context) (any, error), timeout time.Duration, bounded bool, label string, onAbandon func(ctx context.Context) error, dumpOnBlockedLoop bool, backend any) (BoundedResult, error)

RunBoundedAsync runs fn under a timer driven deadline, cancelling and abandoning it on expiry or caller cancellation

type CLIResult

type CLIResult struct {
	Stdout     string
	Stderr     string
	ReturnCode int
}

CLIResult is a completed helper process

func RunCLI

func RunCLI(argv []string, env map[string]string, timeout time.Duration, label, timeoutMessage string, stdin *os.File) (CLIResult, error)

RunCLI runs an argv list with a captured utf-8 result, timeout and spawn failure become errors

type CacheDestination

type CacheDestination struct {
	Provider, BaseURL, APIMode, Model *string
}

CacheDestination overrides agent fields per call, a nil field reads the agent value

type CachePolicyAgent

type CachePolicyAgent struct {
	Provider        string
	BaseURL         string
	APIMode         string
	Model           any
	CacheDisabled   bool
	CustomProviders []map[string]any
}

CachePolicyAgent is the agent state the cache policy falls back to, nil CustomProviders means none attached yet

func BlankCachePolicyAgent

func BlankCachePolicyAgent(ctx context.Context, cacheDisabled *bool) *CachePolicyAgent

BlankCachePolicyAgent is the identity blank policy agent, a nil disable flag reads the bound config

type CacheScopeAgent

type CacheScopeAgent struct {
	SessionID           string
	SessionDB           any
	GatewaySessionKey   string
	PersistDisabled     bool
	InheritedCacheScope string
	Platform            string
	Env                 *tools.Env
	PromptCacheForkTag  string
	CompressionCount    func() int
	Provider            string
	Model               string
	BaseURL             string
	// contains filtered or unexported fields
}

CacheScopeAgent carries the agent state the prompt cache scope resolution reads and memoizes

type CacheScopeSessionStore

type CacheScopeSessionStore struct{ DB CacheScopeStore }

CacheScopeSessionStore is the session store view the resolver reads, each lookup bound to a background context

func (CacheScopeSessionStore) DeclaredScopeIdentity

func (c CacheScopeSessionStore) DeclaredScopeIdentity(sessionID string) (bool, string, error)

func (CacheScopeSessionStore) GetCompressionLineage

func (c CacheScopeSessionStore) GetCompressionLineage(sessionID string) ([]string, error)

func (CacheScopeSessionStore) GetSession

func (c CacheScopeSessionStore) GetSession(ctx context.Context, sessionID string) (*pyjson.Object, error)

func (CacheScopeSessionStore) IsExplicitForkChild

func (c CacheScopeSessionStore) IsExplicitForkChild(sessionID string) (bool, error)

func (CacheScopeSessionStore) LatestConversationBoundary

func (c CacheScopeSessionStore) LatestConversationBoundary(sessionKey, source string) (int64, bool, error)

type CacheScopeStore

type CacheScopeStore interface {
	GetCompressionLineage(ctx context.Context, sessionID string) ([]string, error)
	GetSession(ctx context.Context, sessionID string) (*pyjson.Object, error)
	IsExplicitForkChild(ctx context.Context, sessionID string) (bool, error)
	DeclaredScopeIdentity(ctx context.Context, sessionID string) (bool, string, error)
	LatestConversationBoundary(ctx context.Context, sessionKey, source string) (int64, bool, error)
}

Session store methods the prompt cache scope reads, as the state package exposes them with a context

type CachedFetch

type CachedFetch struct {
	Secrets   map[string]string
	FetchedAt float64
}

CachedFetch is a set of fetched secret values plus when they were fetched

func CachedFetchFromPayload

func CachedFetchFromPayload(payload any) (CachedFetch, bool)

CachedFetchFromPayload decodes a secrets and fetched_at object, only string pairs survive

func (CachedFetch) IsFresh

func (c CachedFetch) IsFresh(ttl float64) bool

IsFresh reports the entry is younger than the TTL

type CachedFetchOptions

type CachedFetchOptions struct {
	APIKey       any
	BaseURL      string
	Timeout      time.Duration
	APIMode      string
	Headers      map[string]string
	ForceRefresh bool
	CacheOnly    bool
	// Native aware discovery supplying the rows without minting a token before cache admission
	FetchModels func() (CatalogRows, bool)
	TTL         time.Duration
}

CachedFetchOptions tune one disk cached custom endpoint listing

type CachedModelsOptions

type CachedModelsOptions struct {
	ForceRefresh bool
	TTL          time.Duration
	NonBlocking  bool
}

CachedModelsOptions tune one disk cached catalog read

type CanonicalProviderEntry

type CanonicalProviderEntry struct {
	Slug    string
	Label   string
	TUIDesc string
}

One row of the model picker universe

func CanonicalProviders

func CanonicalProviders() []CanonicalProviderEntry

CanonicalProviders returns the full row table including hidden plugin profiles

type CanonicalUsage

type CanonicalUsage struct {
	InputTokens      int
	OutputTokens     int
	CacheReadTokens  int
	CacheWriteTokens int
	ReasoningTokens  int
	RequestCount     int
	RawUsage         map[string]any
}

CanonicalUsage is the provider neutral token bucket view of one or more responses

func NewCanonicalUsage

func NewCanonicalUsage() CanonicalUsage

NewCanonicalUsage returns the empty bucket counting one request

func NormalizeUsage

func NormalizeUsage(responseUsage any, provider, apiMode string) CanonicalUsage

NormalizeUsage turns a raw API usage payload into canonical token buckets by wire shape

func WithServedServiceTier

func WithServedServiceTier(usage CanonicalUsage, serviceTier string) CanonicalUsage

WithServedServiceTier folds the response level OpenAI service tier into the raw usage

func (CanonicalUsage) Add

Add sums two buckets, dropping raw usage and adding request counts

func (CanonicalUsage) PromptTokens

func (u CanonicalUsage) PromptTokens() int

PromptTokens is uncached input plus both cache buckets

func (CanonicalUsage) TotalTokens

func (u CanonicalUsage) TotalTokens() int

TotalTokens is prompt plus output

type CatalogConfig

type CatalogConfig struct {
	Enabled   bool
	URL       string
	TTLHours  float64
	Providers map[string]any
}

CatalogConfig is the model_catalog config block with defaults filled in

func ParseCatalogConfig

func ParseCatalogConfig(raw map[string]any) CatalogConfig

Parses a model_catalog block, legacy ttl_hours honoured only while ttl_minutes sits at its default

type CatalogEntry

type CatalogEntry struct {
	ID, DisplayName, Description, Repo string
	Variants                           []QuantVariant
	NCtxTrain, FullLayers              int
	RecurrentLayers                    int
	PerLayerF16                        int64
	SWALayers, SWAWindow               int
	MoE, MTP                           bool
	MTPDraftDepth                      int
	NVocab                             int64
	Architecture                       string
	MMProj, Draft, MTPHead             *AssetFile
	DraftSpecType                      string
	DraftDepth                         int
	DraftMinEngine                     string
	Sampling                           []CatalogSetting
	MinEngine                          string
	Quality                            int
	DecodeFraction                     float64
	Recommend                          bool
}

One curated model family with the estimator inputs that price it before download

func Catalog

func Catalog() []CatalogEntry

Running catalog, the packaged document until a refresh swaps in a fetched one

func EntryForModel

func EntryForModel(modelID string) *CatalogEntry

Entry owning a staged model id, nil when none does

func RecommendedEntry

func RecommendedEntry(budget HardwareBudget, entries []CatalogEntry, backend string) (*CatalogEntry, string)

Default pick for this machine with its reason key, nil when nothing resident clears the pleasant floor

func (CatalogEntry) CompanionBytes

func (e CatalogEntry) CompanionBytes() int64

Bytes of the vision projector and MTP head loaded beside the weights

func (CatalogEntry) DownloadBytes

func (e CatalogEntry) DownloadBytes(v QuantVariant) int64

func (CatalogEntry) DownloadFiles

func (e CatalogEntry) DownloadFiles(v QuantVariant) []AssetFile

Variant files then projector, draft and MTP head in the order a download job fetches them

func (CatalogEntry) InstallFiles

func (e CatalogEntry) InstallFiles(v QuantVariant) []AssetFile

Files a variant needs to count as downloaded, the optional draft excluded

func (CatalogEntry) LaunchPlan

func (e CatalogEntry) LaunchPlan(v QuantVariant, budget HardwareBudget) LaunchPlan

Launch plan of a variant on this budget with companions priced as fixed overhead

func (CatalogEntry) MTPCapable

func (e CatalogEntry) MTPCapable() bool

MTP spec decode runs from heads built into the model or shipped beside it

func (CatalogEntry) Profile

func (e CatalogEntry) Profile(v QuantVariant) ModelProfile

Estimator profile of a variant from the catalog's measured layer facts

type CatalogModel

type CatalogModel struct {
	ID          string
	Description string
}

CatalogModel is one picker row as model id plus the description shown in menus

func CuratedOpenRouterModels

func CuratedOpenRouterModels(ctx context.Context) []CatalogModel

CuratedOpenRouterModels returns OpenRouter's curated rows from the manifest, nil when it has none

func FetchAIGatewayModels

func FetchAIGatewayModels(ctx context.Context, timeout time.Duration, forceRefresh bool) []CatalogModel

FetchAIGatewayModels returns the curated AI Gateway picker list refreshed from the live catalog when possible

func FetchOpenRouterModels

func FetchOpenRouterModels(ctx context.Context, opts FetchModelsOptions) []CatalogModel

FetchOpenRouterModels returns the curated OpenRouter picker list refreshed from the live catalog when possible

type CatalogProviderBase

type CatalogProviderBase interface {
	ProviderBase
	IsAvailable() bool
	ListModels() []map[string]any
	DefaultModel() string
}

Provider with a model catalog that is available by default and shows a title cased label

type CatalogProviderDefaults

type CatalogProviderDefaults struct {
	Self CatalogProviderBase
}

Embeddable CatalogProviderBase defaults dispatching through Self, the outer provider that supplies Name

func (CatalogProviderDefaults) DefaultModel

func (d CatalogProviderDefaults) DefaultModel() string

Id of the first catalog entry, empty when the catalog is empty or the entry has no string id

func (CatalogProviderDefaults) DisplayName

func (d CatalogProviderDefaults) DisplayName() string

Label shown in icebath tools, the provider name title cased

func (CatalogProviderDefaults) GetSetupSchema

func (d CatalogProviderDefaults) GetSetupSchema() map[string]any

Picker row naming the provider by its display name with no badge, tag or env vars

func (CatalogProviderDefaults) IsAvailable

func (CatalogProviderDefaults) IsAvailable() bool

Provider can service calls, true unless overridden

func (CatalogProviderDefaults) ListModels

func (CatalogProviderDefaults) ListModels() []map[string]any

Model catalog entries, empty unless overridden

type CatalogRows

type CatalogRows struct {
	IDs      []string
	Fallback bool
	Native   bool
}

CatalogRows is one provider catalog answer, Fallback marks a curated outage placeholder, Native a local server listing

func CachedFetchAPIModels

func CachedFetchAPIModels(ctx context.Context, opts CachedFetchOptions) (CatalogRows, bool)

CachedFetchAPIModels is the disk cached custom endpoint listing keyed by URL and credential fingerprint

func FetchPickerLiveModels

func FetchPickerLiveModels(ctx context.Context, apiKey any, apiURL, nativeProvider string, preserveNative bool, headers map[string]string, timeout time.Duration, apiMode string) (CatalogRows, bool)

Cached picker fetch of an endpoint's live models, Native set for an Ollama native catalog, false when unavailable

func MergeProfileCatalog

func MergeProfileCatalog(ctx context.Context, normalized string, profile Profile, live []string) (CatalogRows, bool)

MergeProfileCatalog combines a live catalog with the curated list the way the model picker does

func ProbeProfileCatalog

func ProbeProfileCatalog(ctx context.Context, normalized string, profile Profile, apiKey, baseURL string) (CatalogRows, bool)

ProbeProfileCatalog fetches a profile's live list only with a key and merges it with the curated row

func ProviderModelIDs

func ProviderModelIDs(ctx context.Context, provider string, forceRefresh bool) CatalogRows

ProviderModelIDs is the best known catalog for a provider, live fetchers then profile fetch then the static list

type CatalogSetting

type CatalogSetting struct {
	Key   string
	Value any
}

One INI launch default in catalog document order

type ChatCompletionAgent

type ChatCompletionAgent interface {
	StreamDiagAgent
	Provider() string
	APIMode() string
	BaseURL() string
	Model() string
	Platform() string
	VerboseLogging() bool
	RetrySession() *RetrySession
	InterruptRequested() bool
	Client() any
	ComputeNonStreamStaleTimeout(apiKwargs map[string]any) (any, error)
	CreateRequestOpenAIClient(reason string, apiKwargs map[string]any) (any, error)
	AbortRequestOpenAIClient(client any, reason string) error
	CloseRequestOpenAIClient(client any, reason string) error
	ActiveRequestAbort() *RequestAbortHook
	SetActiveRequestAbort(hook *RequestAbortHook)
	RunCodexStream(ctx context.Context, apiKwargs map[string]any, client any, onFirstDelta func()) (any, error)
	CodexOnFirstDelta() func()
	AnthropicMessagesCreate(ctx context.Context, apiKwargs map[string]any, client any) (any, error)
	CodexSilentHangHint(model any) (string, error)
	ReasoningConfig() map[string]any
	EphemeralReasoningOff() bool
	SetEphemeralReasoningOff(on bool)
	ReasoningEffortRejected() bool
	ReasoningDisableRejected() bool
	ReasoningFloorRequired() bool
	SetWireReasoningConfig(cfg map[string]any)
	OllamaNumCtx() int
	OllamaSupportsThinkingCached() bool

	ToolEnv() *tools.Env
	IsHeadedMode() (bool, error)
	CleanupBrowser(ctx context.Context, taskID string) error
	CreateRequestAnthropicClient(reason string) (any, error)
	AbortRequestAnthropicClient(client any, reason string) error
	CloseRequestAnthropicClient(client any, reason string) error
	ActiveCodexStreamRequestToken() any
	SetActiveCodexStreamRequestToken(token any)
	EmitWaitNotice(text string)
	EmitDiagnosticWait(text string)
	ClientLogContext() string
	SessionID() string
	MaxIterations() int
	SuppressStatusOutput() bool
	SafePrint(text string, diagnostic bool)
	EmitWarning(text string)
	BufferStatus(text string)
	ShouldSanitizeToolCalls() bool
	CopyReasoningContentForAPI(src, dst map[string]any)
	SanitizeToolCallsForStrictAPI(msg map[string]any, model string)
	CachedSystemPrompt() string
	EphemeralSystemPrompt() string
	PrefillMessages() []map[string]any
	SanitizeAPIMessages(msgs []map[string]any) []map[string]any
	EvictStaleOutboundToolImages(msgs []map[string]any) int
	StripImagesForRejectingModel(msgs []map[string]any) bool
	DropThinkingOnlyAndMergeUsers(msgs []map[string]any) []map[string]any
	SubstituteAPIContent(msg map[string]any)
	CanonicalizeAPIToolCalls(msgs []map[string]any)
	CloneMessageForSend(msg map[string]any) map[string]any
	BuildAPIKwargs(apiMessages []map[string]any) (map[string]any, error)
	SanitizeOutboundKwargs(kwargs map[string]any)
	InterruptibleAPICall(ctx context.Context, apiKwargs map[string]any) (any, error)
	Transport() Transport
	MaxTokens() *int
	IsAnthropicOAuth() bool
	AnthropicPreserveDots() bool
	AnthropicBaseURL() string
	StreamEmitters
	SetCodexOnFirstDelta(fn func())
	FireStreamDelta(text string)
	FireToolGenStarted(name string)
	FireReasoningDelta(text string)
	HasStreamConsumers() bool
	WantsReasoningDeltas() bool
	DisableStreaming()
	CurrentAPIRequestID() string
	IsSubagent() bool
	FallbackIndex() int
	HeaderCapture() *HeaderCapture
	CurrentStreamedAssistantText() string
	RouteSuppressedStreamText(text string)
	ResetStreamDeliveryTracking()
	WarningPresentationEnabled() bool
	LogPrefix() string
	SetLastAPIFirstChunkAt(at float64)
}

ChatCompletionAgent is every agent field and method the agent shaped request helpers read or write

type ChatStreamWatchdog

type ChatStreamWatchdog struct {
	Window           float64
	FirstTokenWindow float64
	// contains filtered or unexported fields
}

ChatStreamWatchdog cuts a silent chat stream once its awake clock window lapses without substantive chunks

func (*ChatStreamWatchdog) Finish

func (w *ChatStreamWatchdog) Finish()

Retires the watchdog so no pending timer acts again

func (*ChatStreamWatchdog) Fired

func (w *ChatStreamWatchdog) Fired() bool

Fired reports whether the window lapsed

func (*ChatStreamWatchdog) Progress

func (w *ChatStreamWatchdog) Progress()

Re-arms the inter chunk window after a substantive chunk

func (*ChatStreamWatchdog) SawProgress

func (w *ChatStreamWatchdog) SawProgress() bool

SawProgress reports whether any substantive chunk arrived

func (*ChatStreamWatchdog) TimeoutError

func (w *ChatStreamWatchdog) TimeoutError() *AuxTimeoutError

No progress timeout before the first output, stalled timeout after it

type Classified

type Classified struct {
	Reason                 FailoverReason
	StatusCode             int
	Provider               string
	Model                  string
	Message                string
	Context                map[string]any
	Retryable              bool
	ShouldCompress         bool
	ShouldRotateCredential bool
	ShouldFallback         bool
}

Classified is the structured verdict on one failed call with its recovery hints

func ClassifyError

func ClassifyError(in ClassifyInput) *Classified

ClassifyError runs the staged pipeline over one failed call and returns its verdict with recovery hints

func (*Classified) BillingUnverified

func (c *Classified) BillingUnverified() bool

BillingUnverified reports a billing verdict resting on an ambiguous body

func (*Classified) IsAuth

func (c *Classified) IsAuth() bool

IsAuth reports a transient or permanent auth verdict

func (*Classified) ResetAt

func (c *Classified) ResetAt() (time.Time, bool)

ResetAt returns the provider declared reopening instant carried in the context

type ClassifierHook

type ClassifierHook func(in ClassifyInput, status int, errorType, errorCode, message string, body map[string]any) *Verdict

ClassifierHook lets a plugin add or correct a verdict before the built in pipeline runs

type ClassifyInput

type ClassifyInput struct {
	Err           error
	Status        int
	Body          string
	Headers       http.Header
	Provider      string
	Model         string
	BaseURL       string
	APIKey        string
	ApproxTokens  int
	ContextLength int
	NumMessages   int
}

ClassifyInput carries everything the classifier stages need about one failed call

type Client

type Client interface {
	Route() Route
	Complete(ctx context.Context, req *Request) (*Response, error)
	Stream(ctx context.Context, req *Request, fn StreamFunc) (*Response, error)
	CountTokens(ctx context.Context, req *Request) (int, error)
}

Client speaks one wire protocol for one route

func NewClient

func NewClient(route Route) (Client, error)

NewClient returns the adapter for the route's wire protocol

func NewGeminiNativeClient

func NewGeminiNativeClient(route Route) (Client, error)

NewGeminiNativeClient is the native Gemini generateContent client of a route

type ClonedGrantStrip

type ClonedGrantStrip struct {
	Pool      []string
	Providers []string
	Files     []string
}

ClonedGrantStrip names the pool providers, provider blocks and singleton files removed from a clone

func StripClonedSingleUseOAuthGrants

func StripClonedSingleUseOAuthGrants(profileDir string) ClonedGrantStrip

StripClonedSingleUseOAuthGrants removes forked single use OAuth grants from a freshly cloned profile, keeping API key rows

type CodexAppServerClient

type CodexAppServerClient struct {
	// contains filtered or unexported fields
}

CodexAppServerClient is a synchronous JSON-RPC 2.0 client of codex app-server over stdio

func NewCodexAppServerClient

func NewCodexAppServerClient(opts CodexAppServerOptions) (*CodexAppServerClient, error)

Starts codex app-server and its stdout and stderr readers

func (*CodexAppServerClient) Close

func (c *CodexAppServerClient) Close(timeout time.Duration)

Closes stdin and waits for the process tree to exit, sweeping the descendants snapshotted before the root retired

func (*CodexAppServerClient) Initialize

func (c *CodexAppServerClient) Initialize(clientName, clientTitle, clientVersion string, capabilities any, timeout time.Duration) (any, error)

Sends initialize then initialized and returns the server's InitializeResponse

func (*CodexAppServerClient) IsAlive

func (c *CodexAppServerClient) IsAlive() bool

True while the app-server process runs

func (*CodexAppServerClient) Notify

func (c *CodexAppServerClient) Notify(method string, params any) error

Sends a JSON-RPC notification, no id and no reply

func (*CodexAppServerClient) PID

func (c *CodexAppServerClient) PID() int

Pid of the app-server child

func (*CodexAppServerClient) Request

func (c *CodexAppServerClient) Request(method string, params any, timeout time.Duration) (any, error)

Sends a request and blocks for its result, a reported error becomes CodexAppServerError

func (*CodexAppServerClient) Respond

func (c *CodexAppServerClient) Respond(requestID any, result any) error

Replies to a server initiated request such as an approval prompt

func (*CodexAppServerClient) RespondError

func (c *CodexAppServerClient) RespondError(requestID any, code int, message string, data any) error

Replies to a server initiated request with an error, data only when given

func (*CodexAppServerClient) StderrTail

func (c *CodexAppServerClient) StderrTail(n int) []string

Last n lines of codex stderr with Python list slice semantics for n

func (*CodexAppServerClient) TakeNotification

func (c *CodexAppServerClient) TakeNotification(timeout time.Duration) any

Next streaming notification or nil on timeout, zero never blocks

func (*CodexAppServerClient) TakeServerRequest

func (c *CodexAppServerClient) TakeServerRequest(timeout time.Duration) any

Next server initiated request such as an exec or applyPatch approval

type CodexAppServerError

type CodexAppServerError struct {
	Code    any
	Message string
	Data    any
}

CodexAppServerError is a JSON-RPC error the app server reported

func (*CodexAppServerError) Error

func (e *CodexAppServerError) Error() string

func (*CodexAppServerError) PyTypeName

func (e *CodexAppServerError) PyTypeName() string

type CodexAppServerOptions

type CodexAppServerOptions struct {
	CodexBin  string
	CodexHome string
	ExtraArgs []string
	Env       map[string]string
	ToolEnv   *tools.Env
}

CodexAppServerOptions configures the codex app-server child process

type CodexAppServerSession

type CodexAppServerSession struct {
	// contains filtered or unexported fields
}

CodexAppServerSession owns one codex thread for an icebath session, one caller at a time

func NewCodexAppServerSession

func NewCodexAppServerSession(opts CodexAppServerSessionOptions) *CodexAppServerSession

Builds a session whose client spawns on first use

func (*CodexAppServerSession) Close

func (s *CodexAppServerSession) Close()

Closes the client and forgets the thread, idempotent

func (*CodexAppServerSession) CompactThread

func (s *CodexAppServerSession) CompactThread(turnTimeout, notificationPollTimeout float64) (*CodexTurnResult, error)

Triggers codex native history compaction of the current thread and waits for its turn/completed

func (*CodexAppServerSession) EnsureStarted

func (s *CodexAppServerSession) EnsureStarted() (string, error)

Spawns, handshakes and starts or resumes the thread, idempotent, a failed resume errors once

func (*CodexAppServerSession) RequestInterrupt

func (s *CodexAppServerSession) RequestInterrupt()

Signals the active turn loop to issue turn/interrupt and unwind, idempotent

func (*CodexAppServerSession) RequestSteer

func (s *CodexAppServerSession) RequestSteer(text string) (bool, error)

Appends user guidance to the active codex turn through turn/steer

func (*CodexAppServerSession) RunTurn

func (s *CodexAppServerSession) RunTurn(userInput any, opts CodexTurnOptions) (*CodexTurnResult, error)

Sends a user message and blocks until turn/completed, bridging approvals and projecting items

func (*CodexAppServerSession) ThreadID

func (s *CodexAppServerSession) ThreadID() string

Thread id of the started session, empty before start

type CodexAppServerSessionOptions

type CodexAppServerSessionOptions struct {
	Cwd                   string
	CodexBin              string
	CodexHome             string
	PermissionProfile     string
	ApprovalCallback      CodexApprovalCallback
	OnEvent               func(note any)
	RequestRouting        *CodexServerRequestRouting
	ClientFactory         func(codexBin, codexHome string) (CodexRPCClient, error)
	Model                 string
	ModelProvider         string
	DeveloperInstructions string
	ResumeThreadID        string
	HistorySeed           string
	ToolEnv               *tools.Env
}

CodexAppServerSessionOptions configures one codex thread per icebath session

type CodexAppServerTransportError

type CodexAppServerTransportError struct{ CodexAppServerError }

CodexAppServerTransportError reports the JSON-RPC transport gone, a failed write or a drained request

func (*CodexAppServerTransportError) As

func (e *CodexAppServerTransportError) As(target any) bool

Matches a CodexAppServerError target as the Python subclass does

func (*CodexAppServerTransportError) Error

func (*CodexAppServerTransportError) PyTypeName

func (e *CodexAppServerTransportError) PyTypeName() string

type CodexApprovalCallback

type CodexApprovalCallback func(command, description string, allowPermanent bool) (string, error)

CodexApprovalCallback asks the user about a codex command and answers once, session, always or deny

type CodexAuxiliaryClient

type CodexAuxiliaryClient struct {
	// contains filtered or unexported fields
}

OpenAI client compatible wrapper routing chat completions through the Codex Responses API

func NewCodexAuxiliaryClient

func NewCodexAuxiliaryClient(realClient auxResponsesClient, model string) *CodexAuxiliaryClient

Wraps the SDK client so chat completions run as Codex Responses streams

func (*CodexAuxiliaryClient) APIKey

func (c *CodexAuxiliaryClient) APIKey() string

func (*CodexAuxiliaryClient) BaseURL

func (c *CodexAuxiliaryClient) BaseURL() string

func (*CodexAuxiliaryClient) Close

func (c *CodexAuxiliaryClient) Close() error

Closes the wrapped SDK client

func (*CodexAuxiliaryClient) CreateChatCompletion

func (c *CodexAuxiliaryClient) CreateChatCompletion(ctx context.Context, kwargs map[string]any) (any, error)

Runs the request through the Codex adapter

type CodexContextCompressor

type CodexContextCompressor interface {
	AwaitingRealUsageAfterCompression() bool
	SetAwaitingRealUsageAfterCompression(on bool)
	UpdateFromResponse(usage map[string]any)
	SetContextLength(n int)
	CompressionCount() int
	SetCompressionCount(n int)
	SetLastCompressionRoughTokens(n int)
	SetLastUsage(promptTokens, completionTokens int)
}

CodexContextCompressor is the context compressor surface the runtime updates after usage and compaction

type CodexEventProjector

type CodexEventProjector struct {
	// contains filtered or unexported fields
}

CodexEventProjector projects codex app server item notifications into OpenAI shaped messages

func NewCodexEventProjector

func NewCodexEventProjector() *CodexEventProjector

Fresh projector with no stashed reasoning

func (*CodexEventProjector) Project

func (p *CodexEventProjector) Project(notification any) CodexProjectionResult

Materializes messages for an item completed notification, every other notification projects to nothing

type CodexLoginArgs

type CodexLoginArgs struct {
	Browser   bool
	NoBrowser bool
	Timeout   time.Duration
}

CodexLoginArgs are the flags of an interactive Codex login

type CodexMigrateOptions

type CodexMigrateOptions struct {
	CodexHome                  string
	DryRun                     bool
	SkipPluginDiscovery        bool
	DefaultPermissionProfile   string
	NoDefaultPermissionProfile bool
	SkipToolsMCPServer         bool
}

CodexMigrateOptions are the migrate keywords, an empty profile is the workspace built in and the No flag is None

type CodexMigrationReport

type CodexMigrationReport struct {
	TargetPath              string
	Migrated                []string
	SkippedKeysPerServer    map[string][]string
	MigratedPlugins         []string
	PluginQueryError        string
	WrotePermissionsDefault string
	PreservedUserServers    []string
	Errors                  []string
	Written                 bool
	DryRun                  bool
}

CodexMigrationReport is the outcome of one migration pass

func MigrateCodexRuntimePlugins

func MigrateCodexRuntimePlugins(ctx context.Context, cfg map[string]any, opts CodexMigrateOptions) (*CodexMigrationReport, error)

Projects the Icebath mcp_servers, installed codex plugins and the tools server into the managed block of codex config.toml

func (*CodexMigrationReport) Summary

func (r *CodexMigrationReport) Summary() string

Human readable lines naming what was written, migrated, skipped, preserved and every error

type CodexProjectionResult

type CodexProjectionResult struct {
	Messages        []map[string]any
	IsToolIteration bool
	FinalText       *string
}

CodexProjectionResult is the output of projecting one codex item, no messages for an ignored notification

type CodexRPCClient

type CodexRPCClient interface {
	Initialize(clientName, clientTitle, clientVersion string, capabilities any, timeout time.Duration) (any, error)
	Request(method string, params any, timeout time.Duration) (any, error)
	Respond(requestID any, result any) error
	RespondError(requestID any, code int, message string, data any) error
	TakeNotification(timeout time.Duration) any
	TakeServerRequest(timeout time.Duration) any
	StderrTail(n int) []string
	IsAlive() bool
	Close(timeout time.Duration)
}

CodexRPCClient is the JSON-RPC surface a session drives, CodexAppServerClient in production

type CodexReplayControl

type CodexReplayControl interface {
	RejectAllTurns(err error) bool
	DropUnverifiedReplay(messageLists ...[]*state.Message) int
}

CodexReplayControl exposes the per client replay recoveries the agent runs on a Codex 400

type CodexRequestTimeoutError

type CodexRequestTimeoutError struct {
	Method  string
	Timeout time.Duration
}

CodexRequestTimeoutError is the TimeoutError a request raises when no reply lands in time

func (*CodexRequestTimeoutError) Error

func (e *CodexRequestTimeoutError) Error() string

func (*CodexRequestTimeoutError) PyTypeName

func (e *CodexRequestTimeoutError) PyTypeName() string

type CodexResetRedeemResult

type CodexResetRedeemResult struct {
	Status         string
	Message        string
	AvailableCount int64
	WindowsReset   int64
}

CodexResetRedeemResult is the outcome of a usage reset attempt against the Codex backend

func RedeemCodexResetCredit

func RedeemCodexResetCredit(ctx context.Context, baseURL, apiKey string, force bool) CodexResetRedeemResult

RedeemCodexResetCredit redeems one banked Codex rate limit reset credit, every failure returned as a result

type CodexResolveOptions

type CodexResolveOptions struct {
	ForceRefresh        bool
	SkipExpiringRefresh bool
	RefreshSkew         time.Duration
	ReadOnly            bool
}

CodexResolveOptions tune the Codex runtime credential resolution

type CodexRuntimeAgent

type CodexRuntimeAgent interface {
	SessionID() string
	Provider() string
	RequestedProvider() string
	Model() string
	BaseURL() string
	APIKey() string
	Platform() string
	ReasoningConfig() map[string]any
	EphemeralSystemPrompt() string
	CachedSystemPrompt() string
	SessionCwd() string
	ValidToolNames() map[string]bool
	ShowCommentary() bool
	HoldStream() bool
	InterruptRequested() bool
	InterruptMessage() any
	ClearInterrupt()
	ItersSinceSkill() int
	SetItersSinceSkill(n int)
	SkillNudgeInterval() int
	CodexSession() *CodexAppServerSession
	SetCodexSession(s *CodexAppServerSession)
	CodexSessionPrompt() *string
	SetCodexSessionPrompt(p *string)
	CodexSessionModelProvider() *string
	SetCodexSessionModelProvider(p *string)
	CodexSessionDB() CodexSessionDB
	SessionDBCreated() bool
	EnsureDBSession() error
	SessionSource() string
	FlushMessagesToSessionDB(messages []map[string]any) state.FlushOutcome
	AddSessionAPICalls(n int)
	AddSessionUsage(key string, value int)
	AddSessionEstimatedCostUSD(usd float64)
	SetSessionCost(status, source string)
	SetLastCompactionInPlace(on bool)
	SetCurrentStreamedAssistantText(text string)
	CompressionCheckpointRequired() bool
	CodexContextCompressor() CodexContextCompressor
	SetUsageAnchor(anchor *UsageAnchor)
	EmitCompactionStatus()
	EmitDiagnosticStatus(text string)
	PublishProviderNativeCompaction()
	EventCallback() func(event string, data map[string]any)
	ToolProgressCallback() func(event, name string, preview any, args any, extra *CodexToolProgressExtra)
	ToolStartCallback() func(callID, name string, args any)
	ToolCompleteCallback() func(callID, name string, args any, result string)
	StreamDeltaHook(attr string) func(text string)
	InterimAssistantMessageHook() func(message map[string]any)
	TouchActivityHook() func(desc string)
	SyncExternalMemoryForTurnHook() func(originalUserMessage, finalResponse any, interrupted bool, messages []map[string]any)
	SpawnBackgroundReviewHook() func(messagesSnapshot []map[string]any, reviewMemory, reviewSkills bool)
	ToolEnv() *tools.Env
}

CodexRuntimeAgent is every agent field and method the codex app-server runtime reads or writes, a nil func is an unset hook

type CodexRuntimeStatus

type CodexRuntimeStatus struct {
	Success            bool
	NewValue           *string
	OldValue           *string
	Message            string
	RequiresNewSession bool
}

CodexRuntimeStatus is the outcome of one codex runtime command, rendered per surface by the caller

func ApplyCodexRuntime

func ApplyCodexRuntime(ctx context.Context, cfg map[string]any, newValue *string, persist func(map[string]any) error) (CodexRuntimeStatus, error)

Shows or switches the codex runtime, persisting through the callback and migrating on enable, an invalid name errors

type CodexRuntimeTurnHooks

type CodexRuntimeTurnHooks interface {
	ApplyLLMOutputTransform(finalResponse string, turnID any) (string, bool, any)
	EffectiveRequestOverrides() map[string]any
}

CodexRuntimeTurnHooks are the agent turn helpers the runtime reaches through the agent like a getattr

type CodexServerRequestRouting

type CodexServerRequestRouting struct {
	AutoApproveExec       bool
	AutoApproveApplyPatch bool
}

CodexServerRequestRouting is the approval policy used when no interactive approval callback is wired in

type CodexSessionDB

type CodexSessionDB interface {
	GetModelConfigValue(id, key string) (any, bool, error)
	PatchModelConfig(id string, patch map[string]any) error
	QueueTokenCounts(sessionID, source string, counts map[string]any) error
}

CodexSessionDB is the session store surface the runtime reads thread bindings from and queues accounting into

type CodexStreamErrorEvent

type CodexStreamErrorEvent struct {
	Message    string
	Code       string
	Param      string
	StatusCode int
	Body       map[string]any
}

CodexStreamErrorEvent is a provider error synthesized from a standalone type=error SSE frame

func (*CodexStreamErrorEvent) BodyText

func (e *CodexStreamErrorEvent) BodyText() string

BodyText is the OpenAI shaped error body as JSON for the classifier

func (*CodexStreamErrorEvent) Error

func (e *CodexStreamErrorEvent) Error() string

type CodexThreadResumeError

type CodexThreadResumeError struct {
	CodexAppServerError
	ThreadID string
}

CodexThreadResumeError reports a stored thread that thread/resume did not hand back

func (*CodexThreadResumeError) As

func (e *CodexThreadResumeError) As(target any) bool

Matches a CodexAppServerError target as the Python subclass does

func (*CodexThreadResumeError) PyTypeName

func (e *CodexThreadResumeError) PyTypeName() string

type CodexToolProgressExtra

type CodexToolProgressExtra struct {
	Duration *float64
	IsError  bool
	Result   *string
}

CodexToolProgressExtra carries the keyword arguments of a tool.completed progress callback

type CodexToolsImportError

type CodexToolsImportError struct{ Msg string }

CodexToolsImportError is a server build failure main reports with exit status 2

func (*CodexToolsImportError) Error

func (e *CodexToolsImportError) Error() string

type CodexToolsServer

type CodexToolsServer struct {
	// contains filtered or unexported fields
}

Stdio MCP server over registered tools, a concurrent one running each call on its own worker

func (*CodexToolsServer) AddTool

func (s *CodexToolsServer) AddTool(name, description string, params []MCPToolParam, inputSchema any, handler func(kwargs *pyjson.Object) string)

Registers a tool after the existing ones, a nil inputSchema listing the schema its params derive

func (*CodexToolsServer) Run

func (s *CodexToolsServer) Run() error

Serves newline delimited JSON-RPC on stdio until the client closes stdin, then lets running calls finish

type CodexTurnOptions

type CodexTurnOptions struct {
	Model                   string
	ReasoningEffort         *string
	ServiceTier             *string
	TurnTimeout             float64
	NotificationPollTimeout float64
	PostToolQuietTimeout    float64
}

CodexTurnOptions are the per turn settings sent on turn/start and the loop timeouts in seconds

type CodexTurnResult

type CodexTurnResult struct {
	FinalText          string
	ProjectedMessages  []map[string]any
	ToolIterations     int
	Interrupted        bool
	Error              string
	TurnID             string
	ThreadID           string
	SubmittedUserText  *string
	TokenUsageLast     *pyjson.Object
	ModelContextWindow int
	Compacted          bool
	ShouldRetire       bool
}

CodexTurnResult is the outcome of one turn through the codex app server, empty strings standing for None

type CodexWatchdogClock

type CodexWatchdogClock struct {
	StaleTimeout         float64
	TTFBEnabled          bool
	TTFBTimeout          float64
	LastEventTS          *float64
	LastProgressTS       *float64
	RetryStartedTS       *float64
	CallStart            float64
	IdleEnabled          bool
	IdleTimeout          float64
	IdleRequiresProgress bool
	Elapsed              float64
	ProgressTimeout      float64
}

Codex request watchdog configuration and its event clock in epoch seconds

type CodexWatchdogState

type CodexWatchdogState struct {
	Token          any
	Mu             sync.Mutex
	LastEventTs    *float64
	LastProgressTs *float64
	RetryStartedTs *float64
	PhaseAware     bool
}

CodexWatchdogState is the watchdog clock one codex request shares with the codex stream its worker runs

func CodexWatchdogStateFrom

func CodexWatchdogStateFrom(ctx context.Context) *CodexWatchdogState

Watchdog state of the codex request the context runs for, nil outside one

type CommandSource

type CommandSource struct{}

CommandSource is a user configured helper command as a bulk source

func (*CommandSource) ConfigSchema

func (s *CommandSource) ConfigSchema() map[string]map[string]any

func (*CommandSource) Fetch

func (s *CommandSource) Fetch(cfg map[string]any, homePath string, environ *SourceEnvironment) *SecretFetchResult

func (*CommandSource) Spec

func (s *CommandSource) Spec() SecretSourceSpec

type CommandTokenError

type CommandTokenError struct{ Message string }

CommandTokenError is a key_cmd that failed to produce a usable token

func (*CommandTokenError) Error

func (e *CommandTokenError) Error() string

type CommandTokenSource

type CommandTokenSource struct {
	Command string
	Label   string
	// contains filtered or unexported fields
}

CommandTokenSource mints a bearer token by running a command and caches it until shortly before expiry

func BuildCommandTokenSource

func BuildCommandTokenSource(keyCmd, providerLabel, h string, fileEnv func() map[string]string) *CommandTokenSource

BuildCommandTokenSource returns a per request token source for a key_cmd or nil when unset

func (*CommandTokenSource) CacheIdentity

func (s *CommandTokenSource) CacheIdentity() string

CacheIdentity is the stable catalog identity so token rotation never mints on cache reads

func (*CommandTokenSource) Token

func (s *CommandTokenSource) Token(ctx context.Context) (string, error)

Token returns the cached bearer or mints a fresh one when the cache is stale

type CompressionCheckpointUnavailable

type CompressionCheckpointUnavailable struct{ Msg string }

CompressionCheckpointUnavailable is raised when required durable pre compress checkpointing is unavailable

func CheckpointBlocked

func CheckpointBlocked(reason string) *CompressionCheckpointUnavailable

Refusal carrying the missing prerequisite marker and the reason the checkpoint is unavailable

func (*CompressionCheckpointUnavailable) Error

type CompressionFastLane

type CompressionFastLane struct {
	CertifiedNonReasoning bool
	ReasoningConfig       map[string]any
}

Explicit non reasoning compression route

func ResolveCompressionFastLane

func ResolveCompressionFastLane(ctx context.Context, actualProvider, actualModel, requestedProvider, requestedModel string, routeConfig map[string]any) (CompressionFastLane, error)

ResolveCompressionFastLane certifies explicit non reasoning settings only on the matching destination

type ConfigBackendUnavailableError

type ConfigBackendUnavailableError struct{ Message string }

ConfigBackendUnavailableError means the config backend cannot be reached with a source supplied credential

func (*ConfigBackendUnavailableError) Error

type ConfigBackendView

type ConfigBackendView struct {
	Name              string
	SelectorEnv       string
	ProtectedEnvNames map[string]bool
}

ConfigBackendView is what the secret loader needs to know about the selected config backend

type ConfigPath

type ConfigPath struct {
	Section string
	Key     string
	Index   int
}

ConfigPath names where one custom entry lives in config

func CustomProviderConfigPathForURL

func CustomProviderConfigPathForURL(baseURL any, cfg map[string]any) *ConfigPath

CustomProviderConfigPathForURL is the config path of the entry a bare custom route at a URL takes its key from

func NamedCustomProviderPath

func NamedCustomProviderPath(ctx context.Context, name string, cfg map[string]any) *ConfigPath

Config path of the entry the active home runtime routes a provider through, reading no credential

type ConfigWriteRefusedError

type ConfigWriteRefusedError struct {
	Path   string
	Reason string
	Err    error
}

ConfigWriteRefusedError is a config.yaml that cannot be read and so must not be replaced

func (*ConfigWriteRefusedError) Error

func (e *ConfigWriteRefusedError) Error() string

func (*ConfigWriteRefusedError) Unwrap

func (e *ConfigWriteRefusedError) Unwrap() error

type ConfiguredMatch

type ConfiguredMatch struct {
	Slug  string
	Model string
}

ConfiguredMatch is a configured provider slug and the declared model id that matched a typed name

type ContextLengthRequest

type ContextLengthRequest struct {
	Model               string
	BaseURL             string
	APIKey              string
	Provider            string
	ConfigContextLength int
	CustomProviders     []map[string]any
}

ContextLengthRequest names the route a context length is resolved for

type CopilotACPChatClient

type CopilotACPChatClient interface {
	CreateChatCompletion(ctx context.Context, kwargs map[string]any) (any, error)
	ListModels(ctx context.Context, timeoutSeconds float64) ([]string, error)
	Close() error
}

ACP stdio client of the GitHub Copilot CLI with the OpenAI chat facade

type CostResult

type CostResult struct {
	AmountUSD      *big.Rat
	Status         string
	Source         string
	Label          string
	FetchedAt      time.Time
	PricingVersion string
	Notes          []string
}

CostResult is the priced outcome of a usage bucket

func EstimateUsageCost

func EstimateUsageCost(ctx context.Context, modelName string, usage CanonicalUsage, provider, baseURL, apiKey string) CostResult

EstimateUsageCost prices a usage bucket for a model route with tier, fast mode and ultrafast rules

type Credential

type Credential struct {
	APIKey      string
	TokenSource func(ctx context.Context) (string, error)
	BaseURL     string
	Source      string
	Pool        *Pool
}

Credential is one usable login for a provider

type CredentialNotSavedError

type CredentialNotSavedError struct{ Message string }

CredentialNotSavedError means add wrote the pool but the store does not hold the new row

func (*CredentialNotSavedError) Error

func (e *CredentialNotSavedError) Error() string

type CredentialPersistError

type CredentialPersistError struct {
	Path  string
	Cause error
}

CredentialPersistError is a rotated single use credential that could not be durably committed

func (*CredentialPersistError) Error

func (e *CredentialPersistError) Error() string

func (*CredentialPersistError) Unwrap

func (e *CredentialPersistError) Unwrap() error

type CredentialSource

type CredentialSource interface {
	Credential(provider string) (Credential, bool)
}

CredentialSource answers which login a provider has

type CuratedFallbackModels

type CuratedFallbackModels []string

CuratedFallbackModels marks a curated list served because the live catalog was unavailable

type DataTrainingWarning

type DataTrainingWarning struct {
	Model    string
	Provider string
	Message  string
}

DataTrainingWarning is the confirmation payload for a tier whose vendor trains on user data

func DataTrainingWarningFor

func DataTrainingWarningFor(modelName, provider string) *DataTrainingWarning

DataTrainingWarningFor warns when the model selects a tier that trains on user data

type DeadlineExpiredError

type DeadlineExpiredError struct {
	Label string
	After time.Duration
}

DeadlineExpiredError is an icebath enforced deadline, not the provider's timeout

func (*DeadlineExpiredError) Error

func (e *DeadlineExpiredError) Error() string

func (*DeadlineExpiredError) Timeout

func (e *DeadlineExpiredError) Timeout() bool

Timeout marks the error as a net.Error style timeout

type DetectedServer

type DetectedServer struct {
	BaseURL      string
	BuildInfo    string
	ModelPath    string
	NCtx         any
	RouterMode   bool
	AuthRequired bool
}

A running llama-server, BaseURL its OpenAI compatible v1 root and NCtx nil when unreported

func DetectServer

func DetectServer(extraPorts []int) (*DetectedServer, error)

First server found across the default ports then extraPorts, each port probed once

func ProbePort

func ProbePort(port int) (*DetectedServer, error)

One port, the props fingerprint first, then the models listing for router capability

type DeviceCodeExpiredError

type DeviceCodeExpiredError struct {
	Message string
	Cause   error
}

DeviceCodeExpiredError is a device code that ran out before the browser approved it

func (*DeviceCodeExpiredError) Code

func (e *DeviceCodeExpiredError) Code() string

Code is the stable device code timeout code every provider shares

func (*DeviceCodeExpiredError) Error

func (e *DeviceCodeExpiredError) Error() string

func (*DeviceCodeExpiredError) Unwrap

func (e *DeviceCodeExpiredError) Unwrap() error

type DeviceFlowCancelledError

type DeviceFlowCancelledError struct{}

DeviceFlowCancelledError is the caller's cancelled hook firing while the token poll waited

func (*DeviceFlowCancelledError) Error

type DirectAlias

type DirectAlias struct {
	Model    string
	Provider string
	BaseURL  string
	APIKey   string
	KeyEnv   string
}

DirectAlias is an exact model, provider and endpoint with the endpoint's own credential

type DirectAliasTable

type DirectAliasTable struct {
	// contains filtered or unexported fields
}

DirectAliasTable is an insertion ordered alias map safe for concurrent use

func NewDirectAliasTable

func NewDirectAliasTable(entries ...NamedDirectAlias) *DirectAliasTable

NewDirectAliasTable builds a table holding the entries in order, a later duplicate replacing the earlier value

func (*DirectAliasTable) Clear

func (t *DirectAliasTable) Clear()

Clear removes every entry in place

func (*DirectAliasTable) Entries

func (t *DirectAliasTable) Entries() []NamedDirectAlias

Entries returns a snapshot of the entries in insertion order

func (*DirectAliasTable) Get

func (t *DirectAliasTable) Get(name string) (DirectAlias, bool)

Get returns the alias stored under a name

func (*DirectAliasTable) Len

func (t *DirectAliasTable) Len() int

Len counts the entries

func (*DirectAliasTable) Set

func (t *DirectAliasTable) Set(name string, alias DirectAlias)

Set stores an alias, keeping the original position of an existing name

type DisplayContextRequest

type DisplayContextRequest struct {
	Model               string
	Provider            string
	BaseURL             string
	APIKey              string
	ModelInfo           *ModelsDevEntry
	CustomProviders     []map[string]any
	ConfigContextLength *int
	ConfiguredModel     string
	ConfiguredProvider  string
	ConfiguredBaseURL   string
}

DisplayContextRequest is the route and configured pin a context length display is computed for

type DistributionManifest

type DistributionManifest = profiles.DistributionManifest

Parsed distribution.yaml of a profile, defined in pkg/profiles so the profile installer shares it

func ReadManifest

func ReadManifest(profileDir string) (*DistributionManifest, error)

Manifest next to profileDir, nil and nil when the directory holds no distribution.yaml

type DotenvLoadOptions

type DotenvLoadOptions struct {
	Home                string
	ProjectEnv          string
	SkipExternalSecrets bool
}

Options of one full dotenv load

type EmptyStreamError

type EmptyStreamError struct{ Message string }

EmptyStreamError is raised when a provider closes a stream without yielding a response

func (*EmptyStreamError) Error

func (e *EmptyStreamError) Error() string

type Engine

type Engine struct {
	Backend string
	Tag     string
	Binary  string
}

func EnsureEngine

func EnsureEngine(ctx context.Context, backend string, opts EnsureEngineOptions) (Engine, error)

Installs the resolved backend's pinned engine through PM and returns the current engine, only deliberate jobs call it

func InstalledEngine

func InstalledEngine(ctx context.Context, backend string, allowOutdated bool) (*Engine, error)

Installed engine for backend, moving a pre PM engine into the store once and never downloading, nil when none

type EnsureEngineOptions

type EnsureEngineOptions struct {
	Progress         pm.InstallProgress
	PauseEvent       *pm.PauseEvent
	DownloadProgress pm.ProgressFunc
}

EnsureEngineOptions carries the install job's progress callbacks and pause switch

type EntraAccessToken

type EntraAccessToken struct {
	Token     string
	ExpiresOn int64
	RefreshOn int64
}

Bearer token with its epoch expiry and the epoch after which a refresh is due

type EntraBearerTransport

type EntraBearerTransport struct {
	Base          http.RoundTripper
	TokenProvider func(context.Context) (string, error)
	SendsAsAPIKey func(token string) bool
}

Round tripper that mints a fresh Entra bearer per request and replaces every preset auth header

func NewEntraBearerTransport

func NewEntraBearerTransport(provider func(context.Context) (string, error), sendsAsAPIKey func(string) bool, base http.RoundTripper) (*EntraBearerTransport, error)

NewEntraBearerTransport wraps base, requiring a token provider

func (*EntraBearerTransport) RoundTrip

func (t *EntraBearerTransport) RoundTrip(req *http.Request) (*http.Response, error)

type EntraIdentityConfig

type EntraIdentityConfig struct {
	Scope                     string
	ExcludeInteractiveBrowser bool
}

Entra knobs icebath manages, everything else flows through the standard AZURE_ variables

func NewEntraIdentityConfig

func NewEntraIdentityConfig(scope string, excludeInteractiveBrowser bool) EntraIdentityConfig

NewEntraIdentityConfig normalizes a blank scope to the Foundry inference default

type EnvCredentialPurge

type EnvCredentialPurge struct {
	PoolPruned []string
	Providers  []string
}

EnvCredentialPurge names the providers whose env seeded pool rows were pruned and every provider the purge touched

func PurgeEnvCredentialReferences

func PurgeEnvCredentialReferences(ctx context.Context, h, envVar string, clearModelsCache bool) (EnvCredentialPurge, error)

PurgeEnvCredentialReferences prunes env seeded pool rows, suppresses the env source and clears affected model cache rows

type ErrorKind

type ErrorKind string

Classified failure cause of an inference call

const (
	ErrAuth            ErrorKind = "auth"
	ErrRateLimit       ErrorKind = "rate_limit"
	ErrQuota           ErrorKind = "quota"
	ErrContextOverflow ErrorKind = "context_overflow"
	ErrInvalidRequest  ErrorKind = "invalid_request"
	ErrModelNotFound   ErrorKind = "model_not_found"
	ErrServer          ErrorKind = "server"
	ErrNetwork         ErrorKind = "network"
	ErrTimeout         ErrorKind = "timeout"
	ErrContentFilter   ErrorKind = "content_filter"
	ErrEmptyResponse   ErrorKind = "empty_response"
	ErrCancelled       ErrorKind = "cancelled"
	ErrUnknown         ErrorKind = "unknown"
)

func KindFor

func KindFor(reason FailoverReason) ErrorKind

KindFor maps a failover reason onto the coarse error kind adapters and views read

type EventKind

type EventKind string

Kind of incremental stream event

const (
	EventTextDelta      EventKind = "text_delta"
	EventReasoningDelta EventKind = "reasoning_delta"
	EventToolCallStart  EventKind = "tool_call_start"
	EventToolCallDelta  EventKind = "tool_call_delta"
	EventToolCallDone   EventKind = "tool_call_done"
	EventUsage          EventKind = "usage"
	EventStatus         EventKind = "status"
	EventWaitNotice     EventKind = "wait_notice"
	EventActivity       EventKind = "activity"
	EventDone           EventKind = "done"
)

type ExpensiveModelWarning

type ExpensiveModelWarning struct {
	Model                string
	Provider             string
	InputCostPerMillion  *big.Rat
	OutputCostPerMillion *big.Rat
	Source               string
	Message              string
}

ExpensiveModelWarning is the confirmation payload for a model priced above the cost guardrail

func ExpensiveModelWarningFor

func ExpensiveModelWarningFor(ctx context.Context, modelName, provider, baseURL, apiKey string, info *ModelsDevEntry) *ExpensiveModelWarning

ExpensiveModelWarningFor warns when known pricing exceeds the input or output threshold, never on unknown pricing

type ExternalProcessSpec

type ExternalProcessSpec struct {
	Command        string
	Args           []string
	CommandEnvVars []string
	ArgsEnvVar     string
}

ExternalProcessSpec describes the CLI an agent over stdio provider launches

type Factory

type Factory func(route Route) (Client, error)

Adapter constructor for one wire protocol

type FailedStreamRequest

type FailedStreamRequest struct {
	URL     string
	Content []byte
}

FailedStreamRequest is the buffered request a failed stream attempt sent, Content nil when unknown

type FailoverReason

type FailoverReason string

FailoverReason names why an API call failed and so which recovery runs

const (
	ReasonAuth                       FailoverReason = "auth"
	ReasonAuthPermanent              FailoverReason = "auth_permanent"
	ReasonBilling                    FailoverReason = "billing"
	ReasonRateLimit                  FailoverReason = "rate_limit"
	ReasonUpstreamRateLimit          FailoverReason = "upstream_rate_limit"
	ReasonUpstreamBlocked            FailoverReason = "upstream_blocked"
	ReasonOverloaded                 FailoverReason = "overloaded"
	ReasonServerError                FailoverReason = "server_error"
	ReasonTimeout                    FailoverReason = "timeout"
	ReasonSSLCertVerification        FailoverReason = "ssl_cert_verification"
	ReasonContextOverflow            FailoverReason = "context_overflow"
	ReasonPayloadTooLarge            FailoverReason = "payload_too_large"
	ReasonImageTooLarge              FailoverReason = "image_too_large"
	ReasonImageCorrupt               FailoverReason = "image_corrupt"
	ReasonModelNotFound              FailoverReason = "model_not_found"
	ReasonProviderPolicyBlocked      FailoverReason = "provider_policy_blocked"
	ReasonDataPolicyDenied           FailoverReason = "data_policy_denied"
	ReasonContentPolicyBlocked       FailoverReason = "content_policy_blocked"
	ReasonModelEntitlement           FailoverReason = "model_entitlement"
	ReasonIncompleteResponse         FailoverReason = "incomplete_response"
	ReasonFormatError                FailoverReason = "format_error"
	ReasonRoleAlternation            FailoverReason = "role_alternation"
	ReasonInvalidEncryptedContent    FailoverReason = "invalid_encrypted_content"
	ReasonMultimodalToolContent      FailoverReason = "multimodal_tool_content_unsupported"
	ReasonReasoningMandatory         FailoverReason = "reasoning_mandatory"
	ReasonThinkingSignature          FailoverReason = "thinking_signature"
	ReasonLongContextTier            FailoverReason = "long_context_tier"
	ReasonOAuthLongContextBetaForbid FailoverReason = "oauth_long_context_beta_forbidden"
	ReasonLlamaCppGrammarPattern     FailoverReason = "llama_cpp_grammar_pattern"
	ReasonCancelled                  FailoverReason = "cancelled"
	ReasonUnknown                    FailoverReason = "unknown"
)

func ParseFailoverReason

func ParseFailoverReason(value any) (FailoverReason, bool)

FailoverReason enum construction by value, false for a value outside the enum

type FailureScope

type FailureScope string

FailureScope names which identity axis a failure invalidates

const (
	// Timeout, overload, connection blip, invalid response, evidence against one model deployment
	ScopeModel FailureScope = "model"
	// Auth 401 or payment 402, evidence against the shared credential
	ScopeCredential FailureScope = "credential"
	// DNS, connection refused, unreachable host, evidence against the endpoint
	ScopeEndpoint FailureScope = "endpoint"
)

type FallbackAPIModeAgent

type FallbackAPIModeAgent interface {
	IsAzureOpenAIURL(baseURL string) bool
	IsDirectOpenAIURL(baseURL string) bool
	ProviderModelRequiresResponsesAPI(model, providerName string) bool
}

FallbackAPIModeAgent is the agent half of fallback wire detection, its Azure, direct OpenAI and Responses predicates

type FallbackCheckRedactor

type FallbackCheckRedactor func(value any, maxChars int) string

FallbackCheckRedactor scrubs one support text, keeping at most maxChars characters unless maxChars is negative

type FallbackEntryCheck

type FallbackEntryCheck struct {
	Provider       string
	Model          string
	BaseURL        string
	APIMode        string
	AuthSource     string
	Configured     bool
	AuthReady      bool
	InferenceReady *bool
	LatencyMs      *int
	ModelReturned  string
	ErrorClass     string
	Error          string
}

FallbackEntryCheck is one fallback entry's verdict, InferenceReady and LatencyMs nil until a live probe ran

func CheckFallbackEntryStatic

func CheckFallbackEntryStatic(ctx context.Context, entry map[string]any, redact FallbackCheckRedactor) (*FallbackEntryCheck, error)

CheckFallbackEntryStatic resolves an entry the way the fallback switch does without sending an inference request, an error only for a host abort or an unreadable config

func (*FallbackEntryCheck) Ready

func (c *FallbackEntryCheck) Ready() bool

Ready reports an entry that resolved with credentials and whose live probe, when one ran, answered

func (*FallbackEntryCheck) Status

func (c *FallbackEntryCheck) Status() string

Status is ready after a live answer, ready (static) without a probe, else the error class every failed path sets

type FastWindow

type FastWindow struct {

	// Stored tier, empty for normal
	ServiceTier string
	// Window length for auto and cold
	AutoSeconds float64
	// Static per session request overrides the fast override is layered onto
	RequestOverrides map[string]any
	// Daybreak opt in forwarded to the Codex tier negotiation
	Daybreak bool
	// contains filtered or unexported fields
}

FastWindow holds a session's service tier, its bounded window, and the models that lack fast capacity

func NewFastWindow

func NewFastWindow(serviceTier string, overrides map[string]any) *FastWindow

NewFastWindow returns a closed window for the tier with the default auto length

func (*FastWindow) BeginTurn

func (f *FastWindow) BeginTurn(history []*state.Message)

BeginTurn opens the window at a user turn boundary, cold only when no history exists

func (*FastWindow) EffectiveRequestOverrides

func (f *FastWindow) EffectiveRequestOverrides(route Route, anthropicBaseURL string) map[string]any

EffectiveRequestOverrides layers the fast override onto the static overrides while the window is open

func (*FastWindow) FastModeUnavailable

func (f *FastWindow) FastModeUnavailable(model string) bool

FastModeUnavailable reports whether the model was marked without fast capacity

func (*FastWindow) MarkFastModeUnavailable

func (f *FastWindow) MarkFastModeUnavailable(model string) bool

MarkFastModeUnavailable stops sending speed for the model this session, false when already marked

func (*FastWindow) Open

func (f *FastWindow) Open() bool

Open reports whether the bounded fast window is live

type FetchModelsOptions

type FetchModelsOptions struct {
	Timeout      time.Duration
	ForceRefresh bool
	CacheOnly    bool
}

FetchModelsOptions tune one picker list fetch

type FileLockTimeoutError

type FileLockTimeoutError struct {
	Message string
}

FileLockTimeoutError is the TimeoutError a waiter raises once the deadline passes with another holder on the lock

func (*FileLockTimeoutError) Error

func (e *FileLockTimeoutError) Error() string

type FoundImportSource

type FoundImportSource struct {
	Source ImportSource
	Home   string
}

FoundImportSource is an importer with the dir or export that showed its agent on this computer

func DetectImportSources

func DetectImportSources() []FoundImportSource

DetectImportSources lists the importers whose agent has a setup on this computer, each with the dir found

type GGMLDevice

type GGMLDevice struct {
	Description string
	Type        int
	Free        int64
	Total       int64
}

A GPU or integrated GPU the engine's ggml backend registers, Free capped at Total

func ProbeDevices

func ProbeDevices(engineDir, backend string) []GGMLDevice

GPU and iGPU devices the backend library in engineDir registers, empty on any failure

type GGUFError

type GGUFError struct {
	Class string
	Msg   string
}

Carries the Python exception class a header read or metadata coercion raised

func (*GGUFError) Error

func (e *GGUFError) Error() string

type GGUFHeader

type GGUFHeader struct {
	Path               string
	Version            uint32
	Metadata           map[string]any
	MetadataKeys       []string
	NTensors           int64
	TensorBytes        int64
	EmbdTableBytes     int64
	FFNBlockBytes      map[int]int64
	LazyCandidateBytes map[string]int64
	RecurrentBlocks    map[int]bool
}

one model's metadata and tensor table totals, summed across split parts

func ReadGGUFHeader

func ReadGGUFHeader(path string) (*GGUFHeader, error)

Header for a model, a split priced as the sum of its readable parts with metadata from part one

func (*GGUFHeader) Architecture

func (h *GGUFHeader) Architecture() string

func (*GGUFHeader) ExpertCount

func (h *GGUFHeader) ExpertCount() (int64, error)

func (*GGUFHeader) FullAttentionInterval

func (h *GGUFHeader) FullAttentionInterval() (int64, error)

Every Nth layer is full attention in GDN hybrids, zero when absent

func (*GGUFHeader) HeadCountsKV

func (h *GGUFHeader) HeadCountsKV() ([]int64, error)

Per layer KV head counts where zero marks a recurrent or linear layer

func (*GGUFHeader) HeadDimK

func (h *GGUFHeader) HeadDimK() (int64, error)

Per head key size from key_length, else embedding size over head count

func (*GGUFHeader) HeadDimV

func (h *GGUFHeader) HeadDimV() (int64, error)

Per head value size from value_length, else the key size

func (*GGUFHeader) KeyLengthSWA

func (h *GGUFHeader) KeyLengthSWA() (int64, error)

Per token key size of sliding window layers when it differs from the global one, zero when absent

func (*GGUFHeader) LazyBytes

func (h *GGUFHeader) LazyBytes() int64

Bytes of weights llama.cpp keeps on disk and reads row by row instead of loading

func (*GGUFHeader) NCtxTrain

func (h *GGUFHeader) NCtxTrain() (int64, error)

func (*GGUFHeader) NEmbd

func (h *GGUFHeader) NEmbd() (int64, error)

func (*GGUFHeader) NHead

func (h *GGUFHeader) NHead() (int64, error)

Attention head count, the maximum when the file stores one per layer

func (*GGUFHeader) NLayer

func (h *GGUFHeader) NLayer() (int64, error)

func (*GGUFHeader) NVocab

func (h *GGUFHeader) NVocab() (int64, error)

Vocabulary size from vocab_size metadata, else the tokenizer list length

func (*GGUFHeader) RecurrentStateBytes

func (h *GGUFHeader) RecurrentStateBytes() (int64, error)

One sequence's f32 conv window plus SSM state across stateful blocks, zero without an SSM shape

func (*GGUFHeader) SamplingDefaults

func (h *GGUFHeader) SamplingDefaults() (map[string]string, error)

Upstream recommended sampling from general.sampling keys as preset INI keys, empty when absent

func (*GGUFHeader) SlidingWindow

func (h *GGUFHeader) SlidingWindow() (int64, error)

func (*GGUFHeader) SlidingWindowPattern

func (h *GGUFHeader) SlidingWindowPattern() ([]int64, error)

Per layer SWA flags from the file's array form, nil when the file declares no array

func (*GGUFHeader) SlidingWindowPatternPeriod

func (h *GGUFHeader) SlidingWindowPatternPeriod() int64

Scalar SWA period declared by the file, zero when absent or in array form

func (*GGUFHeader) ValueLengthSWA

func (h *GGUFHeader) ValueLengthSWA() (int64, error)

Per token value size of sliding window layers when it differs from the global one, zero when absent

type GeminiAPIError

type GeminiAPIError struct {
	Message    string
	Code       string
	StatusCode int
	RetryAfter time.Duration
	Details    map[string]any
	Headers    http.Header
	Body       string
	Err        error
}

GeminiAPIError is a failed native Gemini call with its google.rpc status, reason and guidance

func (*GeminiAPIError) Error

func (e *GeminiAPIError) Error() string

func (*GeminiAPIError) ResponseHeaders

func (e *GeminiAPIError) ResponseHeaders() http.Header

Response headers of the failed call for retry after parsing

func (*GeminiAPIError) Unwrap

func (e *GeminiAPIError) Unwrap() error

type GoogleCredentials

type GoogleCredentials struct {
	// contains filtered or unexported fields
}

Google OAuth credential that mints bearer tokens on demand, safe for concurrent use

func GoogleAuthorizedUserCredentials

func GoogleAuthorizedUserCredentials(info map[string]any, scopes []string) (*GoogleCredentials, error)

End user credential refreshed through its refresh token, scoped as given

func GoogleDefaultCredentials

func GoogleDefaultCredentials(ctx context.Context, scopes []string) (*GoogleCredentials, string, error)

Application default credential and its project, from the env key file, the gcloud login or the metadata server

func GoogleServiceAccountCredentials

func GoogleServiceAccountCredentials(info map[string]any, scopes []string) (*GoogleCredentials, error)

Service account credential from a parsed key file, scoped as given

func (*GoogleCredentials) Current

func (g *GoogleCredentials) Current() (string, time.Time)

Cached token and its expiry, zero values before the first mint

func (*GoogleCredentials) QuotaProject

func (g *GoogleCredentials) QuotaProject() string

Quota project the credential bills, empty when none is set

func (*GoogleCredentials) Refresh

func (g *GoogleCredentials) Refresh(ctx context.Context) error

Mints a fresh token regardless of the cached one

func (*GoogleCredentials) Seed

func (g *GoogleCredentials) Seed(token string, expiry time.Time)

Installs a token minted earlier so it is used until its expiry passes

func (*GoogleCredentials) Token

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

Valid bearer token, refreshed first when missing or near expiry

type GrowthDecision

type GrowthDecision struct {
	Action     string
	NextWindow int
	Reason     string
}

One end of turn verdict to grow to the next window, hold or compress

func DecideGrowth

func DecideGrowth(profile ModelProfile, budget HardwareBudget, currentWindow, sessionTokens int,
	measuredDecodeTokS *float64, serverIdle, flashAttention, occupancyConfirmed bool) GrowthDecision

End of turn growth verdict gated on occupancy, native cap, idleness, speed floor and live memory

type HFFileGroup

type HFFileGroup struct {
	Label      string   `json:"label"`
	Paths      []string `json:"paths"`
	TotalBytes int64    `json:"total_bytes"`
	Fit        string   `json:"fit"`
}

HFFileGroup is one downloadable quant, a single GGUF or every part of a split one

func PricedRepoFiles

func PricedRepoFiles(repo string, budget HardwareBudget) ([]HFFileGroup, error)

Repo files each priced against budget

func RepoFiles

func RepoFiles(repo string) ([]HFFileGroup, error)

Servable GGUFs of repo with split parts collapsed and companions dropped, largest first

type HFModelHit

type HFModelHit struct {
	Repo      string `json:"repo"`
	Downloads int64  `json:"downloads"`
	Likes     int64  `json:"likes"`
	Updated   string `json:"updated"`
	Gated     bool   `json:"gated"`
}

HFModelHit is one Hugging Face repo that ships GGUF files

func SearchModels

func SearchModels(query string, limit int) ([]HFModelHit, error)

Hugging Face models shipping GGUF files that match query, most downloaded first

type HTTPException

type HTTPException struct {
	StatusCode int
	Detail     string
}

Refusal carrying a status code and the detail the user sees

func (*HTTPException) Error

func (e *HTTPException) Error() string

type HTTPStatusError

type HTTPStatusError struct {
	Status int
	URL    string
	Body   string
}

HTTPStatusError is a response whose status is an error, the raise for status of the stdlib

func (*HTTPStatusError) Error

func (e *HTTPStatusError) Error() string

type HardwareBudget

type HardwareBudget struct {
	UsableVRAMBytes   int64
	TotalDeviceBytes  int64
	RAMAvailableBytes int64
	UMA               bool
	GPUName           string
	Platform          string
	GPUPCIID          *int64
	LazyReads         bool
	CommitRoomBytes   *int64
}

The memory the physics check budgets against on one machine

func LaunchBudget

func LaunchBudget(capacity HardwareBudget, ownBytes int64) (*HardwareBudget, error)

Capacity less what other programs hold on the card now, nil when no live reading applies

func ProbeBudget

func ProbeBudget(planning bool) (HardwareBudget, error)

Live budget or capacity budget when planning, err for the exceptions Python lets escape the probe

type HardwareProbeError

type HardwareProbeError struct {
	Class string
	Msg   string
}

Python exception that escaped every handler of the probe, Class names the exception type

func (*HardwareProbeError) Error

func (e *HardwareProbeError) Error() string

type HeaderCapture

type HeaderCapture struct {

	// Live provider the rate limit headers are parsed for
	Provider string
	Log      *slog.Logger
	// contains filtered or unexported fields
}

HeaderCapture holds the last rate limit headers and the OpenRouter cache hits of a session

func NewHeaderCapture

func NewHeaderCapture(provider string) *HeaderCapture

NewHeaderCapture returns an empty capture bound to a provider

func (*HeaderCapture) CaptureRateLimits

func (c *HeaderCapture) CaptureRateLimits(h http.Header)

Parses x-ratelimit headers into the cached state keeping the last known on a miss

func (*HeaderCapture) CheckOpenRouterCacheStatus

func (c *HeaderCapture) CheckOpenRouterCacheStatus(h http.Header)

Logs X-OpenRouter-Cache-Status and counts HITs

func (*HeaderCapture) OpenRouterCacheHits

func (c *HeaderCapture) OpenRouterCacheHits() int

How many HIT responses the session saw

func (*HeaderCapture) RateLimit

func (c *HeaderCapture) RateLimit() *RateLimitState

Last captured rate limit state or nil

func (*HeaderCapture) SetProvider

func (c *HeaderCapture) SetProvider(provider string)

Moves the capture onto the live provider after a fallback or model switch

type HeaderCarrier

type HeaderCarrier interface{ ResponseHeaders() http.Header }

HeaderCarrier exposes the response headers of a failed call for reset and welcome tier parsing

type HeaderEntry

type HeaderEntry struct {
	Key   string
	Value string
	Fn    func() string
}

HeaderEntry is one default header, Fn computing the value on first read when set

type HookJSONCaps

type HookJSONCaps struct {
	MaxDepth    int
	MaxString   int
	MaxSequence int
}

HookJSONCaps bounds the depth, string length, and sequence length of a sanitized payload

type HostedAnswer

type HostedAnswer struct {
	Cancelled bool
	Index     int
	Picked    []int
	Text      string
	Ran       bool
	Err       string
}

HostedAnswer is the reply of the host, Cancelled when the user backed out of the question

type HostedModelResult

type HostedModelResult struct {
	Model    string
	Provider string
	Changed  bool
}

HostedModelResult is the default model and provider a hosted model section leaves, and whether it changed them

func RunHostedModelSection

func RunHostedModelSection(ctx context.Context, ask SetupAsker, out io.Writer, entry string) (HostedModelResult, error)

RunHostedModelSection runs the model picker on a host, opening at entry, then resaves the config unless stopped

func RunHostedSetupFlow

func RunHostedSetupFlow(ctx context.Context, ask SetupAsker, out io.Writer, run func(ctx context.Context, ask setupflow.Asker) error) (HostedModelResult, bool, error)

Runs a setup flow with its questions put to a host, reporting the model it leaves and a stop

type HostedPrompt

type HostedPrompt struct {
	Kind        string
	Title       string
	Description string
	Rows        []string
	Answers     []string
	Headings    map[int]string
	Default     int
	Picked      []int
	Argv        []string
}

HostedPrompt is one question a setup flow asks while a host answers in place of a terminal

type IcebathOverlay

type IcebathOverlay struct {
	Transport       string
	IsAggregator    bool
	AuthType        string
	ExtraEnvVars    []string
	BaseURLOverride string
	BaseURLEnvVar   string
}

Overlay fields for a provider's models.dev keyed definition

type ImportSource

type ImportSource struct {
	Name         string
	Label        string
	Dirs         []string
	SetupSecrets bool
	Exports      []string
}

ImportSource is one native importer with the dirs that show the agent is installed

type InterruptedError

type InterruptedError struct {
	Message string
}

Python InterruptedError a user interrupt raises inside a provider stream

func (*InterruptedError) Error

func (e *InterruptedError) Error() string

type IronProxy

type IronProxy struct {
	Home string
	Log  *slog.Logger
}

IronProxy binds the iron-proxy integration to one icebath home

func (IronProxy) BuildProxyConfig

func (p IronProxy) BuildProxyConfig(opts IronProxyConfigOptions) map[string]any

BuildProxyConfig is the iron-proxy YAML document, real secrets come from the daemon's own env

func (IronProxy) EnsureCACert

func (p IronProxy) EnsureCACert(force bool) (string, string, error)

EnsureCACert generates or returns the 10 year CA cert and key through the host openssl

func (IronProxy) EnsureManagementToken

func (p IronProxy) EnsureManagementToken(force bool) (string, error)

EnsureManagementToken returns the management API bearer key, minting it on first call

func (IronProxy) FindIronProxy

func (p IronProxy) FindIronProxy(installIfMissing bool) string

FindIronProxy resolves the binary from PATH or the tool store, installing on a miss when asked

func (IronProxy) GetStatus

func (p IronProxy) GetStatus() IronProxyStatus

GetStatus snapshots the proxy state without side effects

func (IronProxy) InstallIronProxy

func (p IronProxy) InstallIronProxy() (string, error)

InstallIronProxy is the explicit setup or repair install

func (IronProxy) IronProxyVersion

func (p IronProxy) IronProxyVersion(binary string) string

IronProxyVersion is the version output stripped and cached by path, empty on failure

func (IronProxy) LoadMappings

func (p IronProxy) LoadMappings() ([]TokenMapping, error)

LoadMappings reads mappings.json, empty on a read or parse failure, erring only when the state dir cannot be made

func (IronProxy) ReloadProxy

func (p IronProxy) ReloadProxy() error

ReloadProxy POSTs the reload endpoint, validation failures leave the running config untouched

func (IronProxy) StartProxy

func (p IronProxy) StartProxy(opts IronProxyStartOptions) (IronProxyStatus, error)

StartProxy spawns iron-proxy as a managed background daemon, idempotent when already running

func (IronProxy) StopProxy

func (p IronProxy) StopProxy() (bool, error)

StopProxy terminates the daemon, true when it was running, a failed cleanup or a refused signal returned as the error

func (IronProxy) WriteMappings

func (p IronProxy) WriteMappings(mappings []TokenMapping) (string, error)

WriteMappings persists sandbox visible tokens to mappings.json

func (IronProxy) WriteProxyConfig

func (p IronProxy) WriteProxyConfig(cfg map[string]any) (string, error)

WriteProxyConfig serializes the config to proxy.yaml under the home, written 0600 from creation

type IronProxyConfigOptions

type IronProxyConfigOptions struct {
	Mappings          []TokenMapping
	CACert            string
	CAKey             string
	TunnelPort        int
	AuditLog          string
	AllowedHosts      []string
	UpstreamDenyCIDRs []string
	DenyCIDRsSet      bool
	HTTPListen        []string
}

IronProxyConfigOptions parameterize the generated proxy.yaml

type IronProxyStartOptions

type IronProxyStartOptions struct {
	Binary                      string
	ConfigPath                  string
	ExtraEnv                    map[string]string
	InstallIfMissing            bool
	RefreshSecretsFromBitwarden bool
	BitwardenConfig             map[string]any
}

IronProxyStartOptions parameterize a daemon start

type IronProxyStatus

type IronProxyStatus struct {
	Enabled       bool
	BinaryPath    string
	BinaryVersion string
	ConfigPath    string
	CACertPath    string
	PID           int
	Listening     bool
	TunnelPort    int
	Warnings      []string
}

IronProxyStatus is a snapshot of the proxy state

func (IronProxyStatus) Configured

func (s IronProxyStatus) Configured() bool

Configured reports both the config and the CA cert on disk

type LMStudioLoadResult

type LMStudioLoadResult struct {
	ContextLength int
	LoadAttempted bool
	Rejected      bool
}

LMStudioLoadResult is the verified LM Studio runtime context plus load attempt provenance

func EnsureLMStudioModelLoaded

func EnsureLMStudioModelLoaded(ctx context.Context, model, baseURL string, apiKey any, targetContextLength int, hasTarget bool, timeout time.Duration) LMStudioLoadResult

EnsureLMStudioModelLoaded returns the loaded model's verified context, cold loading it with the explicit target when one is set

type LaunchPlan

type LaunchPlan struct {
	Decision      WindowOutcome
	MTPPrefill    bool
	OverheadBytes int64
	Profile       *ModelProfile
}

A window outcome with its prefill posture, overhead and the profile it priced

func FitToFreeMemory

func FitToFreeMemory(plan LaunchPlan, profile ModelProfile, live HardwareBudget, mtpCapable bool, fixedOverhead int64) LaunchPlan

Resident plan narrowed to the window free memory holds now, never below the floor

func PlanLaunch

func PlanLaunch(profile ModelProfile, budget HardwareBudget, mtpCapable bool, fixedOverhead int64, requestedWindow int) LaunchPlan

Window first then prefill posture, both priced at the effective window with a restored window honoured

type LayerKind

type LayerKind string

The attention kind of one model layer

const (
	LayerFull      LayerKind = "full"
	LayerSWA       LayerKind = "swa"
	LayerRecurrent LayerKind = "recurrent"
)

type LazyHeaders

type LazyHeaders struct {
	// contains filtered or unexported fields
}

LazyHeaders keeps default headers in insertion order and resolves callable values on first read

func NewLazyHeaders

func NewLazyHeaders(entries ...HeaderEntry) *LazyHeaders

NewLazyHeaders stores every key up front and defers callable values until a read

func (*LazyHeaders) Contains

func (h *LazyHeaders) Contains(key string) bool

Contains reports key membership without resolving any value

func (*LazyHeaders) Copy

func (h *LazyHeaders) Copy() map[string]string

Copy returns a plain resolved map

func (*LazyHeaders) Delete

func (h *LazyHeaders) Delete(key string) bool

Delete removes key after resolving, false when it was absent

func (*LazyHeaders) Equal

func (h *LazyHeaders) Equal(other any) bool

Equal compares the resolved contents with another lazy or plain header map

func (*LazyHeaders) Get

func (h *LazyHeaders) Get(key string) (string, bool)

Get returns the resolved value of key

func (*LazyHeaders) GetDefault

func (h *LazyHeaders) GetDefault(key, def string) string

GetDefault returns the resolved value of key or def when absent

func (*LazyHeaders) IOr

func (h *LazyHeaders) IOr(other map[string]string) *LazyHeaders

IOr merges other into the headers in place and returns them

func (*LazyHeaders) Items

func (h *LazyHeaders) Items() [][2]string

Items returns resolved key value pairs in insertion order

func (*LazyHeaders) Keys

func (h *LazyHeaders) Keys() []string

Keys returns the keys in insertion order after resolving

func (*LazyHeaders) Len

func (h *LazyHeaders) Len() int

Len counts the stored keys without resolving any value

func (*LazyHeaders) Or

func (h *LazyHeaders) Or(other map[string]string) map[string]string

Or returns a plain map of the resolved headers overlaid by other

func (*LazyHeaders) Pop

func (h *LazyHeaders) Pop(key string) (string, bool)

Pop removes key and returns its resolved value

func (*LazyHeaders) PopDefault

func (h *LazyHeaders) PopDefault(key, def string) string

PopDefault removes key and returns its value, def when absent

func (*LazyHeaders) PopItem

func (h *LazyHeaders) PopItem() (string, string, bool)

PopItem removes and returns the most recently inserted pair

func (*LazyHeaders) ROr

func (h *LazyHeaders) ROr(other map[string]string) map[string]string

ROr returns a plain map of other overlaid by the resolved headers

func (*LazyHeaders) Reversed

func (h *LazyHeaders) Reversed() []string

Reversed returns the keys in reverse insertion order after resolving

func (*LazyHeaders) Set

func (h *LazyHeaders) Set(key, value string)

Set stores a value after resolving, appending a new key at the end

func (*LazyHeaders) SetDefault

func (h *LazyHeaders) SetDefault(key, def string) string

SetDefault returns the value of key, storing def first when absent

func (*LazyHeaders) String

func (h *LazyHeaders) String() string

String renders the resolved headers as a Python dict literal

func (*LazyHeaders) Update

func (h *LazyHeaders) Update(pairs ...[2]string)

Update stores every pair in order after resolving

func (*LazyHeaders) Values

func (h *LazyHeaders) Values() []string

Values returns the resolved values in insertion order

type LeftCoreFeature

type LeftCoreFeature struct {
	Plugin             string
	Label              string
	InUse              func(h string, processEnv bool) bool
	Unchanged          string
	SecretEnv          []string
	PrivateEnv         []string
	Toolsets           []string
	OffPlatforms       []string
	ReplacesToolsets   []string
	Platform           string
	EnableEnv          []string
	ChannelEnvPrefixes []string
	CLI                string
	Command            string
	OldCommand         string
	OldCLI             []string
	PluginKey          string
	LeftAt             int
	Providers          []string
	ProfileEnv         []string
	LaunchEnv          []string
	Hosts              []string
	Notice             func(h string, processEnv bool) string
}

LeftCoreFeature is one feature that moved out of core into a catalog plugin

func LeftCore

func LeftCore() []LeftCoreFeature

LeftCore returns a copy of every feature row that left core

type LimitState

type LimitState struct {
	Scope    string
	ResetsAt float64
	Models   map[string]float64
}

LimitState describes a pool wide or per model rate limit a picker should mention

type LlamaServerSupervisor

type LlamaServerSupervisor struct {
	Binary     string
	ModelsDir  string
	ModelsMax  int
	Port       int
	APIKey     string
	ExtraArgs  []string
	LogPath    string
	PresetPath string
	// contains filtered or unexported fields
}

One llama-server router process owned for the life of an icebath session

func EnsureLocalRuntime

func EnsureLocalRuntime(ctx context.Context, cfg map[string]any, force bool) (*LlamaServerSupervisor, error)

Idempotent boot of the managed runtime, nil when disabled or unavailable, an error only for a failed boot

func NewLlamaServerSupervisor

func NewLlamaServerSupervisor(binary, modelsDir string, modelsMax, port int, extraArgs []string, logPath, presetPath string) (*LlamaServerSupervisor, error)

Supervisor for binary serving modelsDir, port 0 picks the stable port and empty paths take the defaults

func (*LlamaServerSupervisor) BaseURL

func (s *LlamaServerSupervisor) BaseURL() string

OpenAI compatible base URL, always the loopback IP since resolving localhost costs seconds on Windows

func (*LlamaServerSupervisor) EnsureModelReady

func (s *LlamaServerSupervisor) EnsureModelReady(modelID string, timeout time.Duration) (bool, error)

Loads a listed model when needed and proves readiness with a touch generation

func (*LlamaServerSupervisor) IsIdle

func (s *LlamaServerSupervisor) IsIdle(modelID string) bool

No processing requests and no busy slots on the given child, or on every loaded child for ""

func (*LlamaServerSupervisor) LoadModel

func (s *LlamaServerSupervisor) LoadModel(modelID string, timeout time.Duration) error

Asks the router to load one model child

func (*LlamaServerSupervisor) Models

func (s *LlamaServerSupervisor) Models(timeout time.Duration) (RouterModels, error)

Model id to status value from GET /models

func (*LlamaServerSupervisor) PrimaryModel

func (s *LlamaServerSupervisor) PrimaryModel() string

Model whose readiness a crash restart proves again, empty for none

func (*LlamaServerSupervisor) ReloadPresets

func (s *LlamaServerSupervisor) ReloadPresets() error

Has the router re-read the preset file, unloading loaded models whose flags changed

func (*LlamaServerSupervisor) SetPrimaryModel

func (s *LlamaServerSupervisor) SetPrimaryModel(modelID string)

func (*LlamaServerSupervisor) Start

func (s *LlamaServerSupervisor) Start(ctx context.Context, timeout time.Duration) error

Spawns the router, waits for health and starts the crash watchdog

func (*LlamaServerSupervisor) State

func (s *LlamaServerSupervisor) State() map[string]any

Endpoint state recorded at the last spawn

func (*LlamaServerSupervisor) Stop

func (s *LlamaServerSupervisor) Stop() error

Stops the router tree, closes the containment job and keeps the state file for a replacement to overwrite

func (*LlamaServerSupervisor) SweepIdle

func (s *LlamaServerSupervisor) SweepIdle(now *float64) []string

Unloads models idle past the threshold and returns their ids, a failed probe keeps the idle clock

func (*LlamaServerSupervisor) TouchGenerate

func (s *LlamaServerSupervisor) TouchGenerate(modelID string, timeout time.Duration) bool

Readiness proof by a temperature zero generation whose content or reasoning names the expected token

func (*LlamaServerSupervisor) UnloadModel

func (s *LlamaServerSupervisor) UnloadModel(modelID string) error

Frees a child's memory now and waits up to 15 s for it to leave the resident states

type LlamacppEndpoint

type LlamacppEndpoint struct {
	BaseURL string
	APIKey  string
}

The llamacpp alias endpoint, APIKey empty for a detected server

func ResolveLlamacppEndpoint

func ResolveLlamacppEndpoint(ctx context.Context, cfg map[string]any, h string, waitForBoot time.Duration) (*LlamacppEndpoint, error)

Managed first then detected endpoint for llamacpp aliases, waiting up to waitForBoot for a booting server

type LoadProgress

type LoadProgress struct {
	Stage   string  `json:"stage"`
	Value   float64 `json:"value"`
	Percent int     `json:"percent"`
}

LoadProgress is one model's live load stage, in stage value and composite percent

type LocalRuntimeUnavailableError

type LocalRuntimeUnavailableError struct {
	Message   string
	Retryable bool
}

LocalRuntimeUnavailableError means the selected model is the managed local runtime and its server is not serving

func (*LocalRuntimeUnavailableError) Error

func (*LocalRuntimeUnavailableError) ErrorCode

func (e *LocalRuntimeUnavailableError) ErrorCode() string

ErrorCode names the readiness probe code for the managed server being down

type LocalValidationError

type LocalValidationError struct {
	Message string
	Err     error
}

LocalValidationError marks a request the adapter refused before any transport attempt

func (*LocalValidationError) Error

func (e *LocalValidationError) Error() string

func (*LocalValidationError) Unwrap

func (e *LocalValidationError) Unwrap() error

type LockTimeoutError

type LockTimeoutError struct {
	// Lock waited for, the auth store lock when empty
	Lock     string
	LockPath string
	Hint     string
}

LockTimeoutError reports an auth store lock that could not be taken in time

func (*LockTimeoutError) Error

func (e *LockTimeoutError) Error() string

type MCPToolParam

type MCPToolParam struct {
	Name       string
	Type       string
	Required   bool
	Default    any
	HasDefault bool
}

One keyword parameter of a tool signature, Default applying when HasDefault is set and None otherwise

func MCPToolParamsFromSchema

func MCPToolParamsFromSchema(schema any) []MCPToolParam

Keyword parameters of a JSON schema, optional ones defaulting to None

type MCPToolServer

type MCPToolServer = CodexToolsServer

Stdio MCP server the codex tools bridge and icebath mcp-serve share

func NewMCPToolServer

func NewMCPToolServer(name, instructions string, in io.Reader, out io.Writer, concurrent bool) *MCPToolServer

Server with no tools yet, a concurrent one running every tool call on its own worker

type ManagedLlmStream

type ManagedLlmStream struct {
	FinalResponse  any
	OutputModified bool
	// contains filtered or unexported fields
}

Synchronous view of one Relay managed provider stream, yielding io.EOF when exhausted

func NewManagedLlmStream

func NewManagedLlmStream(ctx context.Context, request map[string]any, streamFactory func(ctx context.Context, request map[string]any) (any, error), o ManagedLlmStreamOptions) (*ManagedLlmStream, error)

Opens a provider stream managed by Relay when the session runs managed execution

func (*ManagedLlmStream) Close

func (s *ManagedLlmStream) Close() error

Closes an explicitly abandoned stream, cancelling its logical call and surfacing the first close failure

func (*ManagedLlmStream) Iter

Iterator the stream is consumed through, the stream itself

func (*ManagedLlmStream) Next

func (s *ManagedLlmStream) Next(ctx context.Context) (any, error)

Next provider or Relay chunk, io.EOF once the stream is exhausted or closed

type ManagedLlmStreamOptions

type ManagedLlmStreamOptions struct {
	SessionID                  string
	Name                       string
	ModelName                  string
	Finalizer                  func(ctx context.Context) (any, error)
	OnStreamCreated            func(ctx context.Context, raw any) error
	OnChunk                    func(ctx context.Context, chunk any) error
	ChunkAdapter               func(chunk any) any
	AcceptChunk                func(chunk any) bool
	CompletedResponsePredicate func(value any) bool
	Metadata                   map[string]any
	DeferLogicalCompletion     bool
}

Options of one Relay managed provider stream

type MemoPins

type MemoPins struct {
	Strings []string
	Touched time.Time
}

MemoPins holds an entry's pinned strings stamped with its last lookup

type MinimaxLoginArgs

type MinimaxLoginArgs struct {
	Region    string
	NoBrowser bool
	Timeout   time.Duration
}

MinimaxLoginArgs are the MiniMax login flags

type MoAArgs

type MoAArgs struct {
	Command string
	Name    string
}

MoAArgs carries the parsed icebath moa subcommand as typed and the optional preset name

type MoAExitError

type MoAExitError struct{ Message string }

MoAExitError is a moa command refusal that exits with status one after printing its message

func (*MoAExitError) Error

func (e *MoAExitError) Error() string

type MoAPresetNotFoundError

type MoAPresetNotFoundError struct{ Preset string }

MoAPresetNotFoundError is raised when a persisted MoA preset no longer exists in config

func (*MoAPresetNotFoundError) Error

func (e *MoAPresetNotFoundError) Error() string

type ModelAssignmentRejected

type ModelAssignmentRejected struct{ Msg string }

ModelAssignmentRejected is a main model pick the model switch refused, its message saying why

func (*ModelAssignmentRejected) Error

func (e *ModelAssignmentRejected) Error() string

type ModelCapabilities

type ModelCapabilities struct {
	SupportsTools     bool
	SupportsVision    *bool
	SupportsReasoning *bool
	ContextWindow     int
	MaxOutputTokens   int
	ModelFamily       string
}

ModelCapabilities is the structured capability view of a model, nil pointers mean unknown

func ModelsDevCapabilities

func ModelsDevCapabilities(ctx context.Context, provider, model string, allowNetwork bool) (ModelCapabilities, bool)

ModelsDevCapabilities returns the capability view with overrides applied, false when nothing knows the model

type ModelCredentialSource

type ModelCredentialSource interface {
	CredentialForModel(provider, model string) (Credential, bool)
	TokenBenchedForModel(provider, token, model string) bool
}

ModelCredentialSource selects a login that is not benched for the target model

type ModelDumper

type ModelDumper interface {
	ModelDump(warnings bool) any
}

ModelDumper is an SDK model whose model_dump answers its plain dict

type ModelFlagParseResult

type ModelFlagParseResult struct {
	ModelInput       string
	ExplicitProvider string
	ReasoningEffort  string
	IsGlobal         bool
	ForceRefresh     bool
	IsSession        bool
	IsOnce           bool
}

ModelFlagParseResult holds the model text and flags of one model command

func ParseModelFlagsDetailed

func ParseModelFlagsDetailed(rawArgs string) ModelFlagParseResult

ParseModelFlagsDetailed splits provider, reasoning, global, session, refresh and once flags from the model text

type ModelFlowRun

type ModelFlowRun struct {
	Ctx          context.Context
	Env          PoolEnv
	Out          io.Writer
	Config       map[string]any
	CurrentModel string
	Args         map[string]any
}

ModelFlowRun is one provider wizard invocation, the loaded config, the current model and the CLI namespace

type ModelIDNormalizer

type ModelIDNormalizer func(ctx context.Context, model, apiKey string) string

ModelIDNormalizer is a provider profile hook that returns the native id for a model or empty for generic rules

type ModelIdentity

type ModelIdentity struct {
	Vendor string
	Family string
}

ModelIdentity is the vendor slug and family prefix a short alias resolves against

type ModelProfile

type ModelProfile struct {
	Name                  string
	WeightsBytes          int64
	EmbdTableBytes        int64
	NCtxTrain             int
	Layers                []ProfileLayer
	SWAWindow             int
	MoE                   bool
	Architecture          string
	NVocab                int64
	KVScale               float64
	FFNBlockBytes         map[int]int64
	LazyBytes             int64
	WindowComputePerToken int64
	RecurrentStateBytes   int64
}

everything the context policy needs about one model

func AsLoaded

func AsLoaded(profile ModelProfile, budget HardwareBudget) ModelProfile

Profile as this machine loads it, on demand tensors counted as weights where read up front

func NewModelProfile

func NewModelProfile(name string, weightsBytes, embdTableBytes int64, nCtxTrain int, layers []ProfileLayer) ModelProfile

Profile with the default KV scale of one and an empty FFN block map

func PostureProfile

func PostureProfile(profile ModelProfile, mtpCapable, mtpPrefill bool) ModelProfile

Profile at one launch posture with window compute buffers scaled by microbatch and context count

func ProfileFromGGUF

func ProfileFromGGUF(h *GGUFHeader) (ModelProfile, error)

Profile priced from a GGUF header with the file's SWA pattern, known fractions or all full attention

func (ModelProfile) PerTokenKVF16

func (p ModelProfile) PerTokenKVF16() int64

Uncapped per token KV cost of full and SWA layers

func (ModelProfile) RecurrentLayerCount

func (p ModelProfile) RecurrentLayerCount() int

func (ModelProfile) WindowComputeBytes

func (p ModelProfile) WindowComputeBytes() int64

Compute buffer bytes per microbatch token per window token for this architecture

type ModelSelectionPrompt

type ModelSelectionPrompt struct {
	ModelIDs        []string
	Pricing         PricingTable
	ConfirmProvider string
	ConfirmBaseURL  string
	ConfirmAPIKey   string
	CurrentModel    string
	Notes           map[string]string
	Title           string
}

ModelSelectionPrompt is everything the post login model picker shows

type ModelSwitchRequest

type ModelSwitchRequest struct {
	Raw              string
	Target           string
	ExplicitProvider string
	ReasoningEffort  string
	IsGlobal         bool
	IsSession        bool
	IsOnce           bool
	ForceRefresh     bool
	Scope            string
	Errors           []string
}

ModelSwitchRequest is a fully parsed model command with its requested scope and error codes

func ParseModelSwitchArgs

func ParseModelSwitchArgs(raw string) ModelSwitchRequest

ParseModelSwitchArgs tokenizes a model command and validates flag conflicts and the reasoning level

func (ModelSwitchRequest) ErrorMessages

func (r ModelSwitchRequest) ErrorMessages() []string

ErrorMessages renders each error code through the canonical copy

func (ModelSwitchRequest) IsReset

func (r ModelSwitchRequest) IsReset() bool

IsReset reports a bare reset request that clears the session override

func (ModelSwitchRequest) ModelInput

func (r ModelSwitchRequest) ModelInput() string

ModelInput is the target text, matching the flag parse result field

type ModelSwitchResult

type ModelSwitchResult struct {
	Success              bool
	NewModel             string
	TargetProvider       string
	ProviderChanged      bool
	APIKey               string
	BaseURL              string
	APIMode              string
	RequestOverrides     map[string]any
	ErrorMessage         string
	WarningMessage       string
	ProviderLabel        string
	ResolvedViaAlias     string
	Capabilities         *ModelCapabilities
	RuntimeCapabilities  map[string]bool
	ModelInfo            *ModelsDevEntry
	IsGlobal             bool
	AliasEndpointApplied bool
}

ModelSwitchResult is the outcome of one model switch attempt

func ValidatedMainModelSelection

func ValidatedMainModelSelection(ctx context.Context, cfg map[string]any, provider, model, baseURL string) (ModelSwitchResult, error)

Main slot pick validated through the model switch against cfg, a refused pick returning ModelAssignmentRejected

type ModelVerdict

type ModelVerdict struct {
	Accepted   bool
	Persist    bool
	Recognized bool
	Message    string
}

ModelVerdict is the switch, persist and recognition outcome of a requested model, an empty Message is none

func ValidateRequestedModel

func ValidateRequestedModel(ctx context.Context, modelName, provider string, opts ValidateModelOptions) ModelVerdict

ValidateRequestedModel validates a model value for the active provider without ever rewriting the requested id

type ModelsDevEntry

type ModelsDevEntry struct {
	ID               string
	Name             string
	Family           string
	ProviderID       string
	Reasoning        bool
	ToolCall         bool
	Attachment       bool
	Temperature      bool
	StructuredOutput bool
	OpenWeights      bool
	InputModalities  []string
	OutputModalities []string
	ContextWindow    int
	MaxOutput        int
	MaxInput         int
	CostInput        float64
	CostOutput       float64
	CostCacheRead    *float64
	CostCacheWrite   *float64
	KnowledgeCutoff  string
	ReleaseDate      string
	Status           string
	Interleaved      any
	Raw              map[string]any
}

ModelsDevEntry is the full metadata of one models.dev model row

func ModelsDevModelInfo

func ModelsDevModelInfo(ctx context.Context, providerID, modelID string, allowNetwork bool) (ModelsDevEntry, bool)

ModelsDevModelInfo returns full model metadata with overrides applied, exact then case insensitive

func ModelsDevProfile

func ModelsDevProfile(ctx context.Context, provider, model string) (ModelsDevEntry, bool)

ModelsDevProfile is the hot path model lookup that never touches the network

func (ModelsDevEntry) FormatCapabilities

func (m ModelsDevEntry) FormatCapabilities() string

FormatCapabilities renders the capability flags as a comma list or basic

func (ModelsDevEntry) HasCostData

func (m ModelsDevEntry) HasCostData() bool

HasCostData reports whether either token price is known

func (ModelsDevEntry) SupportsAudioInput

func (m ModelsDevEntry) SupportsAudioInput() bool

SupportsAudioInput reports audio among the input modalities

func (ModelsDevEntry) SupportsPDF

func (m ModelsDevEntry) SupportsPDF() bool

SupportsPDF reports pdf among the input modalities

func (ModelsDevEntry) SupportsVision

func (m ModelsDevEntry) SupportsVision() bool

SupportsVision reports image input through the attachment flag or the input modalities

type ModelsDevFetchDeadlineError

type ModelsDevFetchDeadlineError struct{ Timeout time.Duration }

ModelsDevFetchDeadlineError reports a download abandoned at the whole exchange cap

func (*ModelsDevFetchDeadlineError) Error

type ModelsDevProvider

type ModelsDevProvider struct {
	ID         string
	Name       string
	Env        []string
	API        string
	Doc        string
	ModelCount int
}

ModelsDevProvider is the metadata of one models.dev provider row

func ModelsDevProviderInfo

func ModelsDevProviderInfo(ctx context.Context, providerID string, allowNetwork bool) (ModelsDevProvider, bool)

Provider metadata by icebath or models.dev id

type ModelsPayloadOptions

type ModelsPayloadOptions struct {
	ExplicitOnly               bool
	IncludeUnconfigured        bool
	PickerHints                bool
	CanonicalOrder             bool
	Pricing                    bool
	PricingCacheOnly           bool
	Capabilities               bool
	Featured                   bool
	Refresh                    bool
	ProbeCustomProviders       bool
	ProbeCurrentCustomProvider bool
	ForPicker                  bool
	MaxModels                  *int
	NonBlockingCatalogs        bool
	FastCustomProbe            *bool
}

ModelsPayloadOptions mirrors the build_models_payload keyword arguments

type ModelsProbe

type ModelsProbe struct {
	IDs             []string
	Listed          bool
	ProbedURL       string
	ResolvedBaseURL string
}

Result of a provider owned models probe, IDs nil with Listed false when the probe failed

type NamedDirectAlias

type NamedDirectAlias struct {
	Name  string
	Alias DirectAlias
}

NamedDirectAlias is one alias entry in table order

type NamedProvider

type NamedProvider = providerregistry.NamedProvider

Abstract identity every registered provider implements, the stable lowercase config key value

type NativeCompactionGate

type NativeCompactionGate struct {
	RuntimeCapability, Configured, CompressionEnabled, CheckpointRequired, TrustedProxy bool
	Model, Provider, BaseURL                                                            string
	LocalTriggerTokens, CompactThreshold                                                any
}

NativeCompactionGate is the agent state the native compaction payload gates on

type NativePreflightEstimator

type NativePreflightEstimator interface {
	EstimateNativePreflightTokens(ctx context.Context, req *Request, systemPrompt string, tools []map[string]any) (int, bool)
}

NativePreflightEstimator estimates the natively compacted Responses wire for the preflight compression check

type NonStreamWatchdogs

type NonStreamWatchdogs struct {
	IdleEnabled, TTFBEnabled               bool
	IdleTimeout, TTFBTimeout, StaleTimeout float64
}

NonStreamWatchdogs is the resolved idle, TTFB and stale fuses of one agent request

func ResolveNonstreamWatchdogs

func ResolveNonstreamWatchdogs(ctx context.Context, agent ChatCompletionAgent, apiKwargs map[string]any) (NonStreamWatchdogs, error)

Resolved idle, TTFB and stale fuses of an agent request for callers outside the package

type NvidiaGPUQuery

type NvidiaGPUQuery struct {
	GPUName        string
	TotalBytes     int64
	FreeBytes      int64
	UsedBytes      int64
	GPUUtilPercent int64
	GPUPCIID       *int64
}

One nvidia-smi reading shared by the budget probe and the hardware endpoint

func CachedNvidiaGPUQuery

func CachedNvidiaGPUQuery(ttl float64) (*NvidiaGPUQuery, error)

One nvidia-smi read cached for ttl seconds, failures included, nil when smi is absent or fails

type OAuthClient

type OAuthClient struct {
	ID              string
	AuthorizeURL    string
	TokenURL        string
	Scopes          []string
	ClientIDEnv     string
	Hosts           []string
	ClientSecretEnv string
	AuthorizeParams [][2]string
}

OAuthClient is one oauth entry of a plugin manifest holding variable names and never their values

func ParseOAuthClients

func ParseOAuthClients(manifest map[string]any) ([]OAuthClient, []string)

ParseOAuthClients reads the manifest oauth block into well formed clients and one problem per defect

func (OAuthClient) Fingerprint

func (c OAuthClient) Fingerprint() string

Fingerprint hashes every field so a grant is used only with the entry it was made for

type OAuthHealSummary

type OAuthHealSummary struct {
	Adopted        bool
	StrippedIDs    []any
	Files          []string
	ProvidersBlock bool
}

OAuthHealSummary reports one forked grant consolidation into the root store

type OAuthLoginExitError

type OAuthLoginExitError struct {
	Code int
	Err  error
}

OAuthLoginExitError carries the process exit code a failed provider login asks for

func (*OAuthLoginExitError) Error

func (e *OAuthLoginExitError) Error() string

func (*OAuthLoginExitError) Unwrap

func (e *OAuthLoginExitError) Unwrap() error

type OAuthPKCEConfig

type OAuthPKCEConfig struct {
	ClientID             string
	AuthorizeURL         string
	TokenURL             string
	Scopes               []string
	RedirectPort         int
	RedirectPath         string
	Audience             string
	ExtraAuthorizeParams map[string]string
	ExtraTokenParams     map[string]string
	AllowedHosts         []string
	TimeoutSeconds       float64
	Label                string
	// Brokered token exchange called with the grant fields instead of posting token_url
	TokenRequest func(grant map[string]string) (map[string]any, error)
}

OAuthPKCEConfig is the public client OAuth metadata a provider plugin declares, PKCE replacing any client secret

func NewOAuthPKCEConfig

func NewOAuthPKCEConfig(clientID, authorizeURL, tokenURL string) OAuthPKCEConfig

NewOAuthPKCEConfig fills the declared endpoints with the callback path and timeout defaults

type OAuthProviderFlow

type OAuthProviderFlow struct {
	ProviderID string
	Resolve    func(env PoolEnv, opts OAuthResolveOptions) (map[string]any, error)
	Status     func(env PoolEnv) map[string]any
	// Codes for which retrying the same refresh token cannot succeed
	TerminalRefreshCodes map[string]bool
	// Logout with no active provider falls back to config.yaml model.provider for these
	LogoutFromConfig bool
}

OAuthProviderFlow is the per provider OAuth plumbing keyed by provider id in OAuthProviderFlows

func (OAuthProviderFlow) IsTerminalRefreshError

func (f OAuthProviderFlow) IsTerminalRefreshError(err error) bool

IsTerminalRefreshError is true when the error is this provider's relogin required grant death

type OAuthResolveOptions

type OAuthResolveOptions struct {
	ForceRefresh        bool
	SkipExpiringRefresh bool
	ReadOnly            bool
	RefreshSkew         time.Duration
	StaleAccessToken    string
}

OAuthResolveOptions are the per call knobs an OAuth runtime credential resolver accepts

type OllamaCloudFetch

type OllamaCloudFetch struct {
	APIKey       string
	BaseURL      string
	ForceRefresh bool
	CacheOnly    bool
}

OllamaCloudFetch selects the credentials and cache policy of an Ollama Cloud catalog read

type OnePasswordApplyOptions

type OnePasswordApplyOptions struct {
	Enabled                bool
	Env                    map[string]any
	Account                string
	ServiceAccountTokenEnv string
	BinaryPath             string
	OverrideExisting       bool
	CacheTTL               float64
	HomePath               string
}

OnePasswordApplyOptions parameterize a sync apply onto the process environment

type OnePasswordFetchOptions

type OnePasswordFetchOptions struct {
	References map[string]any
	Account    string
	TokenEnv   string
	Binary     string
	BinaryPath string
	UseCache   bool
	CacheTTL   float64
	HomePath   string
	Environ    *SourceEnvironment
}

OnePasswordFetchOptions parameterize one resolution of op references

type OnePasswordSource

type OnePasswordSource struct{}

OnePasswordSource is 1Password as a mapped source

func (*OnePasswordSource) ConfigSchema

func (s *OnePasswordSource) ConfigSchema() map[string]map[string]any

func (*OnePasswordSource) Fetch

func (s *OnePasswordSource) Fetch(cfg map[string]any, homePath string, environ *SourceEnvironment) *SecretFetchResult

func (*OnePasswordSource) Spec

type OpenAIClientOptions

type OpenAIClientOptions = auxOpenAIOptions

OpenAIClientOptions are the options of one OpenAI SDK client beyond its key and base URL

type Opener

type Opener struct {
	Transport  http.RoundTripper
	TLS        *tls.Config
	Processors []RequestProcessor
	AddHeaders [][2]string
	Redirect   func(*http.Request, []*http.Request) error
	// contains filtered or unexported fields
}

Opener is a urllib OpenerDirector in Go, a transport behind default headers, request processors and a redirect policy

func (*Opener) Open

func (o *Opener) Open(req *http.Request, timeout time.Duration) (*http.Response, error)

Open sends one request through the opener under the timeout

type OpenerFactory

type OpenerFactory func(redirect *SafeCredentialRedirectHandler) RequestOpener

OpenerFactory is the explicit test seam building the opener around the redirect handler

type Origin

type Origin struct {
	Scheme string
	Host   string
	Port   int
}

Origin is the normalized scheme, hostname and effective port of a URL, Port -1 when none applies

func URLOrigin

func URLOrigin(rawURL string) (Origin, error)

URLOrigin parses a URL into its origin, erroring on a malformed port so the request fails closed

func (Origin) String

func (o Origin) String() string

String renders the origin as one comparable key

type PerModelAPIModeHook

type PerModelAPIModeHook func(model string, apiKey *string) APIMode

PerModelAPIModeHook answers the wire for one model with a key or no key, empty for the declared mode

type PhysicsRefusal

type PhysicsRefusal struct {
	NeededBytes    int64
	AvailableBytes int64
	Message        string
}

The only true refusal, weights plus floor KV exceeding VRAM plus RAM

func PhysicsCheck

func PhysicsCheck(profile ModelProfile, budget HardwareBudget, floor int, flashAttention bool, overheadBytes int64) *PhysicsRefusal

Refusal when the model at the floor window exceeds VRAM plus RAM, nil when it fits

type PickerConfigContext

type PickerConfigContext struct {
	CurrentProvider   string
	CurrentModel      string
	CurrentBaseURL    string
	UserProviders     map[string]any
	CustomProviders   []any
	ExcludedProviders []string
}

PickerConfigContext is the disk config snapshot every picker consumer reads

func LoadPickerContext

func LoadPickerContext(ctx context.Context) (PickerConfigContext, error)

LoadPickerContext reads the provider picker inputs of the active home config

func (PickerConfigContext) WithOverrides

func (pc PickerConfigContext) WithOverrides(currentProvider, currentModel, currentBaseURL string) PickerConfigContext

Copy with the non empty overrides applied so blank agent fields never clobber disk values

type PickerProvidersOptions

type PickerProvidersOptions struct {
	CurrentProvider            string
	CurrentBaseURL             string
	UserProviders              map[string]any
	CustomProviders            []any
	MaxModels                  *int
	CurrentModel               string
	IncludeMoA                 bool
	ExcludedProviders          []string
	NonBlockingCatalogs        bool
	SkipCustomProviderProbe    bool
	ProbeCurrentCustomProvider bool
}

PickerProvidersOptions mirrors the list_picker_providers keyword arguments

type PickerRadiolistOptions

type PickerRadiolistOptions struct {
	Selected      int
	CancelReturns int
	Description   string
	Searchable    bool
	SearchLabels  []string
	Headings      map[int]string
}

PickerRadiolistOptions carries the cursor start, cancel index, description, search labels and section headings

type PickerRow

type PickerRow struct {
	Kind        string
	Slug        string
	GroupID     string
	Label       string
	Description string
	Members     []string
}

PickerRow is one folded picker row, a single slug or a group of member slugs

func GroupProviders

func GroupProviders(slugs []string) []PickerRow

GroupProviders folds an ordered slug list into picker rows, a group at its first member's position

type PickerSegment

type PickerSegment struct {
	Text  string
	Style string
}

PickerSegment is one styled run of a picker row, an empty style drawing plain

type PluginAuthError

type PluginAuthError struct{ Message string }

PluginAuthError is a provider auth handler failure surfaced as a readable exit naming provider and action

func (*PluginAuthError) Error

func (e *PluginAuthError) Error() string

type PluginManagerHooks

type PluginManagerHooks struct {
	CatalogEntry    func(name string) (string, bool)
	Install         func(ctx context.Context, name string, consent bool) (map[string]any, error)
	LoadError       func(plugin string) string
	DependencyHomes func() ([]string, error)
}

PluginManagerHooks are the plugin manager entry points the plugins package installs into this package

func PluginHooks

func PluginHooks() *PluginManagerHooks

Installed plugin manager hooks, panicking when the plugins package never installed them

type PluginOAuthManifestError

type PluginOAuthManifestError struct{ Message string }

PluginOAuthManifestError is the ValueError of a malformed oauth block or an ambiguous plugin name

func (*PluginOAuthManifestError) Error

func (e *PluginOAuthManifestError) Error() string

type PluginOAuthPermissionError

type PluginOAuthPermissionError struct{ Message string }

PluginOAuthPermissionError is the PermissionError of a bearer request to a URL carrying user info

func (*PluginOAuthPermissionError) Error

func (*PluginOAuthPermissionError) Unwrap

func (e *PluginOAuthPermissionError) Unwrap() error

type PluginOAuthResolver

type PluginOAuthResolver func(rawURL string) (map[string]string, string, error)

PluginOAuthResolver returns the auth headers and request URL for one origin checked request

type PluginOrigin

type PluginOrigin struct {
	Scheme string
	Host   string
	Port   int
}

PluginOrigin is one scheme, host and port a plugin bearer may travel to

type Pool

type Pool struct {
	// contains filtered or unexported fields
}

Pool is a persistent multi credential pool for one provider with same provider failover

func EntryScopedPool

func EntryScopedPool(pool *Pool, poolKey string, entry map[string]any) *Pool

EntryScopedPool is the rows the custom entry owns, the pool itself when it owns all, nil when none

func LoadPool

func LoadPool(env PoolEnv, provider string) *Pool

LoadPool reads a provider's rows, seeds them from singletons env and config, and persists changes

func LoadRoutePool

func LoadRoutePool(env PoolEnv, provider, baseURL, requestedProvider string) *Pool

LoadRoutePool is the pool to attach when a live agent moves onto a route, a custom identity's entry scoped view or a built-in's own pool

func LoadRoutePoolWith

func LoadRoutePoolWith(env PoolEnv, load func(PoolEnv, string) *Pool, provider, baseURL, requestedProvider string) *Pool

LoadRoutePoolWith is LoadRoutePool reading every pool through load

func LoadRuntimePool

func LoadRuntimePool(env PoolEnv, provider, baseURL, requestedProvider string, snapshot map[string]any) *Pool

LoadRuntimePool is the pool for a runtime identity, entry scoped for a custom runtime

func LoadRuntimePoolWith

func LoadRuntimePoolWith(env PoolEnv, load func(PoolEnv, string) *Pool, provider, baseURL, requestedProvider string, snapshot map[string]any) *Pool

LoadRuntimePoolWith is LoadRuntimePool reading the resolved pool key through load

func NewPool

func NewPool(env PoolEnv, provider string, entries []PooledCredential) *Pool

NewPool builds a pool over entries sorted by priority

func PoolForAuxProvider

func PoolForAuxProvider(ctx context.Context, provider, poolKey string, cfg map[string]any, load func(string) *Pool) *Pool

PoolForAuxProvider loads a pool for an auxiliary read, entry scoped when the provider or its pool key names a custom entry

func (*Pool) AcquireLease

func (p *Pool) AcquireLease(credentialID string) (string, bool)

AcquireLease takes a soft lease on the given entry, else the least leased available one

func (*Pool) ActiveLeases

func (p *Pool) ActiveLeases() map[string]int

ActiveLeases copies the live lease count per credential id for tests and diagnostics

func (*Pool) AddEntry

func (p *Pool) AddEntry(entry PooledCredential) (PooledCredential, error)

AddEntry appends a credential and persists it to the profile's own store, never to a borrowed root

func (*Pool) Credential

func (p *Pool) Credential(provider string) (Credential, bool)

Credential is the pool's current login for the provider when the pool serves it

func (*Pool) CredentialForModel

func (p *Pool) CredentialForModel(provider, model string) (Credential, bool)

CredentialForModel selects a login not benched for the model

func (*Pool) Current

func (p *Pool) Current() (PooledCredential, bool)

Current is the entry selected last, if it is still in the pool

func (*Pool) CurrentID

func (p *Pool) CurrentID() string

CurrentID is the id of the entry selected last

func (*Pool) Entries

func (p *Pool) Entries() []PooledCredential

Entries is a snapshot of the rows

func (*Pool) EntryCount

func (p *Pool) EntryCount() int

EntryCount is the number of rows

func (*Pool) EntryIDForAPIKey

func (p *Pool) EntryIDForAPIKey(apiKeyHint string) string

EntryIDForAPIKey is the stable id of the runtime credential in use, the current selection when it still supplies the hint

func (*Pool) Env

func (p *Pool) Env() PoolEnv

Env is the dependency set the pool was loaded with

func (*Pool) HasAvailable

func (p *Pool) HasAvailable(model string) bool

HasAvailable reports at least one entry outside exhaustion cooldown for model

func (*Pool) HasCredentials

func (p *Pool) HasCredentials() bool

HasCredentials reports whether any row exists

func (*Pool) LiftReopenedCooldowns

func (p *Pool) LiftReopenedCooldowns(model string) bool

LiftReopenedCooldowns clears elapsed or early reopened cooldowns then reports availability

func (*Pool) LimitState

func (p *Pool) LimitState(models []string) *LimitState

LimitState reports an account wide bench or the model cooldowns blocking the given models, nil when none

func (*Pool) MarkExhaustedAndRotate

func (p *Pool) MarkExhaustedAndRotate(req RotationRequest) (PooledCredential, bool)

MarkExhaustedAndRotate benches the failed credential and returns the next usable entry

func (*Pool) MoveEntry

func (p *Pool) MoveEntry(credentialID string, priority int) (PooledCredential, bool)

MoveEntry places an entry at a clamped zero based position and persists contiguous priorities

func (*Pool) NextAvailableAt

func (p *Pool) NextAvailableAt(model string) (time.Time, bool)

NextAvailableAt is the earliest time any entry re-enters rotation, false when available now or unknown

func (*Pool) Peek

func (p *Pool) Peek() (PooledCredential, bool)

Peek is the current entry or the first available one without selecting

func (*Pool) Provider

func (p *Pool) Provider() string

Provider is the pool key this pool is scoped to

func (*Pool) Reclaim

func (p *Pool) Reclaim(credentialID, model string) (PooledCredential, bool)

Reclaim hands back the entry once its cooldown lifted without counting a request

func (*Pool) ReleaseLease

func (p *Pool) ReleaseLease(credentialID string)

ReleaseLease drops one soft lease on the entry

func (*Pool) RemoveIndex

func (p *Pool) RemoveIndex(index int) (PooledCredential, bool)

RemoveIndex drops the one based entry and renumbers priorities

func (*Pool) ResetStatus

func (p *Pool) ResetStatus(credentialID string) (PooledCredential, bool)

ResetStatus clears only the target's local error state, preserving sibling cooldowns

func (*Pool) ResetStatuses

func (p *Pool) ResetStatuses() int

ResetStatuses clears exhaustion state on every entry and returns how many were cleared

func (*Pool) ResolveTarget

func (p *Pool) ResolveTarget(target string) (int, PooledCredential, string)

ResolveTarget finds an entry by id, unique label or one based index, with the user facing error

func (*Pool) Select

func (p *Pool) Select(model string) (PooledCredential, bool)

Select picks the next usable credential for model, refreshing deferred rows then reselecting

func (*Pool) Strategy

func (p *Pool) Strategy() string

Strategy is the configured selection strategy

func (*Pool) TokenBenchedForModel

func (p *Pool) TokenBenchedForModel(provider, token, model string) bool

TokenBenchedForModel reports a model cooldown on the token

func (*Pool) TokenIsBlocked

func (p *Pool) TokenIsBlocked(token, model string) bool

TokenIsBlocked reports whether a pool cooldown blocks the token for model, unknown tokens fail open

func (*Pool) TryRefreshCurrent

func (p *Pool) TryRefreshCurrent() (PooledCredential, bool)

TryRefreshCurrent force refreshes the entry selected last

func (*Pool) TryRefreshMatching

func (p *Pool) TryRefreshMatching(apiKeyHint, credentialID string) (PooledCredential, bool)

TryRefreshMatching force refreshes the entry that supplied the failed request

type PoolCredentials

type PoolCredentials struct {
	// contains filtered or unexported fields
}

PoolCredentials is the credential source the resolver reads pooled logins through

func NewPoolCredentials

func NewPoolCredentials(env PoolEnv) *PoolCredentials

NewPoolCredentials builds a pool backed credential source over one home

func (*PoolCredentials) Credential

func (c *PoolCredentials) Credential(provider string) (Credential, bool)

Credential is the pooled login for a provider key

func (*PoolCredentials) CredentialForEntry

func (c *PoolCredentials) CredentialForEntry(poolKey string, entry map[string]any) (Credential, bool)

CredentialForEntry narrows the pool to the rows a custom entry owns before selecting

func (*PoolCredentials) CredentialForModel

func (c *PoolCredentials) CredentialForModel(provider, model string) (Credential, bool)

CredentialForModel is the pooled login not benched for model

func (*PoolCredentials) Pool

func (c *PoolCredentials) Pool(poolKey string) *Pool

Pool loads and caches the pool for a key

func (*PoolCredentials) Reload

func (c *PoolCredentials) Reload()

Reload drops every cached pool so the next read reloads from disk

func (*PoolCredentials) TokenBenchedForModel

func (c *PoolCredentials) TokenBenchedForModel(provider, token, model string) bool

TokenBenchedForModel reports a model cooldown the provider's pool holds for the token

type PoolEnv

type PoolEnv struct {
	Store   *Store
	Secrets *config.Secrets
	Scope   *SecretScope
	// Read only config, the session's frozen config when one is frozen
	Config func() map[string]any
	Log    *slog.Logger
	HTTP   *http.Client
	Ctx    context.Context
}

PoolEnv is the per home dependency set a credential pool reads and writes through

func HomePoolEnv

func HomePoolEnv(h string) PoolEnv

HomePoolEnv is the pool environment of home h for callers outside the package

type PoolPresenceSource

type PoolPresenceSource interface {
	HasPoolCredentials(provider string) bool
}

PoolPresenceSource reports whether a provider's credential pool holds any row at all

type PooledCredential

type PooledCredential struct {
	Provider          string
	ID                string
	Label             string
	AuthType          string
	Priority          int
	Source            string
	AccessToken       string
	RefreshToken      string
	LastStatus        string
	LastStatusAt      float64
	LastErrorCode     int
	LastErrorReason   string
	LastErrorMessage  string
	LastErrorResetAt  float64
	StatusClearedAt   float64
	BaseURL           string
	ExpiresAt         string
	ExpiresAtMS       int64
	LastRefresh       string
	InferenceBaseURL  string
	AgentKey          string
	AgentKeyExpiresAt string
	RequestCount      int
	ModelCooldowns    map[string]float64
	Extra             map[string]any
	// contains filtered or unexported fields
}

PooledCredential is one row of a provider credential pool

func ApplyPluginRefreshResult

func ApplyPluginRefreshResult(entry PooledCredential, result map[string]any) PooledCredential

ApplyPluginRefreshResult merges a refresh_credential return value into the row, unknown keys into extras

func PooledCredentialFromMap

func PooledCredentialFromMap(provider string, payload map[string]any) PooledCredential

PooledCredentialFromMap rehydrates a stored row, defaulting id, label, auth type, priority and source

func RecoverFailedPluginRefresh

func RecoverFailedPluginRefresh(p *Pool, entry PooledCredential, cause error, held bool) (PooledCredential, bool, bool)

RecoverFailedPluginRefresh adopts a peer rotation or quarantines a dead grant, handled false means bench

func (PooledCredential) ClearStatus

func (e PooledCredential) ClearStatus() PooledCredential

ClearStatus blanks every error field

func (PooledCredential) Clone

Clone copies the row with independent extra and cooldown maps

func (PooledCredential) ExtraString

func (e PooledCredential) ExtraString(key string) string

ExtraString reads a JSON only key such as scope or failure_reason

func (PooledCredential) FailureReason

func (e PooledCredential) FailureReason() string

FailureReason is the classifier verdict persisted with the last exhaustion

func (PooledCredential) MarkOK

MarkOK clears every error field and stamps the ok status

func (PooledCredential) RuntimeAPIKey

func (e PooledCredential) RuntimeAPIKey() string

RuntimeAPIKey is the bearer a request sends

func (PooledCredential) RuntimeBaseURL

func (e PooledCredential) RuntimeBaseURL() string

RuntimeBaseURL is the endpoint the row serves, the codex proxy override winning for every reader

func (PooledCredential) ToMap

func (e PooledCredential) ToMap() map[string]any

ToMap serializes the row for auth.json with borrowed secrets stripped

func (PooledCredential) WithExtra

func (e PooledCredential) WithExtra(key string, value any) PooledCredential

WithExtra returns a copy whose extras map has key set, or deleted when value is nil

type PreparedMainAssignment

type PreparedMainAssignment struct {
	BaseURL string
	Result  ModelSwitchResult
}

PreparedMainAssignment is a validated main slot pick computed outside the config mutation lock

type PresetEntry

type PresetEntry struct {
	ModelID string
	Window  int
	Spilled bool
	Refusal string
	Keys    map[string]string
	Order   []string
}

Launch decision for one staged model, Order lists Keys in INI order

func GeneratePresets

func GeneratePresets(modelsDir string, budget HardwareBudget, presetPath string, mtpCapable map[string]bool,
	live *HardwareBudget, residents int, engineTag string) ([]*PresetEntry, error)

Plans every staged model and writes one INI where refused models get no section

func PlanPresets

func PlanPresets(modelsDir string, budget HardwareBudget, mtpCapable map[string]bool, live *HardwareBudget,
	residents int, engineTag string) ([]*PresetEntry, error)

Launch decision of every staged model with unreadable headers skipped

func PresetForModel

func PresetForModel(gguf string, budget HardwareBudget, mtpCapable map[string]bool, requestedWindow int,
	live *HardwareBudget, residents int, engineTag string) (*PresetEntry, error)

Launch decision for one staged model, nil with a nil error when its header is unreadable

type PricingEntry

type PricingEntry struct {
	InputCostPerMillion           *big.Rat
	OutputCostPerMillion          *big.Rat
	CacheReadCostPerMillion       *big.Rat
	CacheWriteCostPerMillion      *big.Rat
	RequestCost                   *big.Rat
	Source                        string
	SourceURL                     string
	PricingVersion                string
	FetchedAt                     time.Time
	TierThresholdTokens           int
	HasTier                       bool
	InputCostPerMillionAbove      *big.Rat
	OutputCostPerMillionAbove     *big.Rat
	CacheReadCostPerMillionAbove  *big.Rat
	CacheWriteCostPerMillionAbove *big.Rat
}

PricingEntry is one rate card row in USD per million tokens with optional whole request tiering

func GetPricingEntry

func GetPricingEntry(ctx context.Context, modelName, provider, baseURL, apiKey string) (PricingEntry, bool)

GetPricingEntry resolves the rate card for a model route from snapshot, endpoint metadata or models.dev

type PricingFetchOptions

type PricingFetchOptions struct {
	APIKey       string
	BaseURL      string
	Timeout      time.Duration
	ForceRefresh bool
	CacheTTL     time.Duration
}

PricingFetchOptions control one OpenRouter compatible pricing fetch

type PricingTable

type PricingTable = map[string]map[string]any

PricingTable maps model id to its picker shaped pricing row

func FetchAIGatewayPricing

func FetchAIGatewayPricing(timeout time.Duration, forceRefresh bool) PricingTable

FetchAIGatewayPricing reads Vercel AI Gateway pricing translating input and output to prompt and completion

func FetchModelsWithPricing

func FetchModelsWithPricing(ctx context.Context, opts PricingFetchOptions) PricingTable

FetchModelsWithPricing reads /v1/models pricing cached per base URL and per credential

func GetPricingForProvider

func GetPricingForProvider(ctx context.Context, provider, baseURL string, forceRefresh, cachedOnly bool) PricingTable

GetPricingForProvider returns live pricing for the providers that publish it, empty for everything else

type ProbeResult

type ProbeResult struct {
	Models           []string
	Found            bool
	ProbedURL        string
	ResolvedBaseURL  string
	SuggestedBaseURL string
	UsedFallback     bool
}

ProbeResult describes one models endpoint probe

func ProbeAPIModels

func ProbeAPIModels(ctx context.Context, apiKey, baseURL string, timeout time.Duration, apiMode string, requestHeaders map[string]string) ProbeResult

ProbeAPIModels probes a models endpoint at the base then its v1 twin, anthropic mode sends x-api-key

type Profile

type Profile struct {
	Name                       string
	DisplayName                string
	Description                string
	SignupURL                  string
	BaseURL                    string
	BaseURLEnv                 string
	ModelsURL                  string
	Mode                       APIMode
	Auth                       AuthKind
	AuthType                   string
	KeyEnv                     []string
	Aliases                    []string
	DefaultModel               string
	FallbackModels             []string
	Headers                    map[string]string
	Local                      bool
	Aggregator                 bool
	Hidden                     bool
	ModelListing               bool
	HealthCheck                bool
	Vision                     bool
	VisionToolMessages         bool
	OmitTemperature            bool
	DefaultMaxTokens           int
	UnsupportedResponseFormats []string
	ModelsDevID                string
	Hostnames                  []string
	PerModelMode               func(model string) APIMode
	AmbientCredentials         bool

	SupportsStreaming          *bool
	SupportsPromptCacheKey     bool
	NativeReasoningDetailsType string
	ProcessCommand             string
	ProcessArgs                []string
	ProcessCommandEnvVars      []string
	ProcessArgsEnvVar          string
	ModelAliases               map[string]string
	Hostname                   string
	LazyHeaders                *LazyHeaders
	FixedTemperature           *float64
	DefaultAuxModel            string
	ModelCapabilities          map[string]map[string]any
	AccountCard                map[string]string
	MetadataHostnames          []string
	MessageCarrierOpaque       string
	MessageCarrierText         string
	ReplaysToolCallSignatures  bool
	StaticModels               []string
	CatalogCredentialFiles     []string
	PickerAfter                string
	PickerGroup                []string
	CatalogAliases             bool
	Overlay                    *IcebathOverlay
	OverlayAliases             []string
	RegistryAuthType           string
	RegistryAfter              string
	PortalBaseURL              string
	ClientID                   string
	Scope                      string
	Extra                      map[string]any

	// Responses wire flags stored so the zero value keeps the upstream defaults
	ResponsesDropReplayItemIDs       bool
	ResponsesOmitPromptCacheKey      bool
	ResponsesIssuer                  string
	ResponsesDistrustCompletedStatus bool
	ResponsesNoNativeCompaction      bool
	ResponsesReasoningFromProfile    bool

	AuthHandler           func(action string, args []string, provider string) (bool, error)
	RefreshCredential     func(entry PooledCredential) (map[string]any, error)
	ClassifyAPIError      ClassifierHook
	AccountStatus         func(ctx context.Context) (any, error)
	StartDeviceLogin      func(ctx context.Context) (any, error)
	PollDeviceLogin       func(ctx context.Context, state any) (any, error)
	SaveDeviceLogin       func(ctx context.Context, result any) error
	ModelSetupFlow        func(ctx context.Context, cfg any, currentModel string, args any) (any, error)
	SetupReasoningEfforts func(model string) any
	PickerCatalog         func(ctx context.Context, forceRefresh bool) ([]string, bool)

	// Hook overrides, a nil hook runs the upstream default body
	FetchAccountUsageHook               func(ctx context.Context, baseURL, apiKey string) (*AccountUsageSnapshot, error)
	ResolveAuxModelHook                 func(ctx context.Context, vision bool) string
	GetHostnameHook                     func() string
	PrepareMessagesHook                 func(messages []map[string]any) []map[string]any
	BuildExtraBodyHook                  func(sessionID string, context map[string]any) *pyjson.Object
	DefaultReasoningConfigHook          func(model string) *Reasoning
	BuildAPIKwargsExtrasHook            func(reasoning *Reasoning, context map[string]any) (*pyjson.Object, map[string]any)
	BuildClientKwargsExtrasHook         func(context map[string]any) map[string]any
	DefaultVisionModelHook              func(ctx context.Context) string
	GetModelContextLengthHook           ProfileContextLengthHook
	GetUsageCostHook                    UsageCostHook
	GetMaxTokensHook                    func(model string) int
	SupportedReasoningEffortsHook       func(ctx context.Context, model string) ([]string, bool, error)
	APIModeForModelHook                 PerModelAPIModeHook
	ClientHeadersHook                   func(baseURL, apiKey string, hasImages bool) map[string]string
	RequestHeadersHook                  func(baseURL, model string, userInitiated bool) map[string]string
	MaxTokensParamHook                  func(baseURL, model string) string
	ListedHook                          func(ctx context.Context) (bool, error)
	CreateClientHook                    func(ctx context.Context, clientKwargs map[string]any) (Client, error)
	SetupStatusHook                     func(ctx context.Context, kwargs map[string]any) (map[string]any, error)
	DiscoverModelsHook                  func(ctx context.Context, kwargs map[string]any) ([]map[string]any, error)
	FetchModelsHook                     func(ctx context.Context, apiKey, baseURL string, timeout time.Duration) ([]string, bool)
	LiveContextLengthHook               ProfileLiveContextLengthHook
	NormalizeModelIDHook                ModelIDNormalizer
	ResolveAPIKeySecretHook             APIKeySecretResolver
	RuntimeBaseURLHook                  RuntimeBaseURLResolver
	PreparePoolEntryHook                func(ctx context.Context, entry *PooledCredential, apiKey string) string
	SeedPoolCredentialsHook             func(ctx context.Context, suppressedSources map[string]bool, explicitlyConfigured bool) []map[string]any
	RemoveCredentialSourceHook          func(source string) ([]string, []string, bool)
	RefreshRuntimeCredentialsHook       func(ctx context.Context, reason string) (apiKey, baseURL string, ok bool, err error)
	IsStaleCredentialErrorHook          func(statusCode int, message string) bool
	CredentialRefreshNoticeHook         func(reason string) string
	RequestRejectionHintHook            func(statusCode int, baseURL string) []string
	ExternalAuthEvidenceHook            func(ctx context.Context) (verified bool, source string, ok bool)
	MissingCredentialsHintHook          func() any
	ReasoningPayloadHook                func(model string, r Reasoning, baseURL string) map[string]any
	ReplayMessageCarriersHook           func(values map[string]any, model, baseURL string) map[string]any
	ReplaysFunctionThoughtSignatureHook func(model, baseURL string) bool
	ProbeModelsHook                     func(ctx context.Context, baseURL, apiKey string, timeout time.Duration) *ModelsProbe
	InvalidateCatalogCacheHook          func()
}

Profile describes one built in inference provider

func BundledProfiles

func BundledProfiles() []Profile

BundledProfiles returns every bundled profile once, the last registration of a name winning, without config or discovery

func CanonicalRegistryRows

func CanonicalRegistryRows(ctx context.Context) []*Profile

CanonicalRegistryRows is the PROVIDER_REGISTRY values of the bound home for callers outside the package

func GetProviderProfile

func GetProviderProfile(ctx context.Context, name string) (Profile, bool)

GetProviderProfile looks a provider profile up by name or alias in the bound home

func ListProviders

func ListProviders(ctx context.Context) []Profile

ListProviders returns every registered profile once, the bound home's plugins shadowing process wide ones

func ProfileFor

func ProfileFor(name string) (Profile, bool)

ProfileFor resolves a provider id or alias to its registry row, else to its registered profile

func ProfileForHost

func ProfileForHost(ctx context.Context, rawURL string, metadata bool) (Profile, bool)

ProfileForHost returns the registered profile whose hostnames claim the url host, metadata adding metadata hostnames

func Profiles

func Profiles() []Profile

Profiles returns the registry rows in priority order followed by registered profiles without a row

func RefreshRouteProfiles

func RefreshRouteProfiles(ctx context.Context, providerName, baseURL string) []*Profile

Profiles overriding the runtime credential refresh for the route

func RegisteredProfileForHost

func RegisteredProfileForHost(ctx context.Context, rawURL string, metadata bool) *Profile

Registry owned profile claiming the url host, one identity per registration so per profile hook memos hold

func RegistryRow

func RegistryRow(ctx context.Context, key string) *Profile

Registry row of the bound home stored under one key, nil when the key is absent

func (Profile) APIModeForModel

func (p Profile) APIModeForModel(model string, apiKey *string) APIMode

APIModeForModel returns the per model wire for a key or no key, empty for the profile mode

func (Profile) BuildAPIKwargsExtras

func (p Profile) BuildAPIKwargsExtras(reasoning *Reasoning, context map[string]any) (*pyjson.Object, map[string]any)

BuildAPIKwargsExtras returns extra_body and top level request fields, both empty by default

func (Profile) BuildClientKwargsExtras

func (p Profile) BuildClientKwargsExtras(context map[string]any) map[string]any

BuildClientKwargsExtras returns client constructor extras, empty by default

func (Profile) BuildExtraBody

func (p Profile) BuildExtraBody(sessionID string, context map[string]any) *pyjson.Object

BuildExtraBody returns provider specific extra_body fields, empty by default

func (Profile) ClientHeaders

func (p Profile) ClientHeaders(baseURL, apiKey string, hasImages bool) map[string]string

ClientHeaders returns client headers for the endpoint, nil for the default headers

func (Profile) CreateClient

func (p Profile) CreateClient(ctx context.Context, clientKwargs map[string]any) (Client, error)

CreateClient returns a provider specific client, nil for the standard construction path

func (Profile) CredentialRefreshNotice

func (p Profile) CredentialRefreshNotice(reason string) string

CredentialRefreshNotice returns the status line after a refresh, empty for the generic wording

func (Profile) DefaultHeaders

func (p Profile) DefaultHeaders() map[string]string

Resolved default headers, the lazy map winning over the plain one when set

func (Profile) DefaultReasoningConfig

func (p Profile) DefaultReasoningConfig(model string) *Reasoning

DefaultReasoningConfig returns the reasoning config applied when the user set none

func (Profile) DefaultVisionModel

func (p Profile) DefaultVisionModel(ctx context.Context) string

DefaultVisionModel returns the provider vision model, empty for none

func (Profile) DiscoverModels

func (p Profile) DiscoverModels(ctx context.Context, kwargs map[string]any) ([]map[string]any, error)

DiscoverModels returns the account's live picker rows, nil to fall back to the fallback models

func (Profile) ExternalAuthEvidence

func (p Profile) ExternalAuthEvidence(ctx context.Context) (bool, string, bool)

ExternalAuthEvidence returns subprocess free login evidence, false when the binary decides

func (Profile) FetchAccountUsage

func (p Profile) FetchAccountUsage(ctx context.Context, baseURL, apiKey string) (*AccountUsageSnapshot, error)

FetchAccountUsage returns the provider account usage snapshot, nil when the profile reports none

func (Profile) FetchModels

func (p Profile) FetchModels(ctx context.Context, apiKey, baseURL string, timeout time.Duration) ([]string, bool)

FetchModels lists live model ids from the models endpoint, false when the fetch failed or listing is off

func (Profile) GetHostname

func (p Profile) GetHostname() string

GetHostname returns the declared hostname, else the base url host, else empty

func (Profile) GetMaxTokens

func (p Profile) GetMaxTokens(model string) int

GetMaxTokens returns the output cap for a model, the profile default when not overridden

func (Profile) GetModelContextLength

func (p Profile) GetModelContextLength(model string) int

GetModelContextLength returns the provider declared context window, zero for unknown

func (Profile) GetUsageCost

func (p Profile) GetUsageCost(model string, usage CanonicalUsage) (CostResult, bool)

GetUsageCost prices usage with the provider's own table, false for the generic pricing

func (Profile) InvalidateCatalogCache

func (p Profile) InvalidateCatalogCache()

InvalidateCatalogCache drops in process catalog memos, nothing by default

func (Profile) KeyEnvNames

func (p Profile) KeyEnvNames() []string

KeyEnvNames returns the API key env names without URL shaped entries

func (Profile) Label

func (p Profile) Label() string

Label returns the human readable provider name

func (Profile) Listed

func (p Profile) Listed(ctx context.Context) (bool, error)

Listed reports whether discovery surfaces may offer the provider, hidden ones once a pool row exists

func (Profile) LiveContextLength

func (p Profile) LiveContextLength(ctx context.Context, model, apiKey, baseURL string) int

LiveContextLength returns the context window from the live credentialed catalog, zero for none

func (Profile) MaxTokensParam

func (p Profile) MaxTokensParam(baseURL, model string) string

MaxTokensParam names the output cap field, empty for the transport default

func (Profile) MissingCredentialsHint

func (p Profile) MissingCredentialsHint() any

MissingCredentialsHint returns the hook's answer for missing credential messages, nil for none

func (Profile) ModelAliasMap

func (p Profile) ModelAliasMap() map[string]string

ModelAliasMap returns the provider native model alias table

func (Profile) NormalizeModelID

func (p Profile) NormalizeModelID(ctx context.Context, model, apiKey string) string

NormalizeModelID returns the provider native id, empty for the generic normalization

func (Profile) PrepareMessages

func (p Profile) PrepareMessages(messages []map[string]any) []map[string]any

PrepareMessages rewrites outgoing messages, unchanged by default

func (Profile) PreparePoolEntry

func (p Profile) PreparePoolEntry(ctx context.Context, entry *PooledCredential, apiKey string) string

PreparePoolEntry turns the selected pool row secret into the runtime key, unchanged by default

func (Profile) ProbeModels

func (p Profile) ProbeModels(ctx context.Context, baseURL, apiKey string, timeout time.Duration) *ModelsProbe

ProbeModels answers a models probe from the provider catalog, nil for the generic HTTP probe

func (Profile) ReasoningPayload

func (p Profile) ReasoningPayload(model string, r Reasoning, baseURL string) map[string]any

ReasoningPayload returns the verbatim reasoning object the endpoint takes, nil for none

func (Profile) RefreshRuntimeCredentials

func (p Profile) RefreshRuntimeCredentials(ctx context.Context, reason string) (string, string, bool, error)

RefreshRuntimeCredentials re-mints the live client key and base url, false when nothing fresher exists

func (Profile) RemoveCredentialSource

func (p Profile) RemoveCredentialSource(source string) ([]string, []string, bool)

RemoveCredentialSource returns sources to suppress and hints, false for the generic removal

func (Profile) ReplayMessageCarriers

func (p Profile) ReplayMessageCarriers(values map[string]any, model, baseURL string) map[string]any

ReplayMessageCarriers returns captured carriers to put back on a replayed assistant message

func (Profile) ReplaysFunctionThoughtSignature

func (p Profile) ReplaysFunctionThoughtSignature(model, baseURL string) bool

ReplaysFunctionThoughtSignature reports whether replayed tool calls keep function thought signatures

func (Profile) RequestHeaders

func (p Profile) RequestHeaders(baseURL, model string, userInitiated bool) map[string]string

RequestHeaders returns per request headers, empty by default

func (Profile) RequestRejectionHint

func (p Profile) RequestRejectionHint(statusCode int, baseURL string) []string

RequestRejectionHint returns lines explaining an endpoint's hard rejection of any route

func (Profile) ResolveAPIKeySecret

func (p Profile) ResolveAPIKeySecret(ctx context.Context) (string, string, bool)

ResolveAPIKeySecret returns the provider owned runtime key and source, false for the generic ladder

func (Profile) ResolveAuxModel

func (p Profile) ResolveAuxModel(ctx context.Context, vision bool) string

ResolveAuxModel returns the cheap auxiliary model, empty for the generic choice

func (Profile) ResponsesIssuerKind

func (p Profile) ResponsesIssuerKind() string

ResponsesIssuerKind is the persisted stamp for encrypted reasoning minted here, empty means URL derived

func (Profile) ResponsesNativeCompaction

func (p Profile) ResponsesNativeCompaction() bool

ResponsesNativeCompaction is false when context_management must never be sent

func (Profile) ResponsesProfileReasoning

func (p Profile) ResponsesProfileReasoning() bool

ResponsesProfileReasoning is true when reasoning comes from the profile payload plus summary without include

func (Profile) ResponsesPromptCacheKey

func (p Profile) ResponsesPromptCacheKey() bool

ResponsesPromptCacheKey reports whether the Responses body carries prompt_cache_key

func (Profile) ResponsesReplayItemIDs

func (p Profile) ResponsesReplayItemIDs() bool

ResponsesReplayItemIDs reports whether replayed Responses message items keep their id

func (Profile) ResponsesTrustsCompletedStatus

func (p Profile) ResponsesTrustsCompletedStatus() bool

ResponsesTrustsCompletedStatus is false when a reasoning only completed response continues

func (Profile) RuntimeBaseURL

func (p Profile) RuntimeBaseURL(ctx context.Context, apiKey, def, envURL string) string

RuntimeBaseURL returns the credential derived base url, empty for the env or default url

func (Profile) SeedPoolCredentials

func (p Profile) SeedPoolCredentials(ctx context.Context, suppressedSources map[string]bool, explicitlyConfigured bool) []map[string]any

SeedPoolCredentials returns rows the provider seeds itself, nil keeps generic env seeding

func (Profile) SetupStatus

func (p Profile) SetupStatus(ctx context.Context, kwargs map[string]any) (map[string]any, error)

SetupStatus returns the external process login status, nil when there is nothing to report

func (Profile) SupportedReasoningEfforts

func (p Profile) SupportedReasoningEfforts(ctx context.Context, model string) ([]string, bool, error)

SupportedReasoningEfforts returns the efforts the model accepts, false when the profile declares none

func (Profile) TemperatureOverride

func (p Profile) TemperatureOverride() (value *float64, omit bool)

Fixed temperature of the profile, omit true for the server managed sentinel

type ProfileContextLengthHook

type ProfileContextLengthHook func(model string) int

ProfileContextLengthHook is a profile qualified context bound, zero declines

type ProfileLayer

type ProfileLayer struct {
	Kind          LayerKind
	KVBytesPerTok int64
}

one layer's kind and f16 KV bytes per token

type ProfileLiveContextLengthHook

type ProfileLiveContextLengthHook func(ctx context.Context, model, apiKey, baseURL string) int

ProfileLiveContextLengthHook reads a profile's credentialed live catalog, zero declines

type PromptCachePlanOptions

type PromptCachePlanOptions struct {
	TTL                   string
	NativeAnthropic       bool
	StaticSystemPrefix    string
	DirectNativeToolCache bool
	ToolPartMarkers       bool
}

Cache layout options of one resolved request destination

type PromptReadingClock

type PromptReadingClock struct {
	Seconds float64
	// contains filtered or unexported fields
}

Time llama server spends reading the prompt, counted only for chunks reporting new tokens read

func NewPromptReadingClock

func NewPromptReadingClock(started time.Time) *PromptReadingClock

Reading clock whose first stretch starts at the given instant

func (*PromptReadingClock) Tick

func (c *PromptReadingClock) Tick(ctx context.Context, progress map[string]any) bool

Counts reading up to this progress chunk and tells the context hook, false when nothing new was read

type ProviderBase

type ProviderBase interface {
	NamedProvider
	DisplayName() string
	GetSetupSchema() map[string]any
}

Identity and icebath tools picker metadata common to every pluggable backend provider

type ProviderClientOptions

type ProviderClientOptions struct {
	AsyncMode       bool
	RawCodex        bool
	ExplicitBaseURL string
	ExplicitAPIKey  any
	APIMode         string
	MainRuntime     map[string]any
	IsVision        bool
	Task            string
}

Arguments of resolve_provider_client beyond provider and model

type ProviderClientResolver

type ProviderClientResolver func(ctx context.Context, provider, model string, opts ProviderClientOptions) (AuxClient, string, error)

ProviderClientResolver builds the client and model of a provider, the router a route entry resolves through

type ProviderCredentialsExhaustedError

type ProviderCredentialsExhaustedError struct {
	Message  string
	Provider string
}

ProviderCredentialsExhaustedError reports an explicit provider whose credential pool is fully exhausted

func (*ProviderCredentialsExhaustedError) Error

type ProviderDef

type ProviderDef struct {
	ID           string
	Name         string
	Transport    string
	KeyEnv       []string
	BaseURL      string
	BaseURLEnv   string
	IsAggregator bool
	AuthType     string
	Doc          string
	Source       string
}

ProviderDef is a resolved provider merged from models.dev, the overlays, plugin profiles and user config

func GetProviderDef

func GetProviderDef(ctx context.Context, name string, allowNetwork bool) *ProviderDef

GetProviderDef looks up a built in provider by id or alias, nil for an unknown or left core provider

func ResolveCustomProvider

func ResolveCustomProvider(name string, customProviders []any) *ProviderDef

Provider definition a name selects from the legacy custom_providers list

func ResolveProviderFull

func ResolveProviderFull(ctx context.Context, name string, userProviders map[string]any, customProviders []any) *ProviderDef

ResolveProviderFull walks user providers, lossy registry ids, built ins, custom providers, llamacpp, models.dev, profiles

type ProviderDefaults

type ProviderDefaults struct {
	Self ProviderBase
}

Embeddable ProviderBase defaults dispatching through Self, the outer provider that supplies Name

func (ProviderDefaults) DisplayName

func (d ProviderDefaults) DisplayName() string

Label shown in icebath tools, the provider name

func (ProviderDefaults) GetSetupSchema

func (d ProviderDefaults) GetSetupSchema() map[string]any

Picker row naming the provider by its display name with no badge, tag or env vars

type ProviderDescriptor

type ProviderDescriptor struct {
	Slug          string
	Label         string
	Description   string
	AuthType      string
	OAuth         bool
	APIKeyEnvVars []string
	BaseURLEnvVar string
	SignupURL     string
	Order         int
}

ProviderDescriptor is one provider as every surface sees it

func ProviderCatalog

func ProviderCatalog() []ProviderDescriptor

ProviderCatalog returns one descriptor per listed canonical provider with registry and profile fallbacks

type ProviderEnvCredentialRemoval

type ProviderEnvCredentialRemoval struct {
	OK             bool
	Key            string
	Removed        bool
	PoolPruned     []string
	Providers      []string
	ConfigScrubbed []string
	Found          bool
}

ProviderEnvCredentialRemoval is the outcome of removing a provider key from every store that held it

func RemoveProviderEnvCredential

func RemoveProviderEnvCredential(ctx context.Context, h, envVar string) (ProviderEnvCredentialRemoval, error)

RemoveProviderEnvCredential removes the key from .env and the process env, the pool, the model cache and config mirrors

type ProviderEnvCredentialSave

type ProviderEnvCredentialSave struct {
	OK            bool
	Key           string
	ConfigUpdates []string
}

ProviderEnvCredentialSave is the outcome of saving a provider key, naming the config mirrors rotated with it

func SaveProviderEnvCredential

func SaveProviderEnvCredential(ctx context.Context, h, envVar, value string) (ProviderEnvCredentialSave, error)

SaveProviderEnvCredential writes the key to .env, rotates config mirrors of the old value, lifts suppression and seeds the pool

type ProviderGroup

type ProviderGroup struct {
	ID          string
	Label       string
	Description string
	Members     []string
}

ProviderGroup folds several slugs of one vendor under a single interactive picker row

func ProviderGroups

func ProviderGroups() []ProviderGroup

ProviderGroups returns the display groups in declaration order

type ProviderHookFailureScope

type ProviderHookFailureScope interface {
	ProviderHookFailures() map[string]bool
}

ProviderHookFailureScope is a session scope that keeps its own failed profile hooks until the session resets

type ProviderNotConfiguredError

type ProviderNotConfiguredError struct{ Message string }

ProviderNotConfiguredError reports that agent init found no usable inference provider

func (*ProviderNotConfiguredError) Error

type ProviderNotSignedInError

type ProviderNotSignedInError struct{ Message string }

ProviderNotSignedInError is raised when this profile has no usable sign in for the provider

func (*ProviderNotSignedInError) Error

func (e *ProviderNotSignedInError) Error() string

type ProviderProfileHooks

type ProviderProfileHooks struct {
	// Rotates a pooled OAuth row, returning the rotated fields or nothing when it could not
	RefreshCredential func(entry PooledCredential) (map[string]any, error)
	// Rows the profile seeds itself from ambient tokens it validates or exchanges
	SeedPoolCredentials func(ctx context.Context, suppressedSources map[string]bool, explicitlyConfigured bool) []map[string]any
	// Source variants and hints the profile claims for a removal, nil when it does not claim the source
	RemoveCredentialSource func(source string) ([]string, []string, bool)
	// Owns an icebath auth action, true when core prints nothing more
	AuthHandler func(action string, args []string, provider string) (bool, error)
}

ProviderProfileHooks are the optional credential hooks a model provider plugin profile ships

type ProviderRegistry

type ProviderRegistry[P NamedProvider] = providerregistry.Registry[P]

Global and per profile scope provider maps with plugin snapshot and restore support

func NewProviderRegistry

func NewProviderRegistry[P NamedProvider](opts ProviderRegistryOptions) *ProviderRegistry[P]

Registry for providers of type P, an all uppercase label keeping its case in log lines

type ProviderRegistryAPI

type ProviderRegistryAPI[P NamedProvider] = providerregistry.API[P]

Historical module level API of a provider registry module plus its providers, scoped providers and lock test hooks

type ProviderRegistryGeneration

type ProviderRegistryGeneration = providerregistry.Generation

Cache fingerprint of a registry, the global generation and the active scope generation

type ProviderRegistryOptions

type ProviderRegistryOptions = providerregistry.Options

Construction options of a provider registry, Normalize defaulting to whitespace stripping

type ProviderRequestOptions

type ProviderRequestOptions struct {
	JSON    any
	Headers map[string]string
	// Zero is the 30 second default and a negative value waits without a timeout
	Timeout time.Duration
	// Directory of the calling plugin as the plugin host loaded it
	PluginDir string
}

ProviderRequestOptions carries the JSON body, headers, timeout and calling plugin of a signed in request

type ProviderRequestPermissionError

type ProviderRequestPermissionError struct{ Message string }

ProviderRequestPermissionError is the PermissionError of a refused caller, provider or origin

func (*ProviderRequestPermissionError) Error

func (*ProviderRequestPermissionError) Unwrap

type ProviderResponse

type ProviderResponse struct {
	Status  int
	Headers map[string]string
	Body    []byte
}

ProviderResponse is the status, lowercased headers and body of a signed in request, never its credential

func CredentialedProviderRequest

func CredentialedProviderRequest(provider, method, rawURL string, opts ProviderRequestOptions) (*ProviderResponse, error)

CredentialedProviderRequest sends method and URL with the calling plugin's provider sign in attached by Icebath

type ProviderStreamError

type ProviderStreamError struct {
	StatusCode int
	Body       map[string]any
	RawText    string
	Headers    http.Header
}

ProviderStreamError is an API error a provider encoded inside streamed content

func (*ProviderStreamError) BodyText

func (e *ProviderStreamError) BodyText() string

Body as JSON text for classification

func (*ProviderStreamError) Code

func (e *ProviderStreamError) Code() string

Code of the error object carried by the body

func (*ProviderStreamError) Error

func (e *ProviderStreamError) Error() string

func (*ProviderStreamError) PyTypeName

func (e *ProviderStreamError) PyTypeName() string

Python class the stream helper raises, a plain Exception subclass

func (*ProviderStreamError) ResponseHeaders

func (e *ProviderStreamError) ResponseHeaders() http.Header

ResponseHeaders exposes the stream response headers for reset and welcome tier parsing

type ProviderTxn

type ProviderTxn struct {
	Data       AuthData
	State      map[string]any
	SourcePath string
	// contains filtered or unexported fields
}

ProviderTxn is one locked provider state transaction

func (*ProviderTxn) SaveState

func (tx *ProviderTxn) SaveState(state map[string]any) error

SaveState persists refreshed provider state back to the store it came from without changing the active provider

type ProviderTypeError

type ProviderTypeError = providerregistry.ProviderTypeError

Python TypeError a provider registry raises for an object that is not an instance of its provider class

type ProviderWriteHook

type ProviderWriteHook func(providerID string, previous, next map[string]any) error

ProviderWriteHook observes every provider state replacement so guest handoff records can be kept

type QuantVariant

type QuantVariant struct {
	Quant     string
	Files     []AssetFile
	Validated bool
	LazyBytes int64
}

One downloadable build whose first file is the load target

func (QuantVariant) ModelID

func (v QuantVariant) ModelID() string

Model id of the first file stem with split part suffixes removed

func (QuantVariant) SizeBytes

func (v QuantVariant) SizeBytes() int64

func (QuantVariant) WeightsBytes

func (v QuantVariant) WeightsBytes() int64

Pre download weights estimate, file bytes less the tensors the engine reads on demand

type RateLimitBucket

type RateLimitBucket struct {
	Limit        int
	Remaining    int
	ResetSeconds float64
	CapturedAt   time.Time
}

RateLimitBucket is one rate limit window such as requests per minute

func (RateLimitBucket) RemainingSecondsNow

func (b RateLimitBucket) RemainingSecondsNow(now time.Time) float64

RemainingSecondsNow estimates seconds until reset adjusted for time since capture

func (RateLimitBucket) UsagePct

func (b RateLimitBucket) UsagePct() float64

UsagePct is the consumed percentage or zero without a limit

func (RateLimitBucket) Used

func (b RateLimitBucket) Used() int

Used is the consumed share of the window clamped at zero

type RateLimitState

type RateLimitState struct {
	RequestsMin  RateLimitBucket
	RequestsHour RateLimitBucket
	TokensMin    RateLimitBucket
	TokensHour   RateLimitBucket
	CapturedAt   time.Time
	Provider     string
}

RateLimitState is the full rate limit picture parsed from response headers

func ParseRateLimitHeaders

func ParseRateLimitHeaders(h http.Header, provider string, now time.Time) *RateLimitState

ParseRateLimitHeaders reads the four x-ratelimit windows or returns nil when none are present

func (*RateLimitState) AgeSeconds

func (s *RateLimitState) AgeSeconds(now time.Time) float64

AgeSeconds is the time since capture or infinity without data

func (*RateLimitState) HasData

func (s *RateLimitState) HasData() bool

HasData reports whether any headers were ever captured

type Reasoning

type Reasoning struct {
	Effort            string
	BudgetTokens      int
	Enabled           *bool
	Summary           string
	IncludeInResponse bool
}

Reasoning controls thinking budget and effort for reasoning models

func ReasoningOfConfig

func ReasoningOfConfig(rc map[string]any) *Reasoning

ReasoningOfConfig is the hook reasoning value of a reasoning config dict, nil when the config is unset

type ReasoningCapabilities

type ReasoningCapabilities struct {
	SupportsReasoning bool
	// Effort levels the route accepts, nil when the catalog lists none
	SupportedEfforts []string
	Mandatory        bool
}

ReasoningCapabilities is one model's advertised reasoning support from an OpenRouter schema catalog

func OpenRouterModelReasoningCapabilities

func OpenRouterModelReasoningCapabilities(ctx context.Context, modelID string, timeout time.Duration, allowFetch bool) (ReasoningCapabilities, bool)

OpenRouterModelReasoningCapabilities is the live catalog answer for an OpenRouter model, cache only by default

type ReasoningReplayRoute

type ReasoningReplayRoute struct {
	Pad      bool
	Carriers map[string]bool
}

ReasoningReplayRoute is the must echo pad flag and the carriers a wire copy keeps, nil carriers outside chat completions

func ReasoningReplayRouteFor

func ReasoningReplayRouteFor(apiMode, provider, model, baseURL string, echoOptIn bool, rejected map[string]bool) ReasoningReplayRoute

ReasoningReplayRouteFor decides the replay shape of one route minus the carriers it rejected

type RejectedThinkingStore

type RejectedThinkingStore interface {
	ModelConfigValue(sessionID, key string) (any, bool)
	PatchModelConfig(sessionID string, patch map[string]any) error
}

RejectedThinkingStore persists rejected thinking fingerprints in a session's model config

type RejectedThinkingTracker

type RejectedThinkingTracker struct {
	Mode            APIMode
	BaseURL         string
	Model           string
	SessionID       string
	Store           RejectedThinkingStore
	PersistDisabled bool
	// Clears the prompt token anchor once the provider visible history changed shape
	ResetUsageAnchor func()
	// contains filtered or unexported fields
}

RejectedThinkingTracker is the per agent holder of rejected thinking fingerprints keyed by session

func (*RejectedThinkingTracker) ApplyRejectedThinkingSuppression

func (t *RejectedThinkingTracker) ApplyRejectedThinkingSuppression(messages []map[string]any) int

ApplyRejectedThinkingSuppression filters rejected thinking from a request copy rebuilt from history

func (*RejectedThinkingTracker) CarryRejectedThinkingToSession

func (t *RejectedThinkingTracker) CarryRejectedThinkingToSession(oldSessionID string)

CarryRejectedThinkingToSession moves the fingerprints of a compressed parent session onto the current one

func (*RejectedThinkingTracker) RememberRejectedThinking

func (t *RejectedThinkingTracker) RememberRejectedThinking(apiMessages []map[string]any) int

RememberRejectedThinking fingerprints the rejected request and repairs its retry copy without touching history

func (*RejectedThinkingTracker) SessionRejectedThinking

func (t *RejectedThinkingTracker) SessionRejectedThinking(sessionID string) map[string]bool

SessionRejectedThinking returns the in memory fingerprints of a session, else the persisted ones

func (*RejectedThinkingTracker) TracksRejectedThinking

func (t *RejectedThinkingTracker) TracksRejectedThinking() bool

TracksRejectedThinking reports whether this holder's route heals signature rejections durably

type RelayChatAccumulator

type RelayChatAccumulator = relayChatAccumulator

RelayChatAccumulator folds relayed chat completion chunks into one response payload

func NewRelayChatAccumulator

func NewRelayChatAccumulator() *RelayChatAccumulator

NewRelayChatAccumulator is an empty accumulator ready to observe relayed chunks

type RelayExecuteOptions

type RelayExecuteOptions struct {
	Name                   string
	ModelName              string
	SessionID              *string
	Metadata               map[string]any
	DeferLogicalCompletion bool
}

Options of one physical provider attempt through Relay

type RelayLogicalCompletion

type RelayLogicalCompletion struct {
	Outcome           string
	ModelName         *string
	ProviderName      *string
	ResponseModelName *string
	ErrorClass        *string
}

Route report of a logical call, each nil field an absent keyword

type RelayStreamOptions

type RelayStreamOptions struct {
	Name                       string
	ModelName                  string
	Finalizer                  func(ctx context.Context) (any, error)
	Metadata                   map[string]any
	DeferLogicalCompletion     bool
	CompletedResponsePredicate func(value any) bool
}

Options of a provider stream run under the inherited turn

type RemovalResult

type RemovalResult struct {
	Cleaned  []string
	Hints    []string
	Suppress bool
}

RemovalResult is the outcome of removing a credential source

type RemovalStep

type RemovalStep struct {
	Provider    string
	SourceID    string
	Remove      func(env PoolEnv, provider string, removed PooledCredential) RemovalResult
	Match       func(source string) bool
	Description string
}

RemovalStep says how to remove one credential source

func FindRemovalStep

func FindRemovalStep(provider, source string) (RemovalStep, bool)

FindRemovalStep is the profile's own step when it claims the source, else the first registry match

func (RemovalStep) Matches

func (s RemovalStep) Matches(provider, source string) bool

Matches reports whether the step covers the provider and source

type Request

type Request struct {
	Model             string
	Messages          []*state.Message
	Tools             []map[string]any
	ToolChoice        any
	ParallelToolCalls *bool
	MaxTokens         int
	Temperature       *float64
	TopP              *float64
	Stop              []string
	Reasoning         Reasoning
	ResponseFormat    map[string]any
	ExtraBody         map[string]any
	Stream            bool
	Timeout           time.Duration
	SessionID         string
	TurnID            string
	CacheTTL          string
	CacheScope        string
	ServiceTier       string
	Metadata          map[string]string
	User              string
}

Request is one inference call in provider neutral shape with the system prompt as the first system message

type RequestAbortHook

type RequestAbortHook struct {
	Abort func(reason string) bool
}

RequestAbortHook is the abort callable an inline request publishes on the agent, compared by identity

type RequestOpener

type RequestOpener interface {
	Open(req *http.Request, timeout time.Duration) (*http.Response, error)
}

RequestOpener opens one request under a timeout

type RequestProcessor

type RequestProcessor func(*http.Request) *http.Request

RequestProcessor rewrites a request before it is sent, urllib's http_request hook

type Response

type Response struct {
	Message      *state.Message
	FinishReason string
	Usage        Usage
	Model        string
	Provider     string
	RequestID    string
	StatusCode   int
	Headers      http.Header
	Raw          json.RawMessage
	Latency      time.Duration
	Truncated    bool
	// Top level completion fields the wire schema does not declare, such as an agent provider's projected rows
	Extra map[string]any
}

Response is one completed inference result

type ResponsesRoute

type ResponsesRoute struct {
	// contains filtered or unexported fields
}

ResponsesRoute is the classified Responses route of a provider and base URL

func ClassifyResponsesRoute

func ClassifyResponsesRoute(provider, baseURL string) ResponsesRoute

ClassifyResponsesRoute classifies the Responses route with exact host or subdomain checks

func (ResponsesRoute) IsCodexBackend

func (r ResponsesRoute) IsCodexBackend() bool

func (ResponsesRoute) IsXAI

func (r ResponsesRoute) IsXAI() bool

func (ResponsesRoute) ProfileReasoning

func (r ResponsesRoute) ProfileReasoning() bool

True when the endpoint profile gates reasoning through its reasoning payload

type RetirementApplyResult

type RetirementApplyResult struct {
	FilePath       string
	BackupPath     string
	IssuesResolved []RetirementIssue
	ConfigChanged  bool
}

RetirementApplyResult is the outcome of rewriting a config for the xAI retirement

func ApplyXAIRetirementMigration

func ApplyXAIRetirementMigration(ctx context.Context, configPath string, issues []RetirementIssue, backup bool) (RetirementApplyResult, error)

ApplyXAIRetirementMigration rewrites the config file in place keeping comments, order and literals, backing it up first

type RetirementIssue

type RetirementIssue struct {
	ConfigPath      string
	CurrentModel    string
	Replacement     string
	ReasoningEffort string
	Note            string
}

RetirementIssue is a reference to a retired xAI model found in an icebath config

func FindRetiredXAIRefs

func FindRetiredXAIRefs(cfg any) []RetirementIssue

FindRetiredXAIRefs lists retired xAI models in the principal, auxiliary, delegation, tts and image gen slots

type RetrySession

type RetrySession struct {
	DisableStreaming         bool
	StreamOptionsUnsupported bool
	// contains filtered or unexported fields
}

RetrySession holds the latches that outlive one API call block

func (*RetrySession) ResetStaleStreak

func (s *RetrySession) ResetStaleStreak()

Clears the stale breaker after the provider proved responsive or the route changed

func (*RetrySession) RetryRecoveredLocalServer

func (s *RetrySession) RetryRecoveredLocalServer(apiMode APIMode, provider, baseURL string) bool

Turn start lets one attempt past an open stale breaker when the local llama-server answers its health check again

func (*RetrySession) StaleStreak

func (s *RetrySession) StaleStreak() int

Consecutive stale attempts the session has seen since the provider last answered

type RotationRequest

type RotationRequest struct {
	StatusCode    int
	ErrorContext  map[string]any
	APIKeyHint    string
	CredentialID  string
	FailureReason string
	Model         string
}

RotationRequest identifies a failed request and its classified failure

type Route

type Route struct {
	Provider   string
	Model      string
	BaseURL    string
	APIKey     string
	Headers    map[string]string
	Mode       APIMode
	Auth       AuthKind
	Region     string
	ProjectID  string
	Deployment string
	APIVersion string
	Timeout    time.Duration
	Local      bool
	ExtraBody  map[string]any
	// AWS credentials for sigv4 signed routes
	AccessKeyID     string
	SecretAccessKey string
	SessionToken    string
	// Refreshes an expiring bearer token and returns the new one
	TokenSource func(ctx context.Context) (string, error)
	Transport   http.RoundTripper
}

Route is one fully resolved way to reach a model

func ConfigureBedrockOpenAIRoute

func ConfigureBedrockOpenAIRoute(ctx context.Context, route Route, timeout time.Duration) (Route, error)

ConfigureBedrockOpenAIRoute installs SigV4 on a Mantle route unless it carries a real Bedrock API key

type RouteEntryClient

type RouteEntryClient struct {
	Client          AuxClient
	Model           string
	APIModeExplicit bool
	APIMode         string
}

RouteEntryClient is what the fallback swap builds for an entry, a nil Client when the provider has no usable one and Model normalized for the provider

func ResolveRouteEntryClient

func ResolveRouteEntryClient(ctx context.Context, resolve ProviderClientResolver, entry map[string]any, provider, model string, rawCodex bool) (RouteEntryClient, error)

ResolveRouteEntryClient builds the client the fallback swap binds for an entry, shared with the live check, the chat completions adapter of a Responses provider when rawCodex is off

type RouterModels

type RouterModels struct {
	IDs    []string
	Status map[string]any
}

Router models in listing order with their status values

func (RouterModels) Get

func (m RouterModels) Get(modelID string) (any, bool)

Status value of one model and whether the router lists it

type RunBudgetAgent

type RunBudgetAgent interface {
	RunBudget() (seconds, startedAt float64)
}

RunBudgetAgent is an agent carrying a wall clock run budget and the epoch second its turn clock started

type RunawayStreamWatch

type RunawayStreamWatch struct {
	// contains filtered or unexported fields
}

RunawayStreamWatch applies the stop path repetition criterion while one channel streams

func NewRunawayStreamWatch

func NewRunawayStreamWatch() *RunawayStreamWatch

func (*RunawayStreamWatch) Feed

func (w *RunawayStreamWatch) Feed(text string) bool

Feed adds one delta and reports once the channel has become a runaway loop

type Runtime

type Runtime struct {
	Provider          string
	APIMode           APIMode
	BaseURL           string
	APIKey            string
	TokenSource       func(ctx context.Context) (string, error)
	Source            string
	RequestedProvider string
	Model             string
	KeyEnv            string
	ProviderKey       string
	KeyCmd            string
	ExtraHeaders      map[string]string
	RequestOverrides  map[string]any
	Capabilities      map[string]bool
	AuthMode          string
	Entra             map[string]any
	Region            string
	BedrockOpenAI     bool
	BedrockAnthropic  bool
	GuardrailConfig   map[string]any
	Command           string
	Args              []string
	AuthError         *AuthError
	Expiry            map[string]any
	CredentialPool    *Pool
}

One resolved provider runtime, the dict handed to the agent

func ResolveNamedCustomRuntime

func ResolveNamedCustomRuntime(ctx context.Context, h, requestedProvider, explicitAPIKey, explicitBaseURL, targetModel string, cfg map[string]any) (*Runtime, error)

Named custom rung of the runtime resolver over an explicit config, nil when the request is no custom route

func ResolveRuntimeProvider

func ResolveRuntimeProvider(ctx context.Context, h, requested, targetModel, explicitBaseURL, explicitAPIKey string) (*Runtime, error)

Resolves the runtime of a requested provider for the home with explicit endpoint overrides

func ResolveRuntimeWithFallback

func ResolveRuntimeWithFallback(ctx context.Context, h, requested, targetModel, explicitBaseURL, explicitAPIKey string) (*Runtime, map[string]any, error)

Primary runtime of the home, the configured fallback chain walked when the primary fails on credentials

func (*Runtime) APIKeyValue

func (rt *Runtime) APIKeyValue() any

Credential as the runtime dict holds it, the callable token source when no static key was resolved

func (*Runtime) Route

func (rt *Runtime) Route() Route

Route converts the runtime into the wire route the adapters consume

type RuntimeBaseURLResolver

type RuntimeBaseURLResolver func(ctx context.Context, apiKey, defaultURL, envURL string) string

RuntimeBaseURLResolver is a provider owned base URL derived from the credential, empty for env or default

type RuntimeCredentialSource

type RuntimeCredentialSource interface {
	RuntimeCredential(provider string) (Credential, error)
}

RuntimeCredentialSource reads an oauth provider's stored login the way the runtime credential resolvers do

type RuntimeMainOptions

type RuntimeMainOptions struct {
	RequestedProvider string
	BaseURL           string
	APIKey            any
	APIMode           string
	AuthMode          string
	SessionID         string
	CacheScope        string
}

Optional fields of a main runtime binding

type SafeCredentialRedirectHandler

type SafeCredentialRedirectHandler struct {
	// contains filtered or unexported fields
}

SafeCredentialRedirectHandler keeps request headers only while redirects stay on one origin

func NewSafeCredentialRedirectHandler

func NewSafeCredentialRedirectHandler(originalURL string, crossOriginSafe ...string) (*SafeCredentialRedirectHandler, error)

NewSafeCredentialRedirectHandler binds the policy to the first URL's origin and the headers allowed across origins

func (*SafeCredentialRedirectHandler) RedirectRequest

func (h *SafeCredentialRedirectHandler) RedirectRequest(req *http.Request, via []*http.Request) error

RedirectRequest applies urllib's status and method rules, then carries the previous hop's headers only within the origin

type ScopedCredentialSource

type ScopedCredentialSource interface {
	CredentialForEntry(poolKey string, entry map[string]any) (Credential, bool)
}

ScopedCredentialSource narrows a pool to the rows a custom entry owns before selecting one

type SecretCache

type SecretCache struct {
	Disk *SecretDiskCache
	// contains filtered or unexported fields
}

SecretCache is an in process layer over a disk cache

func NewSecretCache

func NewSecretCache(basename string) *SecretCache

NewSecretCache builds the two layer cache for a basename

func (*SecretCache) Clear

func (c *SecretCache) Clear(homePath string)

Clear drops both layers

func (*SecretCache) Lookup

func (c *SecretCache) Lookup(key string, ttl float64, homePath string, readDisk func() (CachedFetch, bool)) (CachedFetch, bool, error)

Lookup is the fresh entry from memory, else from disk promoted into memory, erring on an undecodable file

func (*SecretCache) Store

func (c *SecretCache) Store(key string, entry CachedFetch, ttl float64, homePath string)

Store writes the entry to both layers

func (*SecretCache) StoreMemory

func (c *SecretCache) StoreMemory(key string, entry CachedFetch)

StoreMemory writes the entry to the in process layer only

type SecretDiskCache

type SecretDiskCache struct {
	// contains filtered or unexported fields
}

SecretDiskCache is the profile aware on disk cache of one backend

func NewSecretDiskCache

func NewSecretDiskCache(basename string) *SecretDiskCache

NewSecretDiskCache binds a disk cache to a basename under the home

func (*SecretDiskCache) Clear

func (c *SecretDiskCache) Clear(homePath string)

Clear deletes the cache file if present

func (*SecretDiskCache) Read

func (c *SecretDiskCache) Read(key string, ttl float64, homePath string) (CachedFetch, bool, error)

Read is the fresh cached entry for key, false on mismatch or staleness, an error only for undecodable bytes

func (*SecretDiskCache) Write

func (c *SecretDiskCache) Write(key string, entry CachedFetch, ttl float64, homePath string)

Write persists the entry atomically, a no-op when the TTL is off or on an I/O error

type SecretErrorKind

type SecretErrorKind string

SecretErrorKind is the failure taxonomy of a fetch

const (
	SecretErrorNotConfigured SecretErrorKind = "not_configured"
	SecretErrorBinaryMissing SecretErrorKind = "binary_missing"
	SecretErrorAuthFailed    SecretErrorKind = "auth_failed"
	SecretErrorAuthExpired   SecretErrorKind = "auth_expired"
	SecretErrorRefInvalid    SecretErrorKind = "ref_invalid"
	SecretErrorNetwork       SecretErrorKind = "network"
	SecretErrorEmptyValue    SecretErrorKind = "empty_value"
	SecretErrorTimeout       SecretErrorKind = "timeout"
	SecretErrorInternal      SecretErrorKind = "internal"
)

func ClassifySecretCLIError

func ClassifySecretCLIError(message string, rules []SecretErrorRule) SecretErrorKind

ClassifySecretCLIError maps helper CLI failure text onto the taxonomy

type SecretErrorRule

type SecretErrorRule struct {
	Kind   SecretErrorKind
	Tokens []string
}

SecretErrorRule maps substrings of CLI failure text onto a kind, first match wins

type SecretFetchResult

type SecretFetchResult struct {
	Secrets    map[string]string
	Applied    []string
	Skipped    []string
	Warnings   []string
	Error      string
	ErrorKind  SecretErrorKind
	BinaryPath string
	// contains filtered or unexported fields
}

SecretFetchResult is the outcome of one source's fetch

func ApplyOnePasswordSecrets

func ApplyOnePasswordSecrets(opts OnePasswordApplyOptions) *SecretFetchResult

ApplyOnePasswordSecrets resolves configured references and sets them on the process environment

func NewSecretFetchResult

func NewSecretFetchResult() *SecretFetchResult

NewSecretFetchResult is an empty successful result

func (*SecretFetchResult) Fail

Fail records the error and kind and returns the result

func (*SecretFetchResult) OK

func (r *SecretFetchResult) OK() bool

OK reports no error

type SecretScope

type SecretScope struct {
	Mapping     map[string]string
	ProfileHome string
	// contains filtered or unexported fields
}

SecretScope is the profile secret mapping a task reads credentials through

func SecretScopeFrom

func SecretScopeFrom(ctx context.Context) *SecretScope

SecretScopeFrom snapshots the context's scope, multiplex and home override into one reader

func (*SecretScope) GetSecret

func (s *SecretScope) GetSecret(name string) (string, bool)

GetSecret is Secret for callers that cannot report an error, an unscoped read panics

func (*SecretScope) GetSecretStr

func (s *SecretScope) GetSecretStr(name, def string) string

GetSecretStr is GetSecret with a default for a genuinely unset secret

func (*SecretScope) Secret

func (s *SecretScope) Secret(name string) (string, bool, error)

Secret resolves an env var name through the scope, failing closed under multiplexing with no scope

type SecretSource

type SecretSource interface {
	Spec() SecretSourceSpec
	// Resolves the source's secrets, never panics, cfg is the raw secrets.<name> section
	Fetch(cfg map[string]any, homePath string, environ *SourceEnvironment) *SecretFetchResult
	ConfigSchema() map[string]map[string]any
}

SecretSource is one external secret backend

func GetSecretSource

func GetSecretSource(name, scope string) SecretSource

GetSecretSource is the registered source by name for the scope

func ListPluginSecretSources

func ListPluginSecretSources() []SecretSource

ListPluginSecretSources lists sources registered outside the bundled set, global plugin origins plus the scope's

func ListSecretSources

func ListSecretSources(scope string) []SecretSource

ListSecretSources lists the sources visible to the scope in apply order

func SnapshotSecretRegistration

func SnapshotSecretRegistration(name, scope string) SecretSource

SnapshotSecretRegistration is the registration owned by exactly one registry layer

type SecretSourceHooks

type SecretSourceHooks interface {
	IsEnabled(cfg map[string]any) (bool, error)
	OverrideExisting(cfg map[string]any) (bool, error)
	ProtectedEnvVars(cfg map[string]any) (map[string]bool, error)
	FetchTimeoutSeconds(cfg map[string]any) (float64, error)
	Remediation(kind SecretErrorKind, cfg map[string]any) (string, error)
}

Overridable base methods a source answers in place of the spec driven defaults

type SecretSourceSpec

type SecretSourceSpec struct {
	APIVersion              int
	Name                    string
	Label                   string
	Shape                   string
	Scheme                  string
	TokenEnvKey             string
	DefaultTokenEnv         string
	OverrideExistingDefault bool
	RemediationHints        map[SecretErrorKind]string
}

SecretSourceSpec is the static description of one secret backend

type SelectionContext

type SelectionContext struct {
	ContextTokens int
	CurrentModel  string
}

SelectionContext carries the live session facts switch aware guards need

func SelectionContextFor

func SelectionContextFor(lastPromptTokens int, currentModel string) *SelectionContext

SelectionContextFor builds the live facts from the last billed prompt size, nil without a positive measurement

type SelectionRequest

type SelectionRequest struct {
	Model        string
	Provider     string
	BaseURL      string
	APIKey       string
	ModelInfo    *ModelsDevEntry
	IncludeKinds []string
	Context      *SelectionContext
}

SelectionRequest is one model selection checked by every registered guard, nil IncludeKinds keeps every kind

type SelectionWarning

type SelectionWarning struct {
	Kind     string
	Title    string
	Model    string
	Provider string
	Message  string
}

SelectionWarning is a selection time warning a surface confirms before applying a model

func CombinedSelectionWarning

func CombinedSelectionWarning(ctx context.Context, req SelectionRequest) *SelectionWarning

CombinedSelectionWarning returns nil, the single warning, or one multiple kind warning stacking every message

func SelectionWarnings

func SelectionWarnings(ctx context.Context, req SelectionRequest) []SelectionWarning

SelectionWarnings returns every registered guard's warning restricted to the requested kinds

type SetupAsker

type SetupAsker func(HostedPrompt) HostedAnswer

SetupAsker puts one hosted prompt to the user and waits for the reply

type SetupAttributeError

type SetupAttributeError struct{ Msg string }

SetupAttributeError is a setup section refusing a config value of the wrong kind

func (*SetupAttributeError) Error

func (e *SetupAttributeError) Error() string

type SetupExit

type SetupExit struct{ Code int }

SetupExit is the sys.exit a setup prompt raises on Ctrl-C, recovered at the command boundary

func (SetupExit) Error

func (e SetupExit) Error() string

type SetupStep

type SetupStep struct {
	Label  string
	Action func() error
}

SetupStep is one labelled section of the wizard

type SetupTypeError

type SetupTypeError struct{ Msg string }

SetupTypeError is a setup section refusing to write into a config value that is not a mapping

func (*SetupTypeError) Error

func (e *SetupTypeError) Error() string

type SignInCancelledError

type SignInCancelledError struct {
	ExitCode int
	HasCode  bool
}

SignInCancelledError is an interactive login the user interrupted or ended at EOF

func (*SignInCancelledError) Error

func (e *SignInCancelledError) Error() string

type SignInCopyError

type SignInCopyError struct {
	Message        string
	OAuthErrorCode string
}

SignInCopyError is an error whose text is already user copy with a lead line and a details line

func (*SignInCopyError) Error

func (e *SignInCopyError) Error() string

type SourceEnvironment

type SourceEnvironment struct {
	// contains filtered or unexported fields
}

SourceEnvironment is the per fetch environment view a source reads bootstrap credentials from

func MappingSourceEnvironment

func MappingSourceEnvironment(vars map[string]string) *SourceEnvironment

MappingSourceEnvironment reads and writes a private mapping, never the process environment

func ProcessSourceEnvironment

func ProcessSourceEnvironment() *SourceEnvironment

ProcessSourceEnvironment reads and writes the process environment

func (*SourceEnvironment) Get

func (e *SourceEnvironment) Get(name string) (string, bool)

Get reads one variable from the view

func (*SourceEnvironment) IsProcess

func (e *SourceEnvironment) IsProcess() bool

IsProcess reports whether the view is the process environment itself

func (*SourceEnvironment) Mapping

func (e *SourceEnvironment) Mapping() map[string]string

Mapping is the private mapping behind a non process view

func (*SourceEnvironment) Set

func (e *SourceEnvironment) Set(name, value string)

Set writes one variable into the view

func (*SourceEnvironment) Snapshot

func (e *SourceEnvironment) Snapshot() map[string]string

Snapshot copies the view into a plain map

func (*SourceEnvironment) Unset

func (e *SourceEnvironment) Unset(name string)

Unset removes one variable from the view

func (*SourceEnvironment) Value

func (e *SourceEnvironment) Value(name string) string

Value reads one variable or an empty string

type SourceReport

type SourceReport struct {
	Name             string
	Label            string
	Result           *SecretFetchResult
	Applied          []string
	SkippedExisting  []string
	SkippedClaimed   []string
	SkippedProtected []string
	SkippedInvalid   []string
}

SourceReport is one source's outcome within an apply pass

type SpotifyLoginOptions

type SpotifyLoginOptions struct {
	ClientID    string
	RedirectURI string
	Scope       string
	NoBrowser   bool
	Timeout     float64
}

SpotifyLoginOptions are the parsed flags of icebath spotify login

type SseDoneTracker

type SseDoneTracker struct {
	SawDone           bool
	SawTerminalFinish bool
	SawLastOne        bool
	SawErrorEvent     bool
	SawMalformedEvent bool
	Interrupted       bool
	// contains filtered or unexported fields
}

SseDoneTracker is an incremental scanner over forwarded SSE chunks deciding whether one [DONE] gets appended

func (*SseDoneTracker) Feed

func (t *SseDoneTracker) Feed(chunk []byte)

Feed observes a forwarded chunk without modifying its bytes

func (*SseDoneTracker) MarkInterrupted

func (t *SseDoneTracker) MarkInterrupted()

MarkInterrupted records that the upstream stream ended through an error or cancel

func (*SseDoneTracker) ShouldAppendDone

func (t *SseDoneTracker) ShouldAppendDone() bool

ShouldAppendDone is true when a single terminal [DONE] belongs after a clean EOF

type StartupModelRoute

type StartupModelRoute struct {
	Model    string
	Provider string
	BaseURL  string
	APIKey   string
}

StartupModelRoute is the model and provider pair resolved before an agent is built

func ResolveStartupModelRoute

func ResolveStartupModelRoute(ctx context.Context, rawModel string, opts StartupRouteOptions) (*StartupModelRoute, error)

ResolveStartupModelRoute resolves aliases, provider qualified input and configured provider slash model at startup

type StartupRouteOptions

type StartupRouteOptions struct {
	ExplicitProvider string
	CurrentProvider  string
	UserProviders    map[string]any
	CustomProviders  []any
	AliasConfig      map[string]any
}

StartupRouteOptions carries the caller's routing context and an optional alias config snapshot

type StaticModelConflict

type StaticModelConflict struct {
	Model       string
	Provider    string
	Suggestions []string
	Message     string
}

StaticModelConflict names a model another vendor's curated catalog owns while the provider's family lacks it

func StaticModelProviderConflict

func StaticModelProviderConflict(ctx context.Context, modelName, provider string, limit int) (StaticModelConflict, bool)

StaticModelProviderConflict checks model and provider coherence offline from the curated catalogs, false when coherent or undecidable

type Store

type Store struct {
	Log *slog.Logger
	// contains filtered or unexported fields
}

Store persists auth.json for one icebath home with the global root as read only fallback

func NewStore

func NewStore(h string) *Store

NewStore binds a store to the auth.json of the given icebath home

func (*Store) ActiveProvider

func (s *Store) ActiveProvider() (string, error)

ActiveProvider returns the active provider id from the store

func (*Store) ActiveProviderIs

func (s *Store) ActiveProviderIs(normalized string) bool

ActiveProviderIs reports whether the active provider equals the normalized id

func (*Store) ClearProviderAuth

func (s *Store) ClearProviderAuth(providerID string) (bool, error)

ClearProviderAuth deletes provider and pool entries for the target and reports whether anything changed

func (*Store) Credential

func (s *Store) Credential(provider string) (Credential, bool)

Credential is the provider's auth.json singleton login

func (*Store) DeactivateProvider

func (s *Store) DeactivateProvider() error

DeactivateProvider clears active_provider without deleting credentials

func (*Store) GetProviderAuthState

func (s *Store) GetProviderAuthState(providerID string) (map[string]any, error)

GetProviderAuthState returns persisted provider state profile first then global root

func (*Store) GlobalPath

func (s *Store) GlobalPath() string

GlobalPath is the global root auth.json or empty when the store is the global root itself

func (*Store) Home

func (s *Store) Home() string

func (*Store) IsSourceSuppressed

func (s *Store) IsSourceSuppressed(providerID, source string) bool

IsSourceSuppressed reports whether the user suppressed a credential source

func (*Store) Load

func (s *Store) Load() (AuthData, error)

Load parses the active auth.json

func (*Store) LoadFile

func (s *Store) LoadFile(path string) (AuthData, error)

LoadFile parses one auth.json, quarantining corrupt content and failing on unreadable files

func (*Store) LoadGlobal

func (s *Store) LoadGlobal() AuthData

LoadGlobal returns the global root store as a memoised read only fallback or an empty map

func (*Store) Lock

func (s *Store) Lock(timeout time.Duration) (func(), error)

Lock takes the active store lock for one read modify write transaction

func (*Store) LockPath

func (s *Store) LockPath(authPath string, timeout time.Duration) (func(), error)

LockPath takes the cross process lock of an explicit auth path like _auth_store_lock with target_path

func (*Store) MarkProviderActiveIfUnset

func (s *Store) MarkProviderActiveIfUnset(providerID string) error

MarkProviderActiveIfUnset sets active_provider only when none is set yet

func (*Store) OnProviderWrite

func (s *Store) OnProviderWrite(h ProviderWriteHook)

OnProviderWrite registers a hook invoked before any provider state is stored

func (*Store) Path

func (s *Store) Path() string

func (*Store) PersistProviderStateToStore

func (s *Store) PersistProviderStateToStore(providerID string, state map[string]any, target string, setActive bool) (string, error)

PersistProviderStateToStore merges one provider into a specific auth store under that store's lock

func (*Store) ProviderState

func (s *Store) ProviderState(data AuthData, providerID string) map[string]any

ProviderState returns provider state with the global root fallback

func (*Store) ProviderStateWithSource

func (s *Store) ProviderStateWithSource(data AuthData, providerID string) (map[string]any, string)

ProviderStateWithSource returns provider state and the path it came from, profile first then global root

func (*Store) ProviderTransaction

func (s *Store) ProviderTransaction(providerID string, timeout time.Duration, fn func(tx *ProviderTxn) error) error

ProviderTransaction locks the active store then the global source and runs fn with the fresh state

func (*Store) ReadCredentialPool

func (s *Store) ReadCredentialPool(providerID string) ([]map[string]any, error)

ReadCredentialPool returns one provider's pool rows with the global root as fallback when the profile has none

func (*Store) ReadCredentialPools

func (s *Store) ReadCredentialPools() (map[string][]map[string]any, error)

ReadCredentialPools returns every provider's rows with per provider global fallback

func (*Store) Save

func (s *Store) Save(data AuthData) error

Save writes the document to the active store

func (*Store) SaveActiveProviderState

func (s *Store) SaveActiveProviderState(providerID string, state map[string]any) (string, error)

SaveActiveProviderState locks loads writes the state as active provider and saves

func (*Store) SaveProviderStateToSource

func (s *Store) SaveProviderStateToSource(data AuthData, providerID string, state map[string]any, source string) error

SaveProviderStateToSource persists provider state to the store it was read from leaving active_provider alone

func (*Store) SaveTo

func (s *Store) SaveTo(data AuthData, target string) error

SaveTo stamps version and updated_at then atomically writes the document to a specific path

func (*Store) StoreProviderState

func (s *Store) StoreProviderState(data AuthData, providerID string, state map[string]any, setActive bool) error

StoreProviderState writes state under providers and optionally makes it the active provider

func (*Store) SuppressCredentialSource

func (s *Store) SuppressCredentialSource(providerID, source string) error

SuppressCredentialSource records that a credential source must not be reseeded

func (*Store) SuppressedCredentialSources

func (s *Store) SuppressedCredentialSources(providerID string) map[string]bool

SuppressedCredentialSources returns every suppressed source for a provider

func (*Store) UnsuppressCredentialSource

func (s *Store) UnsuppressCredentialSource(providerID, source string) (bool, error)

UnsuppressCredentialSource clears a suppression marker and reports whether one existed

func (*Store) Update

func (s *Store) Update(fn func(data AuthData) (bool, error)) error

Update runs fn under the store lock and saves when fn reports a change

func (*Store) WriteCredentialPool

func (s *Store) WriteCredentialPool(providerID string, entries []map[string]any, removedIDs, statusClearedIDs []string, tokenBases map[string]TokenPair) ([]map[string]any, error)

WriteCredentialPool persists one provider's rows merging concurrent disk rows and newer disk cooldowns

type StreamAbandonedError

type StreamAbandonedError struct {
	Err error
}

StreamAbandonedError ends a streaming call whose attempt reader the watchdog kills could not unwind

func (*StreamAbandonedError) Error

func (e *StreamAbandonedError) Error() string

func (*StreamAbandonedError) Unwrap

func (e *StreamAbandonedError) Unwrap() error

type StreamChunks

type StreamChunks struct {
	Chunks []map[string]any
	Extra  map[string]any
	// contains filtered or unexported fields
}

Stream chunk list that also carries the response level attributes of the completion it came from

func CompletionToStreamChunks

func CompletionToStreamChunks(completion map[string]any) (*StreamChunks, error)

Reshapes a one shot ACP completion as a data chunk then a usage chunk, copying its other attributes

func (*StreamChunks) Close

func (s *StreamChunks) Close() error

Releases nothing since every chunk is already in memory

func (*StreamChunks) Next

func (s *StreamChunks) Next(ctx context.Context) (map[string]any, error)

Next chunk in order, io.EOF once every chunk was read

type StreamDiag

type StreamDiag struct {
	StartedAt        time.Time
	FirstChunkAt     *time.Time
	Chunks           int
	Bytes            int
	Headers          [][2]string
	HTTPStatus       *int
	ServingProvider  string
	FinishReasonSeen bool
}

StreamDiag is the per attempt diagnostic record the streaming functions fill and the retry block reads

func StreamDiagInit

func StreamDiagInit() *StreamDiag

Fresh diagnostic record for one stream attempt

type StreamDiagAgent

type StreamDiagAgent interface {
	StreamProvider() string
	StreamBaseURL() string
	BufferDiagnosticStatus(text string)
	TouchActivity(desc string)
}

StreamDiagAgent is the agent surface the stream drop log and status line read

type StreamEmitters

type StreamEmitters interface {
	EmitStreamStart()
	EmitStreamEnd(finalText string, finished bool, errText *string)
}

StreamEmitters brackets a stream with the agent display hooks for its start and its end

type StreamEvent

type StreamEvent struct {
	Kind EventKind
	Text string
	// Wait notice carrying diagnostic text, the gateway DiagnosticText routing
	Diagnostic bool
	Index      int
	ToolCall   *state.ToolCall
	Usage      *Usage
	Raw        json.RawMessage
}

StreamEvent is one incremental piece of a streamed response

type StreamEventOrderError

type StreamEventOrderError struct{ Type string }

Event that arrived before message_start, the order the stream accumulator refuses

func (*StreamEventOrderError) Error

func (e *StreamEventOrderError) Error() string

func (*StreamEventOrderError) PyTypeName

func (e *StreamEventOrderError) PyTypeName() string

Python exception class the SDK raises for an out of order stream event

type StreamFunc

type StreamFunc func(StreamEvent) error

StreamFunc receives stream events and aborts the stream by returning an error

type StreamLifetimeExceededError

type StreamLifetimeExceededError struct {
	Elapsed float64
	Cap     float64
	Cause   error
}

StreamLifetimeExceededError is a stream attempt cut by the agent.stream_max_lifetime cap

func (*StreamLifetimeExceededError) Error

func (*StreamLifetimeExceededError) Timeout

func (e *StreamLifetimeExceededError) Timeout() bool

Timeout marks the cap kill as a timeout for transport error classification

func (*StreamLifetimeExceededError) Unwrap

func (e *StreamLifetimeExceededError) Unwrap() error

Transport error of the cut attempt the cap error replaced

type StreamRequestError

type StreamRequestError struct {
	Err     error
	Request *FailedStreamRequest
}

StreamRequestError attaches the buffered request to a stream open failure

func (*StreamRequestError) Error

func (e *StreamRequestError) Error() string

func (*StreamRequestError) FailedRequest

func (e *StreamRequestError) FailedRequest() *FailedStreamRequest

func (*StreamRequestError) PyTypeName

func (e *StreamRequestError) PyTypeName() string

func (*StreamRequestError) Unwrap

func (e *StreamRequestError) Unwrap() error

type StreamResponseHolder

type StreamResponseHolder interface {
	StreamResponse() any
}

StreamResponseHolder is a stream handle exposing the transport response that closes its connection

type StreamWriterFence

type StreamWriterFence interface {
	// contains filtered or unexported methods
}

StreamWriterFence is the single writer fence an agent owns over its delta sink

type StreamingThinkScrubber

type StreamingThinkScrubber struct {
	// contains filtered or unexported fields
}

StreamingThinkScrubber hides reasoning tag blocks from streamed assistant text across delta boundaries

func NewStreamingThinkScrubber

func NewStreamingThinkScrubber() *StreamingThinkScrubber

func (*StreamingThinkScrubber) Feed

func (s *StreamingThinkScrubber) Feed(text string) string

Feed scrubs one delta and returns the visible portion, empty when it is all reasoning or held back

func (*StreamingThinkScrubber) Flush

func (s *StreamingThinkScrubber) Flush() string

Flush releases held prose at stream end, discarding an unterminated block, and re arms the boundary

func (*StreamingThinkScrubber) LastHidden

func (s *StreamingThinkScrubber) LastHidden() string

LastHidden is the reasoning text the most recent Feed stripped from inside blocks

func (*StreamingThinkScrubber) Reset

func (s *StreamingThinkScrubber) Reset()

Reset clears every state for a new turn

type SuspectableBackend

type SuspectableBackend interface {
	MarkSuspect(reason string)
}

SuspectableBackend is a stateful backend flagged on timeout so its owner recovers the connection before reuse

type SwitchModelOptions

type SwitchModelOptions struct {
	RawInput         string
	CurrentProvider  string
	CurrentBaseURL   string
	CurrentAPIKey    string
	IsGlobal         bool
	ExplicitProvider string
	UserProviders    map[string]any
	CustomProviders  []any
}

SwitchModelOptions is the current session route and the typed request of one model switch

type SwitchRoute

type SwitchRoute struct {
	BaseURL               string
	APIKey                string
	NewModel              string
	TargetProvider        string
	APIMode               string
	ValidationHeaders     map[string]string
	SuppressOllamaHeaders bool
}

SwitchRoute is the endpoint state a model switch carries, embedded by the switch pipeline state

type TLSSettings

type TLSSettings struct {
	CACert    string
	Verify    bool
	HasVerify bool
}

TLSSettings are the per route certificate knobs a custom entry declares

func CustomProviderTLSSettings

func CustomProviderTLSSettings(baseURL string, customProviders []map[string]any, cfg map[string]any) TLSSettings

CustomProviderTLSSettings returns the TLS settings of the first entry serving the base URL

type TLSVerify

type TLSVerify struct {
	Insecure bool
	Config   *tls.Config
}

TLSVerify is the resolved verification mode for one HTTP client

func ResolveTLSVerify

func ResolveTLSVerify(log *slog.Logger, caBundle string, sslVerify any, baseURL string) TLSVerify

ResolveTLSVerify picks insecure, an explicit bundle replacing the store, or the platform store for a client

type TaggedTokenSource

type TaggedTokenSource struct {
	Mint   func(ctx context.Context) (string, error)
	Source string
	// contains filtered or unexported fields
}

TaggedTokenSource is a token minter that names its credential source without being called

func BuildMinimaxOAuthTokenProvider

func BuildMinimaxOAuthTokenProvider(env PoolEnv) *TaggedTokenSource

BuildMinimaxOAuthTokenProvider mints a fresh MiniMax access token per call, tagged as the MiniMax OAuth source

func TagCredentialSource

func TagCredentialSource(mint func(ctx context.Context) (string, error), source string) *TaggedTokenSource

TagCredentialSource records the source on a minter and returns a callable token source

func (*TaggedTokenSource) Func

func (t *TaggedTokenSource) Func() func(context.Context) (string, error)

Func is the minter as a bare route token source that still answers its source tag

func (*TaggedTokenSource) Token

func (t *TaggedTokenSource) Token(ctx context.Context) (string, error)

Token mints through the wrapped minter

type TimeoutPhaseError

type TimeoutPhaseError struct {
	Phase string
	Err   error
}

TimeoutPhaseError marks a transport timeout with the phase the adapter observed

func (*TimeoutPhaseError) Error

func (e *TimeoutPhaseError) Error() string

func (*TimeoutPhaseError) Timeout

func (e *TimeoutPhaseError) Timeout() bool

Timeout marks the error as a net.Error timeout

func (*TimeoutPhaseError) Unwrap

func (e *TimeoutPhaseError) Unwrap() error

type TokenMapping

type TokenMapping struct {
	ProxyToken    string
	RealEnvName   string
	UpstreamHosts []string
	MatchHeaders  []string
	AliasEnvNames []string
}

TokenMapping is a sandbox visible proxy token to upstream credential lookup

func DiscoverProviderMappings

func DiscoverProviderMappings(availableEnvNames []string) []TokenMapping

DiscoverProviderMappings mints one mapping per known provider whose env var or alias is set

func MergeMappings

func MergeMappings(existing, discovered []TokenMapping, rotate bool) []TokenMapping

MergeMappings keeps existing tokens and refreshes hosts from discovered, rotate re-mints every token

type TokenPair

type TokenPair struct{ Access, Refresh any }

TokenPair is the access and refresh token generation of one pool row

type ToolFeatureState

type ToolFeatureState struct {
	Key                string
	Label              string
	Available          bool
	Active             bool
	ToolsetEnabled     bool
	CurrentProvider    string
	ExplicitConfigured bool
}

ToolFeatureState is one tool feature's availability and the backend serving it as status surfaces show it

type ToolFeatures

type ToolFeatures struct {
	Features map[string]ToolFeatureState
}

ToolFeatures is the per feature state of the configured tool backends

func GetToolFeatures

func GetToolFeatures(env PoolEnv, cfg map[string]any) ToolFeatures

GetToolFeatures resolves every tool feature's state from the config and the configured credentials

func (ToolFeatures) Feature

func (f ToolFeatures) Feature(key string) ToolFeatureState

Feature is the state of one feature key

type Transport

type Transport interface {
	APIMode() string
	ConvertMessages(messages []map[string]any, kwargs map[string]any) (any, error)
	ConvertTools(tools []map[string]any) any
	BuildKwargs(model string, messages []map[string]any, tools []map[string]any, params map[string]any) (map[string]any, error)
	NormalizeResponse(response any, kwargs map[string]any) (*Response, error)
	ValidateResponse(response any) bool
	ExtractCacheStats(response any) map[string]int
	MapFinishReason(raw string) string
}

Transport is the data path of one api mode, messages and tools in, provider kwargs out, raw responses normalized back

func GetTransport

func GetTransport(apiMode string) Transport

GetTransport returns a fresh transport for the api mode, nil when no transport is registered for it

type UnknownAuthProviderError

type UnknownAuthProviderError struct{ Provider string }

UnknownAuthProviderError is a logout aimed at a provider the registry does not know

func (*UnknownAuthProviderError) Error

func (e *UnknownAuthProviderError) Error() string

type UnscopedSecretError

type UnscopedSecretError struct {
	SecretName      string
	DeveloperDetail string
}

UnscopedSecretError is a secret read in multiplex mode with no scope installed

func NewUnscopedSecretError

func NewUnscopedSecretError(secretName, developerDetail string) *UnscopedSecretError

NewUnscopedSecretError treats a whitespace bearing name as the developer detail of an older caller

func (*UnscopedSecretError) Error

func (e *UnscopedSecretError) Error() string

type UnsupportedProviderRequestError

type UnsupportedProviderRequestError struct{ Message string }

UnsupportedProviderRequestError is the ValueError of a provider with no signed in request support

func (*UnsupportedProviderRequestError) Error

type UpstreamAdapter

type UpstreamAdapter interface {
	Name() string
	DisplayName() string
	AllowedPaths() map[string]bool
	IsAuthenticated() bool
	GetCredential() (UpstreamCredential, error)
	GetRetryCredential(failed UpstreamCredential, statusCode int) (*UpstreamCredential, error)
}

UpstreamAdapter is the contract for an upstream provider the proxy can forward to

type UpstreamCredential

type UpstreamCredential struct {
	Bearer    string
	BaseURL   string
	TokenType string
	ExpiresAt string
}

UpstreamCredential is a resolved bearer and base URL ready to forward to

type Usage

type Usage struct {
	InputTokens      int
	OutputTokens     int
	CacheReadTokens  int
	CacheWriteTokens int
	ReasoningTokens  int
	TotalTokens      int
}

Usage counts tokens for one call

func (*Usage) Add

func (u *Usage) Add(o Usage)

Add sums another usage into this one

type UsageAnchor

type UsageAnchor struct {
	PromptTokens     int
	CompletionTokens int
	BaseCount        int
	BaseLastRole     string
	BaseLastFP       string
	BasePrefixFP     string
}

UsageAnchor is provider usage at capture plus the transcript position and prefix it priced

func CaptureUsageAnchor

func CaptureUsageAnchor(promptTokens, completionTokens any, messages []*state.Message) *UsageAnchor

CaptureUsageAnchor builds an anchor from provider reported usage, nil when usage or the transcript is unusable

func (UsageAnchor) ToMap

func (a UsageAnchor) ToMap() map[string]any

ToMap is the persisted anchor blob, an empty last role written as null

type UsageAnchorState

type UsageAnchorState struct {
	Anchor          *UsageAnchor
	TurnBaseAnchor  *UsageAnchor
	PersistDisabled bool
	SessionID       string
	Store           UsageAnchorStore
}

UsageAnchorState is the anchor state an agent carries and mirrors to its session row

func (*UsageAnchorState) Persist

func (s *UsageAnchorState) Persist(anchor *UsageAnchor)

Persist writes or clears the session row anchor blob, failures logged and dropped

func (*UsageAnchorState) Restore

func (s *UsageAnchorState) Restore(history []*state.Message, haveHistory bool)

Restore adopts the persisted anchor while the history carries its priced prefix, clearing a stale blob

func (*UsageAnchorState) Set

func (s *UsageAnchorState) Set(anchor *UsageAnchor, turnBase bool)

Set installs an anchor, nil clearing it, and mirrors it to the session row

type UsageAnchorStore

type UsageAnchorStore interface {
	PatchModelConfig(id string, patch map[string]any) error
	GetModelConfigValue(id, key string) (any, bool, error)
}

UsageAnchorStore is the session row surface that persists and reads model config keys

type UsageCostHook

type UsageCostHook func(model string, usage CanonicalUsage) (CostResult, bool)

UsageCostHook lets a provider profile report the cost its own API returned for a response

type ValidateModelOptions

type ValidateModelOptions struct {
	APIKey  string
	BaseURL string
	APIMode string
	Headers map[string]string
}

ValidateModelOptions carries the endpoint a requested model is validated against, nil Headers is none

type ValueError

type ValueError = providerregistry.ValueError

Python ValueError an auxiliary adapter raises for a request its route refuses

type VariantChoice

type VariantChoice struct {
	Variant   QuantVariant
	ZeroSpill bool
	ReasonKey string
}

Build this machine should download with the UI reason key of the fit

func SelectVariant

func SelectVariant(entry CatalogEntry, budget HardwareBudget) *VariantChoice

Fits the entry's Q4 build to this machine, nil when physics refuses it

type Verdict

type Verdict struct {
	Reason                 FailoverReason
	Retryable              *bool
	ShouldCompress         *bool
	ShouldRotateCredential *bool
	ShouldFallback         *bool
	Context                map[string]any
	// Message a plugin classification puts in place of the extracted error message
	Message *string
}

Verdict is the reason plus hint overrides a stage decided on

type VisionCapabilities

type VisionCapabilities struct{}

VisionCapabilities serves the tools vision probes from the profile registry, the models.dev catalog and the local runtime

func (VisionCapabilities) CatalogSupportsVision

func (VisionCapabilities) CatalogSupportsVision(ctx context.Context, provider, model string) (supported, known bool)

Catalog verdict fetched with network allowed, unknown when the catalog has no vision flag for the model

func (VisionCapabilities) DetectLocalServerType

func (VisionCapabilities) DetectLocalServerType(ctx context.Context, baseURL, apiKey string) string

func (VisionCapabilities) IsLocalEndpoint

func (VisionCapabilities) IsLocalEndpoint(baseURL string) bool

func (VisionCapabilities) IsManagedEndpoint

func (VisionCapabilities) IsManagedEndpoint(baseURL string) bool

func (VisionCapabilities) IsRoutingAggregator

func (VisionCapabilities) IsRoutingAggregator(provider string) bool

func (VisionCapabilities) ManagedModelSupportsVision

func (VisionCapabilities) ManagedModelSupportsVision(ctx context.Context, model string) (supported, known bool)

func (VisionCapabilities) ProviderVisionProfile

func (VisionCapabilities) ProviderVisionProfile(provider string) (supportsVision, supportsVisionToolMessages, found bool)

func (VisionCapabilities) QueryOllamaSupportsVision

func (VisionCapabilities) QueryOllamaSupportsVision(ctx context.Context, model, baseURL, apiKey string) (supported, known bool)

func (VisionCapabilities) StripCodexContextVariantSuffix

func (VisionCapabilities) StripCodexContextVariantSuffix(model string) string

type WaitNoticeState

type WaitNoticeState struct {
	// contains filtered or unexported fields
}

Remembers which wait phase and watchdog the status line currently shows

func (*WaitNoticeState) Reset

func (w *WaitNoticeState) Reset()

Forgets the shown notice so the next silence gets a fresh one

func (*WaitNoticeState) ShouldEmit

func (w *WaitNoticeState) ShouldEmit(phase string, watchdog *WatchdogDeadline) bool

True for the first notice of a silence, a phase or watchdog change, and once near the deadline

type WatchdogDeadline

type WatchdogDeadline struct {
	Label     string
	Remaining float64
}

Names the watchdog that would reconnect and the seconds until it fires

func CodexWatchdogDeadline

func CodexWatchdogDeadline(c CodexWatchdogClock) *WatchdogDeadline

Earliest enabled Codex watchdog with its remaining seconds, nil when none applies or its deadline passed

type WindowDecision

type WindowDecision struct {
	Window     int
	SpillBytes int64
	KVOnGPU    bool
	Reasons    []string
}

The chosen window, the weights it displaces to host and KV residency

func (*WindowDecision) Spilled

func (d *WindowDecision) Spilled() bool

type WindowOutcome

type WindowOutcome interface {
	// contains filtered or unexported methods
}

A launch window decision or a physics refusal

func InitialWindow

func InitialWindow(profile ModelProfile, budget HardwareBudget, flashAttention bool, overheadBytes int64) WindowOutcome

Launch window as the largest zero spill rung, else the floor with bounded early context cost

type WindowsJob

type WindowsJob struct{}

WindowsJob is the owner held containment handle, never created outside Windows

func SpawnServer

func SpawnServer(ctx context.Context, cmd *exec.Cmd, owned bool) (*WindowsJob, error)

Starts cmd, an owned router leads its own group handed to the owner death supervisor

func (*WindowsJob) Close

func (*WindowsJob) Close() error

Releases nothing because POSIX spawns carry no job object

type WireAliasTransport

type WireAliasTransport interface {
	SetLastWireAliases(aliases map[string]string)
}

WireAliasTransport records the tool names a request aliased so the response normalizer reverses only those

type XAIGrokAdapter

type XAIGrokAdapter struct {
	// contains filtered or unexported fields
}

XAIGrokAdapter is the proxy upstream for xAI Grok via Icebath managed OAuth credentials

func (*XAIGrokAdapter) AllowedPaths

func (a *XAIGrokAdapter) AllowedPaths() map[string]bool

func (*XAIGrokAdapter) AuthHint

func (a *XAIGrokAdapter) AuthHint() string

AuthHint is the login command proxy start prints when no credential is available

func (*XAIGrokAdapter) DisplayName

func (a *XAIGrokAdapter) DisplayName() string

func (*XAIGrokAdapter) GetCredential

func (a *XAIGrokAdapter) GetCredential() (UpstreamCredential, error)

GetCredential selects a pool entry under the adapter lock

func (*XAIGrokAdapter) GetRetryCredential

func (a *XAIGrokAdapter) GetRetryCredential(failed UpstreamCredential, statusCode int) (*UpstreamCredential, error)

GetRetryCredential refreshes the key after a 401, rotates after a 429, nil when the pool has nothing else

func (*XAIGrokAdapter) IsAuthenticated

func (a *XAIGrokAdapter) IsAuthenticated() bool

func (*XAIGrokAdapter) Name

func (a *XAIGrokAdapter) Name() string

type XAILoginArgs

type XAILoginArgs struct {
	Timeout   time.Duration
	NoBrowser bool
}

XAILoginArgs are the xAI login flags

Source Files

Jump to

Keyboard shortcuts

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