Documentation
¶
Overview ¶
Package provider resolves model routes and speaks every supported inference wire protocol
Index ¶
- Constants
- Variables
- func ACPFormatMessagesAsPrompt(messages []any, tools []any, toolChoice any) (string, error)
- func AIGatewayHeaders() map[string]string
- func AIGatewayModelIDs(ctx context.Context, forceRefresh bool) []string
- func AWSErrorClassName(err error) string
- func AccountUsageIdentityID(provider string, entry PooledCredential) string
- func AccountUsageSnapshotIsStale(snapshot *AccountUsageSnapshot) bool
- func ActivateMultiProfileHosting()
- func AdaptiveRateLimitBackoff(attempt int, baseURL, model string, e error, defaultWait time.Duration) (time.Duration, string)
- func AddLoopbackNoProxy(env map[string]string) map[string]string
- func AddOpenAIClientResponseHook(client any, mark string, hook func(resp *http.Response)) bool
- func AdmittedResidencyCount(modelsDir string, budget HardwareBudget, configured int, live *HardwareBudget, ...) (int, error)
- func AdoptExternalLoginsEnabled(env PoolEnv) bool
- func AdoptLegacyEngine(ctx context.Context, backend string) bool
- func AffinityScope(ctx context.Context) string
- func AffordableMaxTokensFromError(err error) (int, bool)
- func AggregatorProviders() []string
- func AnchoredContextTokens(ctx context.Context, messages []*state.Message, anchor *UsageAnchor, ...) (int, bool)
- func AnsweredByRequestedModel(requested, returned string) bool
- func AnthropicBaseClientQuery(baseURL string) (string, map[string]string)
- func AnthropicLiveBlocks(m *state.Message) ([]any, bool)
- func AnthropicMaxOutput(model string) int
- func AnthropicOAuthProbeBetas() (full, withoutContext1M string)
- func AnthropicPromptCachePolicy(ctx context.Context, agent *CachePolicyAgent, dest CacheDestination) (bool, bool)
- func AnthropicRequiresBearerAuth(baseURL string) bool
- func AnthropicResponseGuardrailIntervened(message map[string]any) bool
- func AnthropicRouteIsOAuth(ctx context.Context, baseURL, credential string, ...) bool
- func AnyHeaderMap(m map[string]any) map[string]string
- func ApplyAnthropicCacheControl(apiMessages []map[string]any, ttl string, nativeAnthropic bool, ...) []map[string]any
- func ApplyCapabilities(ctx context.Context, rows []map[string]any, metadataConfig map[string]any) error
- func ApplyCustomProviderExtraHeadersToClientKwargs(clientKwargs map[string]any, baseURL string, customProviders []map[string]any, ...)
- func ApplyCustomProviderTLSToClientKwargs(clientKwargs map[string]any, baseURL string, customProviders []map[string]any, ...)
- func ApplyDaybreak(route Route, daybreak bool, overrides map[string]any)
- func ApplyDefaultAgentSettings(ctx context.Context, cfg config.Tree) error
- func ApplyExternalSecretSources(h string)
- func ApplyInheritedModelAssignment(ctx context.Context, modelCfg any, inherited map[string]any) (map[string]any, error)
- func ApplyMainModelAssignment(ctx context.Context, modelCfg any, result ModelSwitchResult) (map[string]any, error)
- func ApplyModelAssignmentSync(ctx context.Context, provider, model, baseURL, apiKey string, ...) (map[string]any, error)
- func ApplyModelSelection(modelCfg any, result ModelSwitchResult, maskCleared bool) map[string]any
- func ApplyRequiredCodexHeaders(headers map[string]string, accessToken, baseURL string) map[string]string
- func ApplyUserDefaultHeaders(ctx context.Context, headers map[string]string) map[string]string
- func ApplyUserMoAPresets(merged map[string]any, raw any)
- func AskOnErrorPath(ctx context.Context, p *Profile, hook string, fallback any, ...) any
- func AskProfile(ctx context.Context, p *Profile, hook string, fallback any, scope any, ...) any
- func AsyncCallLLM(ctx context.Context, kwargs map[string]any) (any, error)
- func AtomicWriteCacheJSON(path string, payload any) error
- func AttributeSecretSourceForTests(name, source string) func()
- func AuthCommand(ctx context.Context, env PoolEnv, ns map[string]any, w, errw io.Writer) (int, error)
- func AutoCacheTTLForSource(source string) string
- func AutoDetectLocalModel(ctx context.Context, baseURL string) string
- func AuxCallKwargs(ctx context.Context, provider, model string, messages any, baseURL string) (map[string]any, error)
- func AuxClientCredential(c AuxClient) any
- func AuxClientCustomHeaders(c AuxClient) map[string]string
- func AuxClientDefaultHeaders(c AuxClient) map[string]string
- func AuxClientEffectiveProvider(c AuxClient) string
- func AuxExcTypeName(err error) string
- func AuxFallbackEntryAPIKey(ctx context.Context, entry map[string]any) string
- func AuxInterruptProtection(ctx context.Context, active bool, cancelCheck AuxCancelCheck, ...) context.Context
- func AuxIsConnectionError(err error) bool
- func AuxModelForProvider(ctx context.Context, providerID string, preferFast bool) string
- func AuxProbeMode(ctx context.Context) context.Context
- func AuxProgressHook(ctx context.Context, hook func() error) context.Context
- func AuxReadMainModel(ctx context.Context) string
- func AuxReadMainProvider(ctx context.Context) string
- func AuxStreamDeadline(ctx context.Context, deadline AuxStreamDeadlineFunc) context.Context
- func AuxThreadLocalHook(ctx context.Context, local AuxHookLocal, hook func() error) context.Context
- func AuxiliaryMaxTokensParam(ctx context.Context, value int, model string) map[string]any
- func AuxiliaryTaskConfig(ctx context.Context, task string) (map[string]any, error)
- func AzureLookupContextLength(ctx context.Context, model, baseURL, apiKey string, ...) int
- func BedrockFoundationModelCount(ctx context.Context, region string) (int, error)
- func BedrockGuardrailConfig(ctx context.Context) map[string]any
- func BedrockModelRoutableFromRegion(modelID, regionName string) bool
- func BedrockRegionGeoPrefix(regionName string) string
- func BedrockStreamCall(ctx context.Context, agent ChatCompletionAgent, apiKwargs map[string]any, ...) (any, error)
- func BindImageTokenCost(ctx context.Context, model, baseURL string) context.Context
- func BindProfileSecretScope(ctx context.Context, h string) context.Context
- func Blake2bSum(data []byte, size int) []byte
- func BodyRetryAfter(body any) (time.Duration, bool)
- func BotAuthorID(profile, origin string) string
- func BoundRegistryKey(ctx context.Context) (string, int64)
- func BufferConnectExhaustedNotice(agent StreamDiagAgent, err error, attempts int, baseURL string)
- func BuildAnthropicBedrockClient(ctx context.Context, region string, timeout float64) (any, error)
- func BuildAnthropicClient(ctx context.Context, apiKey any, baseURL string, timeout float64, ...) (any, error)
- func BuildAuxPickerRows(ctx context.Context, currentProvider, currentModel, currentBaseURL string, ...) ([]map[string]any, error)
- func BuildEntraTokenProviderIn(ctx context.Context, cfg *EntraIdentityConfig, scope string, ...) (func(context.Context) (string, error), error)
- func BuildKeepaliveHTTPClient(baseURL string, asyncMode bool, verify TLSVerify) *http.Client
- func BuildModelOptionsPayload(ctx context.Context, pc PickerConfigContext, ...) (map[string]any, error)
- func BuildModelsPayload(ctx context.Context, pc PickerConfigContext, opts ModelsPayloadOptions) (map[string]any, error)
- func BuildNvidiaNIMHeaders(baseURL string) map[string]string
- func BuildORHeaders(ctx context.Context, orConfig map[string]any) (map[string]string, error)
- func BuildOpenAIToolCall(callID, name, arguments string) state.ToolCall
- func BuildPlanPrompt(task string) string
- func BuildProfileSecretScope(h string) map[string]string
- func BuildPromptCachePlan(apiMessages, tools []map[string]any, o PromptCachePlanOptions) ([]map[string]any, []map[string]any)
- func BuiltinAuxTaskKeys() []string
- func BuiltinNameUserEntry(ctx context.Context, name string, providers map[string]any) (string, bool)
- func BypassChatSDKRequestTransform(requestKwargs map[string]any, client any) map[string]any
- func BypassSDKRequestTransform(requestKwargs map[string]any, fields []string, keepSlots bool) map[string]any
- func CacheTTLMeansDisabled(ttl any) bool
- func CachedProviderModelIDs(ctx context.Context, provider string, opts CachedModelsOptions) []string
- func CalibrateImageTokenCost(ctx context.Context, model, baseURL string, anchor *UsageAnchor, ...) (context.Context, int, bool)
- func CallLLM(ctx context.Context, kwargs map[string]any) (any, error)
- func CallableKeyIdentity(v any) (uintptr, bool)
- func CanonicalAPIMode(apiMode string) string
- func CanonicalCustomIdentity(ctx context.Context, baseURL, configProvider, model, requested string) string
- func CapToRunBudget(agent any, timeout float64) float64
- func CaptureLaunchEnv() map[string]string
- func CapturedAuxCancelRequested(check AuxCancelCheck) bool
- func CarrierRecord(ctx context.Context, assistantMessage map[string]any) map[string]any
- func CatalogByID() map[string]CatalogEntry
- func CatalogCachePath(ctx context.Context) string
- func CatalogItemIsGeneration(item any) bool
- func CatalogModelIDs(rows []CatalogModel) []string
- func CatalogProviderAlias(name string) (string, bool)
- func CatalogProviderAliases() map[string]string
- func CatalogProviderLabel(slug string) string
- func CatalogRefreshInterval(ctx context.Context) time.Duration
- func ChatCatalogIDs(items any) []string
- func ChatWireNeedsKeyOrder(msg map[string]any, keys []string) bool
- func CheckCodexBinary(codexBin string, minVersion [3]int) (bool, string, error)
- func CheckCodexBinaryOK(codexBin string) (bool, string)
- func CheckFallbackEntryLive(ctx context.Context, entry map[string]any, result *FallbackEntryCheck, ...) error
- func ClaimKeptNotices(ctx context.Context) []string
- func ClaimStreamWriter(agent any) int
- func ClampEffort(effort string, supported []string) string
- func ClampReasoningEffortToSupported(effort string, supported []string) string
- func ClampTimeout(seconds float64) (time.Duration, bool)
- func ClaudeCodeCredentialsPath() string
- func CleanErrorMessage(errorMsg string) string
- func CleanupStaleAsyncClients()
- func CleanupTaskResources(ctx context.Context, agent ChatCompletionAgent, taskID string)
- func ClearAllProviderModelsCache(ctx context.Context)
- func ClearBitwardenCaches(homePath string)
- func ClearCatalogFetchBackoff(ctx context.Context)
- func ClearCodexPoolQuotaCooldowns(env PoolEnv, accessToken string) int
- func ClearOnePasswordCaches(homePath string)
- func ClearProviderModelsCache(ctx context.Context, provider string)
- func ClearWindowOverride(modelID string) error
- func CmdMoA(ctx context.Context, out io.Writer, args MoAArgs) error
- func CmdModel(ctx context.Context, ns map[string]any, w io.Writer) (code int, err error)
- func CmdProxy(ctx context.Context, h string, ns map[string]any, w, errw io.Writer) (int, error)
- func CodexCatalogCredentialIdentity(ctx context.Context) string
- func CodexCatalogURLs(baseURL string) []string
- func CodexCloudflareHeaders(accessToken, baseURL string) map[string]string
- func CodexRuntimeCommand(ctx context.Context, h string, ns map[string]any, w io.Writer) (int, error)
- func CodexRuntimeParseArgs(argString string) (*string, []string)
- func CodexStaleTimeoutFloor(estTokens int) float64
- func CodexTokenCountDelta(source string, counts map[string]any) state.TokenCountDelta
- func CodexToolsExposedTools() []string
- func CoerceAPIErrorDetail(value any) string
- func CoerceFloat(value any, def float64) float64
- func CoerceInsecure(sslVerify any) bool
- func CoerceLLMMessage(response any) any
- func CoercePositiveTimeout(raw any) (float64, bool)
- func CoercePrivacyFilter(value any) string
- func CoerceProviderID(value any) string
- func CoerceToolName(name any, fallback string) string
- func CombinedSelectionMessage(warnings []SelectionWarning) string
- func CompatibleCustomProviders(cfg map[string]any) []map[string]any
- func CompressionThresholdForModel(model, provider string, allowCodexGPT55Autoraise bool) (float64, bool)
- func ConfigFacadeBrowserEnvSources(h string) config.BrowserEnvSources
- func ConfigFacadeStampHooks() config.StampHooks
- func ConfigLoader(h string) func() map[string]any
- func ConfigureBedrockOpenAIClientKwargs(ctx context.Context, clientKwargs map[string]any, timeout *float64) error
- func ConfiguredCustomProviderIDs(ctx context.Context) map[string]bool
- func ConfiguredProviderName(ctx context.Context, section string, logger *slog.Logger) string
- func ConnectExhaustedNotice(err error, attempts int, baseURL string) string
- func ConsumeOAuthHealNotices() []string
- func ContextCacheKey(model, baseURL string) string
- func ContextRouteMismatch(configuredBaseURL, activeBaseURL, configuredProvider, activeProvider string) bool
- func ConversationContext(ctx context.Context) string
- func CoreDeclaredEnvNames() map[string]bool
- func CountImages(messages []*state.Message) int
- func CreateAnthropicMessage(ctx context.Context, client any, apiKwargs map[string]any, logPrefix string, ...) (any, error)
- func CredentialLabel(key any) string
- func CredentialPoolEntryServesEndpoint(entry PooledCredential, baseURL string) bool
- func CredentialPoolMatchesProvider(ctx context.Context, poolProvider, provider, baseURL string) bool
- func CredentialPoolMatchesProviderIn(poolProvider, provider, baseURL string, cfg map[string]any) bool
- func CredentialSourceOf(key any) string
- func CtxBytes(profile ModelProfile, window int, flashAttention bool) int64
- func CuratedCatalogProviders() []string
- func CuratedCatalogRows() map[string][]string
- func CurrentAuxProgressHook(ctx context.Context) func() error
- func CurrentAuxStreamDeadline(ctx context.Context) (time.Time, bool)
- func CurrentCachePath(h, name string) string
- func CurrentImageTokenCost(ctx context.Context) int
- func CurrentPromptReadingHook(ctx context.Context) func(seconds float64)
- func CurrentSecretScope(ctx context.Context) map[string]string
- func CurrentSecretScopeHome(ctx context.Context) string
- func CursesPromptChoice(question string, choices []string, def int, description string) (int, error)
- func CustomEntryForEndpoint(baseURL, providerName string, cfg map[string]any) (string, map[string]any, bool)
- func CustomProviderAPIMode(baseURL string, customProviders []map[string]any, cfg map[string]any) string
- func CustomProviderAliases(displayName, providerKey string) map[string]bool
- func CustomProviderContextLength(model, baseURL string, customProviders []map[string]any, cfg map[string]any) int
- func CustomProviderExtraBodyForAgent(provider, model, baseURL string, customProviders []map[string]any) map[string]any
- func CustomProviderExtraHeaders(baseURL string, customProviders []map[string]any, cfg map[string]any) map[string]string
- func CustomProviderModelCapability(model, baseURL, capability string, customProviders []map[string]any, ...) (value bool, known bool)
- func CustomProviderSessionAffinityHeader(baseURL string, customProviders []map[string]any, cfg map[string]any) string
- func CustomProviderSessionAffinityHeaders(ctx context.Context, baseURL, sessionID string) map[string]string
- func CustomProviderSlug(displayName, providerKey string) string
- func DaybreakOffered(model, providerName, baseURL, accessToken string) (bool, error)
- func DeclaredAuthProviders(manifest map[string]any) []string
- func DeclaredConversationScope(a *CacheScopeAgent) string
- func DeclaredConversationScopeSafe(a *CacheScopeAgent) (scope string)
- func DeclaredModelIDs(value any) []string
- func DeclaresModelProviderKind(pluginDir string) bool
- func DecodeJWTClaims(token string) map[string]any
- func DecodeMoATurn(message string) (string, map[string]any, error)
- func DecorateXAIEntitlementError(detail string) string
- func DeepinfraBaseURL(ctx context.Context, section map[string]any) string
- func DeepinfraModelIDs(ctx context.Context, tag string, forceRefresh bool) []string
- func DefaultCABundlePath() string
- func DefaultContextLengths() map[string]int
- func DefaultModelFromCatalogCache(ctx context.Context, provider string) string
- func DeferStartupNotice(ctx context.Context, message string)
- func DeliveryEnv(ctx context.Context, env *tools.Env, author *pyjson.Object, profileHome string) (map[string]string, error)
- func DeriveResponsesFunctionCallID(callID, responseItemID string) string
- func DescribeActiveEntraCredential(ctx context.Context, cfg *EntraIdentityConfig, scope string, ...) map[string]any
- func DescribePrimary(cfg map[string]any) (string, error)
- func DetectLocalServerType(ctx context.Context, baseURL, apiKey string) string
- func DetectProviderForModel(ctx context.Context, modelName, currentProvider string) (string, string, bool)
- func DetectStaticProviderForModel(ctx context.Context, modelName, currentProvider string) (string, string, bool)
- func DetectVendor(model string) string
- func DirectAPICall(ctx context.Context, agent ChatCompletionAgent, apiKwargs map[string]any) (resp any, err error)
- func DirectAliasAPIKey(ctx context.Context, alias DirectAlias) (string, error)
- func DirectAliasRuntimeRequest(ctx context.Context, alias DirectAlias) (string, string, error)
- func DiscoverFlag(entry map[string]any) bool
- func DiscoverUncoveredProviders(availableEnvNames []string) []string
- func DispatchCodexToolsMCPServerEntry()
- func DispatchNonstreamingAPIRequest(ctx context.Context, agent ChatCompletionAgent, apiKwargs map[string]any, ...) (any, error)
- func DotenvSetValues(path string) (map[string]string, error)
- func DotenvUnreadable(path string) bool
- func DropExpired[K comparable, V any](values map[K]V, stamps map[K]time.Time, ttl time.Duration, now time.Time)
- func DropModelKey(ctx context.Context, modelCfg map[string]any, key string) error
- func DropStaleModelRoute(modelCfg map[string]any, provider string, cfg map[string]any) (map[string]any, bool)
- func DropUnofferableModelIDs(rows []any)
- func DropsReplayItemIDs(baseURL string) bool
- func DumpIfModel(value any) any
- func EagerFallbackStatus(cl *Classified, isUpstream, isTransport bool) string
- func EffectiveAuxTimeout(ctx context.Context, task string, timeout *float64) float64
- func EffectiveCacheTTL(ttl, model, providerName string) string
- func EffectiveRuntimeProvider(entry map[string]any, rt *Runtime) string
- func EffortDisplayLabel(effort, provider, model, apiMode string) string
- func EffortLadderIndex(level string) int
- func EgressCommand(ctx context.Context, h string, ns map[string]any, w io.Writer) (int, error)
- func EmitStreamDrop(agent StreamDiagAgent, err error, attempt, maxAttempts int, midToolCall bool, ...)
- func EnabledSecretSourceNames(secretsCfg map[string]any, homePath string) map[string]bool
- func EnsureAuditLog(auditPath string) error
- func EnsureBuiltinSecretSources()
- func EntriesForRoute(baseURL string, customProviders []map[string]any, cfg map[string]any) []map[string]any
- func EntriesLabel(n int) string
- func EntryDeclaresCredential(entry map[string]any) bool
- func EntryModelsDiscovered(entry any) bool
- func EntryURL(entry map[string]any) string
- func EnvWriterLaunchDenylist() map[string]bool
- func EnvelopeToolPartCacheMarkersSupported(providerName, baseURL string) bool
- func EstimateMessageTokensRough(msg any, imageCost int) int
- func EstimateMessagesTokens(msgs []*state.Message, imageCost int, chargeStaleThinking bool) int
- func EstimateNativeAnthropicMessagesTokens(ctx context.Context, messages []*state.Message) int
- func EstimateNativeAnthropicRequestTokens(ctx context.Context, messages []*state.Message, system string, ...) int
- func EstimateRequestContextTokens(ctx context.Context, payload any) int
- func EstimateRequestTokens(ctx context.Context, msgs []*state.Message, system string, ...) int
- func EstimateRowsTokens(rows []map[string]any, imageCost int) int
- func EstimateTokens(text string) int
- func EstimateToolsTokens(tools []map[string]any) int
- func EvictOldScreenshots(result []map[string]any)
- func EvictOldest[K comparable, V any](cache map[K]V, key K, stampOf func(V) time.Time, limit int, ...)
- func ExactMoAPresetName(raw any, text string) string
- func ExcStatusCode(err error) int
- func ExpandDirectAPIAlias(ctx context.Context, provider, existingBase string) (string, string)
- func ExternalProcessLaunchEnvNames() map[string]bool
- func ExtractAPIErrorContext(err error) map[string]any
- func ExtractCompressFlags(rawArgs string) (string, bool, bool)
- func ExtractContentOrReasoning(response any, maxReasoningChars int) string
- func ExtractFallbackFromModelCfg(modelCfg any) (map[string]any, bool, error)
- func ExtractToolCallsFromText(text string) ([]state.ToolCall, string, error)
- func FallbackAPIModeHint(ctx context.Context, fb map[string]any, fbProvider string, ...) (bool, string, error)
- func FallbackAPIModeResolved(ctx context.Context, agent FallbackAPIModeAgent, ...) (string, error)
- func FallbackAdd(ctx context.Context, w io.Writer, h string, store *Store, picker func() error) error
- func FallbackClear(ctx context.Context, w io.Writer, h string, ...) error
- func FallbackCommand(ctx context.Context, h string, ns map[string]any, w, errw io.Writer) (code int, err error)
- func FallbackList(ctx context.Context, w io.Writer, h string) error
- func FallbackReasonText(reason FailoverReason) string
- func FallbackRemove(ctx context.Context, w io.Writer, h string, ...) error
- func FastModeUnprovisioned(apiErr *APIError, extraBody map[string]any, headers http.Header) bool
- func FeatureInUse(f *LeftCoreFeature, h string, processEnv bool) bool
- func FetchAPIModels(ctx context.Context, apiKey, baseURL string, timeout time.Duration, ...) ([]string, bool)
- func FetchBitwardenSecrets(opts BitwardenFetchOptions) (map[string]string, []string, error)
- func FetchCodexCatalogEntries(get func(string) (*probeResponse, error), baseURL string) ([]any, int, error)
- func FetchEndpointModelMetadata(ctx context.Context, baseURL, apiKey string, forceRefresh bool) map[string]map[string]any
- func FetchLMStudioModels(ctx context.Context, apiKey any, baseURL string, timeout time.Duration) ([]string, error)
- func FetchModelMetadata(ctx context.Context, forceRefresh bool) map[string]map[string]any
- func FetchModelsDev(ctx context.Context, forceRefresh bool) map[string]any
- func FetchOllamaCloudModels(ctx context.Context, opts OllamaCloudFetch) []string
- func FetchOllamaLocalModels(ctx context.Context, baseURL string, timeout time.Duration, ...) ([]string, bool)
- func FetchOnePasswordSecrets(opts OnePasswordFetchOptions) (map[string]string, []string, error)
- func FileLock(lockPath string, timeout time.Duration, timeoutMessage string) (release func(), err error)
- func FillProviderEnvVars()
- func FindBws(installIfMissing bool) string
- func FindCustomProviderIdentity(baseURL string, cfg map[string]any) string
- func FindCustomProviderIdentityByModel(model string, cfg map[string]any) string
- func FindEntryForModel(modelID string) (*CatalogEntry, *QuantVariant)
- func FindFirstThinkTag(buf []rune, tags [][]rune) (int, int)
- func FindOp(binaryPath string) string
- func FindProviderEntry(providers any, key any) (string, map[string]any)
- func FingerprintSecretValue(value any) string
- func FinishAuxCallHooks(ctx context.Context, hooks *AuxCallHooks, response any, callErr error, ...)
- func FirstChoiceMessage(response any) (any, error)
- func FirstProxyEnvValue() string
- func FixedTemperatureForModel(model, baseURL, provider string) (omit bool, fixed *float64, err error)
- func FlattenExceptionChain(err error) string
- func FlattenMessageText(content any, sep string) string
- func FloorReasoningConfig(reasoningConfig any) any
- func FootprintBytes(profile ModelProfile, window int, flashAttention bool, overheadBytes int64) int64
- func ForceCloseTCPSockets(client any) int
- func ForgetMessageTokenMemo(messages any, keep any) int
- func ForgetPluginGrants(plugin string) error
- func FormatAuthError(err *AuthError) string
- func FormatCostLabel(amount *big.Rat) string
- func FormatCount(n int) string
- func FormatDurationCompact(seconds float64) string
- func FormatEgressStatusText(h string, showTokens bool) (string, error)
- func FormatFallbackEntry(entry map[string]any) string
- func FormatModelForDisplay(modelName string) string
- func FormatPercentUsed(usedFraction float64) string
- func FormatPricePerMtok(perToken string) string
- func FormatRateLimitCompact(s *RateLimitState, now time.Time) string
- func FormatResetWindow(d time.Duration) string
- func FormatResetsIn(resetsAtMs, nowMs *int64) string
- func FormatRetirementIssue(issue RetirementIssue) string
- func FormatRuntimeProviderError(err error) string
- func FormatSeconds(seconds float64) string
- func FormatSecretSourceSuffix(h, envVar string) string
- func FrozenRuntimeConfig(ctx context.Context) map[string]any
- func GGUFReadSkippable(err error) bool
- func GetAPIKeyProviderStatus(env PoolEnv, providerID string) map[string]any
- func GetAnthropicKey(ctx context.Context) string
- func GetAuthStatus(env PoolEnv, providerID string) map[string]any
- func GetAuthenticatedProviderSlugs(ctx context.Context, currentProvider string, userProviders map[string]any, ...) []string
- func GetAvailableVisionBackends(ctx context.Context) ([]string, error)
- func GetCachedContextLength(ctx context.Context, model, baseURL string, bedrockConfirmed bool) (int, bool)
- func GetCatalog(ctx context.Context, forceRefresh bool) map[string]any
- func GetCodexAuthStatus(env PoolEnv) map[string]any
- func GetCodexModelIDs(ctx context.Context, accessToken, baseURL string) ([]string, bool)
- func GetConfiguredCodexBinary(cfg map[string]any) string
- func GetContextLengthFromProviderError(errorMsg string, current int) (int, bool)
- func GetCurrentCodexRuntime(cfg map[string]any) string
- func GetCustomProviderPoolKey(baseURL, providerName string, cfg map[string]any) string
- func GetDefaultModelForProvider(ctx context.Context, provider string) string
- func GetEnvPreferDotenv(env PoolEnv, key string) string
- func GetExternalProcessProviderStatus(env PoolEnv, providerID string) map[string]any
- func GetFallbackChain(cfg map[string]any) []map[string]any
- func GetLoadingProgress() map[string]LoadProgress
- func GetMinimaxOAuthAuthStatus(env PoolEnv) map[string]any
- func GetNamedCustomProvider(ctx context.Context, name string) map[string]any
- func GetPoolStrategy(cfg map[string]any, provider string) string
- func GetPreferredSilentDefaultModel(ctx context.Context, provider string) string
- func GetPrefillProgress(model string) (processed int64, ok bool, err error)
- func GetProviderLabel(ctx context.Context, providerID string) string
- func GetProviderRequestTimeout(ctx context.Context, providerID, model string) (float64, bool)
- func GetProviderStaleTimeout(ctx context.Context, providerID, model string) (float64, bool)
- func GetQwenAuthStatus(env PoolEnv) map[string]any
- func GetSecret(ctx context.Context, name string) (string, bool, error)
- func GetSecretStr(ctx context.Context, name, def string) string
- func GetXAIOAuthAuthStatus(env PoolEnv) map[string]any
- func Getpass(prompt string) (string, error)
- func GrokSupportsReasoningEffort(model string) bool
- func HandleMaxIterations(ctx context.Context, agent ChatCompletionAgent, messages *[]map[string]any) (final string, err error)
- func HasAWSCredentials(ctx context.Context, instanceMetadata bool) bool
- func HasAccountUsage(ctx context.Context, provider string) bool
- func HasCodexContextVariant(modelBare string) bool
- func HasCompactionCheckpoint(items []map[string]any) bool
- func HasCuratedCatalog(provider string) bool
- func HasKnownPricing(ctx context.Context, modelName, provider, baseURL, apiKey string) bool
- func HasNamedCustomProvider(ctx context.Context, h, name string) bool
- func HasRateLimitHeaders(lowered map[string]string) bool
- func HasUsableSecret(value any, minLength int) bool
- func HeaderKeys(m map[string]string) []string
- func HomeRawConfig(h string) map[string]any
- func HomeRawConfigForWrite(path string) (map[string]any, error)
- func HomeYAMLLayers(h string) (map[string]any, error)
- func HookFailed(p *Profile, hook string, scope any) bool
- func HookJSONable(value any, caps HookJSONCaps) any
- func HookPayloadMaxChars() int
- func HostGatedEnvKeyCandidates(ctx context.Context, h, baseURL string, ollama bool) []string
- func HostInstallHint(baseURL string) string
- func HostMatches(rawURL, domain string) bool
- func HostSetupFlow(asker SetupAsker, out io.Writer, fn func() error) (err error)
- func HostedModelEntry(entry string) bool
- func Hostname(rawURL string) string
- func HydrateProfileSecretSources(h string) map[string]string
- func IcebathOAuthFile(env PoolEnv) string
- func IcebathOverlays(ctx context.Context) map[string]IcebathOverlay
- func ImageCostContext(ctx context.Context, cost *int) context.Context
- func ImageDimensionsFromBytes(raw []byte) (int, int, bool)
- func ImagesAllWithinManyImageLimit(datas []string) bool
- func InstallBws() (string, error)
- func InstallOpener(opener *Opener)
- func InstallPluginManagerHooks(h PluginManagerHooks)
- func InstallSafeStdio()
- func InstallTrustStore() bool
- func InterruptibleAPICall(ctx context.Context, agent ChatCompletionAgent, apiKwargs map[string]any) (any, error)
- func InterruptibleStreamingAPICall(ctx context.Context, agent ChatCompletionAgent, apiKwargs map[string]any, ...) (any, error)
- func InvalidateBedrockRuntimeClient(ctx context.Context, region string) bool
- func InvalidateCachedContextLength(ctx context.Context, model, baseURL string)
- func IronAllowlistedEnv() map[string]string
- func IsActualRoute(providerName, baseURL string) bool
- func IsAggregatorModelProvider(name string) bool
- func IsAggregatorProvider(slug string) bool
- func IsAnthropicFastModeModel(model string) bool
- func IsAnthropicOAuthToken(key string) bool
- func IsAvailableSafe(provider AvailabilityProvider, logger *slog.Logger, format string, ...) bool
- func IsBorrowedCredentialSource(source, providerID string) bool
- func IsCancelled(err error) bool
- func IsCapabilityRejection(err error) bool
- func IsClaudeCodeTokenValid(creds map[string]any) bool
- func IsCodex900kBase(model string) bool
- func IsCodexContextVariant(model string) bool
- func IsCodexGPT54OrGPT55(model, provider string) bool
- func IsCodexSpark(model, provider string) bool
- func IsCustomRuntime(env PoolEnv, provider, requestedProvider, baseURL string) bool
- func IsEntitlement403(agent AuthRecoveryAgent, statusCode int, errorContext map[string]any) bool
- func IsEntitlementFailure(errorContext map[string]any, status int) bool
- func IsEnvSettingKey(key string) bool
- func IsExpiring(expiresAt any, skew time.Duration) bool
- func IsExternalProcessProvider(ctx context.Context, provider string) bool
- func IsForeignProviderEndpoint(provider, baseURL string) bool
- func IsForkCacheScope(scope string) bool
- func IsGeminiNativeProviderName(name string) bool
- func IsGlobalEnv(name string) bool
- func IsGrok46Family(model string) bool
- func IsImportSourceName(name string) bool
- func IsKnownNonChatModel(model string) bool
- func IsLiveFirstPickerProvider(provider string) bool
- func IsLlamaCppAlias(name string) bool
- func IsLocalEndpoint(baseURL string) bool
- func IsLocalValidationError(err error) bool
- func IsLoopbackHost(host string) bool
- func IsManagedEndpoint(baseURL string) bool
- func IsManagedLocalEndpoint(baseURL string) bool
- func IsManagedProvider(provider, baseURL string) (managed bool)
- func IsMandatoryThinkingClaude(model string) bool
- func IsModelsDevPreferred(provider string) bool
- func IsMultiplexActive(ctx context.Context) bool
- func IsNativeAnthropicHost(baseURL string) bool
- func IsNativeCompactionRejection(errText string, statusCode int) bool
- func IsNativeGeminiBaseURL(baseURL string) bool
- func IsNetworkError(err error) bool
- func IsNetworkResolutionFailure(err error) bool
- func IsNoninteractive() bool
- func IsOAuthToken(key string) bool
- func IsOfficialOpenAIHost(rawURL string) bool
- func IsOpencodeTarget(provider, baseURL string) bool
- func IsOutputCapError(errorMsg string) bool
- func IsPresetFieldPath(parts []string) bool
- func IsProcessHome(h string) bool
- func IsPromptInterrupt(err error) bool
- func IsProviderEnabled(providerCfg any) bool
- func IsProviderExplicitlyConfigured(env PoolEnv, providerID string) bool
- func IsProviderStreamParseError(err error) bool
- func IsProxyLoopbackHost(host string) bool
- func IsRateLimitedAuthError(err error) bool
- func IsReasoningFieldRejection(errorMsg string) bool
- func IsReasoningLevelRejection(errorMsg string) bool
- func IsReasoningRequiredRejection(errorMsg string) bool
- func IsRefreshableOAuthProvider(provider string) bool
- func IsRegisteredEnvName(name string) bool
- func IsRepetitionDominated(text string) bool
- func IsRotationConsumedUncommitted(secret, sourcePath string) bool
- func IsRoutableProvider(ctx context.Context, provider string) bool
- func IsRoutingAggregator(providerName string) bool
- func IsRunawayRepetition(text string) bool
- func IsSecretPayloadKey(key string) bool
- func IsSensitiveHookKey(key string) bool
- func IsSetupHiddenEnv(name string) bool
- func IsSlotKeyedCacheRoute(providerName, model, baseURL string) bool
- func IsStreamEventOrderError(err error) bool
- func IsStreamStall(err error) bool
- func IsTerminalAnthropicRefreshError(err error) bool
- func IsTerminalPluginRefreshError(err error) bool
- func IsTokenProvider(value any) bool
- func IsTruthyValue(v any) bool
- func IsValidEnvName(name string) bool
- func IsVertexExpressBaseURL(normalized string) bool
- func IsZAICodingOverload(baseURL, model string, err error) bool
- func IterationSummaryAPIMessages(agent ChatCompletionAgent, messages []map[string]any) []map[string]any
- func JitteredBackoff(attempt int, opts BackoffOptions) time.Duration
- func KVDtypeFactor(flashAttention bool) float64
- func KillProcessTree(pid int, sig syscall.Signal) bool
- func KnownReasoningFloor(ctx context.Context, reasoningConfig any, ...) (any, error)
- func LMStudioModelReasoningOptions(ctx context.Context, model, baseURL string, apiKey any, timeout time.Duration) []string
- func Label(providerID string) string
- func LabelFromToken(token, fallback string) string
- func Ladder(native int) []int
- func LadderReason(reason FailoverReason) bool
- func LadderStopHint(platform string) string
- func LanguageCatalog() config.LanguageCatalog
- func LatchedRetireCount(retire int, carrierIDsNewestFirst []string, retiredIDs map[string]bool) int
- func LaunchArgs(profile ModelProfile, decision *WindowDecision, ...) []string
- func LaunchModelSeed(ctx context.Context, sourceCfg map[string]any) map[string]any
- func LaunchSecretScope(launchHome string) map[string]string
- func LaunchSecretScopeCtx(ctx context.Context, launchHome string) map[string]string
- func LaunchTerminalEnv() map[string]string
- func LearnedImageTokenCost(ctx context.Context, model, baseURL string) int
- func LeftCoreFailedRecently(h, plugin string) bool
- func LeftCoreFailureStamp(h, plugin string) string
- func LeftCoreFirstCause(errText string) string
- func LeftCoreVersions() []int
- func ListAgenticModels(ctx context.Context, provider string, allowNetwork bool) []string
- func ListAuthenticatedProviders(ctx context.Context, opts AuthenticatedProvidersOptions) ([]map[string]any, error)
- func ListCustomPoolProviders(store *Store) []string
- func ListModelsDevModels(ctx context.Context, provider string, allowNetwork bool) []string
- func ListPickerProviders(ctx context.Context, opts PickerProvidersOptions) ([]map[string]any, error)
- func LiveLoopTable[T any](tables map[any]T, loop any, lock sync.Locker, same func(a, b any) bool, ...) T
- func LlamacppContext(client *probeClient, serverURL, model string) (int, bool, error)
- func LoadConfigSafe(ctx context.Context, h string) map[string]any
- func LoadDotenvFile(path string, override bool) error
- func LoadIcebathDotenv(ctx context.Context, opts DotenvLoadOptions) ([]string, error)
- func LoadModelMetadataDiskCache(ctx context.Context) map[string]map[string]any
- func LoadWindowOverrides() map[string]int
- func LocalModelsActivate(ctx context.Context, modelID string) (map[string]any, error)
- func LocalModelsCatalog(ctx context.Context) (map[string]any, error)
- func LocalModelsHardware(ctx context.Context) (map[string]any, error)
- func LocalModelsHumanGB(n float64) string
- func LocalModelsJobView(jobID string) (map[string]any, error)
- func LocalModelsPauseJob(jobID string) bool
- func LocalModelsQuickstart(ctx context.Context, modelID string) (map[string]any, error)
- func LocalModelsRuntimeInstall(ctx context.Context, backendRequest string) (map[string]any, error)
- func LocalModelsStatus(ctx context.Context) (map[string]any, error)
- func LocalOrigin() string
- func LocalRuntimeStatePath() string
- func LockConfigMutation(ctx context.Context) (context.Context, func())
- func LogStreamRetry(agent StreamDiagAgent, kind string, err error, attempt, maxAttempts int, ...)
- func LoginCommand(out io.Writer)
- func LoginMinimaxOAuth(env PoolEnv, out io.Writer, args MinimaxLoginArgs) error
- func LoginOpenAICodex(env PoolEnv, out io.Writer, args CodexLoginArgs, forceNewLogin bool) error
- func LoginXAIOAuth(env PoolEnv, out io.Writer, args XAILoginArgs, forceNewLogin bool) error
- func LogoutCommand(env PoolEnv, providerID string, out io.Writer) error
- func LongDecodeStaleMultiplier(apiPayload map[string]any) int
- func LongestDefaultContextMatch(modelLower string) (int, bool)
- func LooksLikeOpenRouterKey(value string) bool
- func LookupModelsDevContext(ctx context.Context, provider, model string, allowNetwork bool) (int, bool)
- func LowerHeaders(h http.Header) map[string]string
- func LowerKey(name string) string
- func ManagedDotenvKeys() []string
- func ManagedLocalNetloc() string
- func ManagedModelSupportsVision(ctx context.Context, modelID string) (vision *bool)
- func MarkRotationConsumedUncommitted(sourcePath string, secrets ...string)
- func MaskAPIKeyForLogs(key any) string
- func MaskedSecretPrompt(prompt string) (string, error)
- func MatchesReasoningEchoFamily(family, provider, model, baseURL string) (bool, error)
- func MaterializeBearerForHTTP(ctx context.Context, value any) (string, error)
- func MaxPartialThinkSuffix(buf []rune, tags [][]rune) int
- func MaybeGrowWindow(modelID, baseURL string, sessionTokens, currentWindow int, ...) (int, bool, error)
- func MergeEndpointSeed(ctx context.Context, dstCfg, seed map[string]any, claimed map[string]bool) map[string]any
- func MergeHeaderMaps(maps ...map[string]string) map[string]string
- func MergeInterimReasoningItems(prior, newer []map[string]any) []map[string]any
- func MergeModelCooldowns(maps ...any) map[string]float64
- func MergeSessionAffinityHeaders(ctx context.Context, kwargs map[string]any, ...) map[string]any
- func MergeSnapshotAuthPreservingLiveSingleUseGrants(snapshot, live map[string]any) map[string]any
- func MessageField(message any, field string) any
- func MessageFingerprint(m *state.Message) string
- func MigrateAllLeftCoreHomes(ctx context.Context, say func(string)) ([]string, error)
- func MigrateCommand(ctx context.Context, h string, ns map[string]any, w, errw io.Writer) (code int, err error)
- func MigrateFromAgents(ctx context.Context, icebathHome, sourceName string, opts AgentImportOptions) (int, error)
- func MinSwitchResetFromConfig(cfg config.Tree) time.Duration
- func MintProxyToken(prefix string) string
- func MissingCredentialsSuffix(ctx context.Context, provider string) string
- func MissingProviderCredentialsMessage(ctx context.Context, providerID string) string
- func MoAUsage() string
- func ModelAliasCanonical(model string) string
- func ModelChoiceSaveCount() int
- func ModelCommitBytes(modelBytes int64) int64
- func ModelConsumesThoughtSignature(model, baseURL, provider string) bool
- func ModelCooldownUntil(entry PooledCredential, model string) (float64, bool)
- func ModelDerivedAPIMode(ctx context.Context, provider, model, apiKey string) (string, bool)
- func ModelIDFromStem(stem string) string
- func ModelIDIsGeneration(modelID any) bool
- func ModelSearchText(model string) string
- func ModelSectionHasCredentials(ctx context.Context, cfg map[string]any) (bool, error)
- func ModelSelectionConfigUpdates(result ModelSwitchResult, currentModelCfg any) []config.KeyValue
- func ModelSupportsFastMode(model string) bool
- func ModelSupportsUltrafast(model string) bool
- func ModelsConfigIsAllowlist(value any, discovered bool) bool
- func ModelsDevIDFor(provider string) (string, bool)
- func ModelsDevProviderMap() map[string]string
- func ModelsNormalizeProvider(provider string) string
- func MovedCommandHint(ctx context.Context, prog, value, action string) string
- func MultiplexProcess() bool
- func NamedCustomProvider(ctx context.Context, h, name string) (map[string]any, error)
- func NamedCustomProviderEntry(ctx context.Context, name string, cfg map[string]any) map[string]any
- func NativeAnthropicAccountingProjection(messages any) (any, []string)
- func NativeAnthropicPreservesPriorThinking(baseURL, model string) bool
- func NativeCompactionContextManagement(g NativeCompactionGate, route ResponsesRoute) []map[string]any
- func NativeResponsesReplayInput(msgs []*state.Message, route ResponsesRoute, baseURL, model string, ...) ([]map[string]any, error)
- func NeedsReasoningEcho(provider, model, baseURL string) bool
- func NegotiateRequestTier(route Route, overrides map[string]any)
- func NewAuxChatStreamAccumulator(ctx context.Context, model string, totalCeiling *float64) *auxChatStreamAccumulator
- func NewBedrockOpenAISigV4Auth(ctx context.Context, region string, base http.RoundTripper) (http.RoundTripper, error)
- func NoProxyEntries(value *string) []string
- func NoProxyEntryMatches(entry, host string, port int, hasPort bool) bool
- func NonretryableLabel(reason FailoverReason) (string, bool)
- func NormalizeActualBaseURL(baseURL string) string
- func NormalizeAuxProvider(ctx context.Context, provider string) string
- func NormalizeBaseURLForMatch(value any) string
- func NormalizeCustomProviderEntry(raw any, providerKey string) map[string]any
- func NormalizeExtraHeaders(extraHeaders any) map[string]string
- func NormalizeFinishReason(raw any) any
- func NormalizeGeminiBaseURL(baseURL string) string
- func NormalizeMainModelAssignment(ctx context.Context, provider, model string) (string, string)
- func NormalizeMoAConfig(raw any) map[string]any
- func NormalizeModelForProvider(model, targetProvider string) string
- func NormalizeModelForProviderCtx(ctx context.Context, model, targetProvider string) string
- func NormalizeOpenCodeBaseURL(providerID string, mode APIMode, baseURL string) string
- func NormalizeOpenCodeModelID(providerID, modelID string) string
- func NormalizeProvider(name string) string
- func NormalizeProviderDef(ctx context.Context, name string) string
- func NormalizeRouteBaseURL(baseURL string) string
- func NoteCatalogItem(item any) bool
- func NoteGenerationModel(modelID any)
- func NoteLeftCoreFailure(h, plugin string)
- func NoteLeftCoreSuccess(h, plugin string)
- func OAuthAdmissionProblems(manifest map[string]any, pluginDir string) []string
- func OAuthAdmissionWarnings(manifest map[string]any, pluginDir string) []string
- func OAuthNotice(manifest map[string]any) string
- func OAuthReloginCommand(provider string) string
- func OAuthSurface(manifest map[string]any) map[string]bool
- func OfferAgentImport(ctx context.Context, icebathHome string, fromSetup bool) (string, error)
- func OfferedModelIDs(models []any, provider, baseURL string) []any
- func OllamaModelSupportsThinking(ctx context.Context, model, baseURL string, apiKey any, timeout time.Duration) (supported, known bool)
- func OpEnvAllowlist() []string
- func OpScrub(text string) string
- func OpenAIModelRejectsReasoning(model string) bool
- func OpenAIReasoningFamily(model string) string
- func OpenBrowserTab(target string) error
- func OpenCodeFamily(providerID string) string
- func OpenCredentialedURL(req *http.Request, timeout time.Duration, openerFactory OpenerFactory, ...) (*http.Response, error)
- func OpenRouterModelIDs(ctx context.Context, forceRefresh bool) []string
- func OpenRouterVariantBase(model string) string
- func OpencodeFamilyForCustom(requestedProvider, baseURL string) string
- func OpencodeSessionHeaders(ctx context.Context, provider, baseURL, sessionID string) map[string]string
- func OpenrouterPKCELogin(env PoolEnv, out io.Writer, openBrowser bool, timeout time.Duration) (map[string]any, error)
- func OrderRecordedMessages(v any) any
- func OrderedHeaders(m map[string]string, keys []string) map[string]string
- func OutboundImageRetireCount(carrierBlocks []int, reservedBlocks int, carrierBytes []int, reservedBytes int, ...) int
- func OverrideContextWindow(ctx context.Context, provider, model string) (int, bool)
- func OwnerSecretScope(ctx context.Context, h string) map[string]string
- func ParseAbsoluteTimestamp(value any) (float64, bool)
- func ParseAvailableOutputTokensFromError(errorMsg string) (int, bool)
- func ParseCodexVersion(output string) ([3]int, bool)
- func ParseContextLimitFromError(errorMsg string) (int, bool)
- func ParseExactServiceTier(raw string) (string, error)
- func ParseISOTimestamp(value any) (float64, bool)
- func ParseModelInput(ctx context.Context, raw, currentProvider string, customIDs map[string]bool) (string, string)
- func ParsePartialCompressArgs(rawArgs string) (bool, int, *string)
- func ParseReasoningEffort(effort any) map[string]any
- func ParseRetryAfter(value string) (time.Duration, bool)
- func ParseServiceTier(raw string) string
- func ParseTurnAuthor(raw any) *pyjson.Object
- func PersistModelSelection(ctx context.Context, result ModelSwitchResult, configPath string) error
- func PersistPoolEntries(env PoolEnv, provider string, payloads []map[string]any, ...) ([]map[string]any, bool)
- func PersistedAnchorTokens(ctx context.Context, store UsageAnchorStore, sessionID string, ...) (int, bool)
- func PersistedProviderID(ctx context.Context, provider string, providers map[string]any) string
- func PinnedTag(backend string) (string, error)
- func PlanCacheSectionsForDestination(ctx context.Context, messages, tools []map[string]any, ...) ([]map[string]any, []map[string]any)
- func PlatformConfiguredOn(h, name string) bool
- func PlatformInstallHint(ctx context.Context, platform string) string
- func PlatformTLSConfig() *tls.Config
- func PluginAuthHandler(provider string) func(action string, args []string, provider string) (bool, error)
- func PluginHomeLabel(h string) string
- func PluginInstallCommand(name, h string) string
- func PluginKey(pluginDir string) string
- func PluginLoadError(ctx context.Context, plugin string) string
- func PluginOAuthKey(pluginDir string) string
- func PluginPresent(plugin, h string) bool
- func PluginRefreshHookExists(provider string) bool
- func PluginRowIsExpiring(entry PooledCredential) bool
- func PluginSecretSources() plugins.SecretSources
- func PollUntil[T any](pred func() (T, bool), timeout, interval time.Duration) T
- func PoolBillingMessage(ctx context.Context, providerID, model string, pool interface{ ... }) (string, bool)
- func PoolCooldownMessage(ctx context.Context, providerID string) (string, bool)
- func PoolFailureReason(reason FailoverReason, errorContext map[string]any, billingUnverified bool) string
- func PoolKeySource() tools.PoolKeySource
- func PoolSockets(client any) []net.Conn
- func PreAgentFallbackNotice(primaryProvider, primaryModel, fallbackProvider, fallbackModel string) string
- func PredictedDecodeTokS(entry CatalogEntry, variant QuantVariant, budget HardwareBudget, spilled bool, ...) float64
- func PreflightKwargs(t Transport, apiKwargs map[string]any, ...) (map[string]any, error)
- func PrepareInheritedEndpointSeed(ctx context.Context, sourceCfg map[string]any) (map[string]any, map[string]bool)
- func PrewarmPickerCacheAsync(ctx context.Context) <-chan struct{}
- func PricingCacheScope(ctx context.Context, provider, baseURL string) string
- func PrimaryFailureWording(err *AuthError) (string, string)
- func PrimaryModelConfig(ctx context.Context, h string) map[string]any
- func PrintSetupBanner(lines ...string)
- func PrintSetupHeader(title string, gap bool)
- func ProbeLMStudioModels(ctx context.Context, apiKey any, baseURL string, timeout time.Duration) ([]string, bool, error)
- func ProbeOllamaLocalModels(ctx context.Context, baseURL string, timeout time.Duration, ...) ([]string, bool)
- func ProfileCLISelector(h string) string
- func ProfileConfigScope(ctx context.Context, h, launchHome string) context.Context
- func ProfileEnvVars(p Profile) []string
- func ProfileModelAPIMode(ctx context.Context, profile Profile, model string) (string, bool)
- func ProfileSecretSource() tools.ProfileSecretSource
- func PromptAPIKey(env PoolEnv, out io.Writer, pconfig Profile, ...) (string, bool, error)
- func PromptCacheBytes(live *HardwareBudget, modelBytes int64, residents int) *int64
- func PromptCachingDisabledFromConfig(ctx context.Context) bool
- func PromptChecklist(title string, items []string, preSelected []int) []int
- func PromptChoice(question string, choices []string, def int, description string) int
- func PromptReadingHook(ctx context.Context, hook func(seconds float64)) context.Context
- func PromptYesNo(question string, def bool, description string) bool
- func ProviderAllowsModelWhitespace(provider, baseURL string) bool
- func ProviderAuthKind(provider string) string
- func ProviderCatalogBySlug() map[string]ProviderDescriptor
- func ProviderEnvEntries() []config.NamedEnvVar
- func ProviderGroupForSlug(slug string) string
- func ProviderHasCredentials(ctx context.Context, provider string) bool
- func ProviderInstallHint(ctx context.Context, name string) string
- func ProviderLabel(provider string) string
- func ProviderLeftCore(name string) bool
- func ProviderOwnsRoute(provider, baseURL string) (owned bool, known bool)
- func ProviderResetDelay(resetAt any, now time.Time) (time.Duration, bool)
- func ProviderRetiredAliases(provider string) []string
- func ProviderRetryAfter(e *APIError) (time.Duration, bool)
- func ProviderSetupFailureLines(err error, retryCommand string) []string
- func ProviderSource(ctx context.Context, name string) string
- func ProviderStateIn(data AuthData, providerID string) map[string]any
- func ProvidersDictToCustomProviders(providersDict any) []map[string]any
- func PublishLRU[K comparable, V any](table map[K]V, order *[]K, key K, value V, limit int, siblings ...func(K)) []K
- func QueryOllamaNumCtx(ctx context.Context, model, baseURL, apiKey string) (int, bool)
- func QueryOllamaSupportsVision(ctx context.Context, model, baseURL, apiKey string) (supported, known bool)
- func ReadClaudeCodeCredentials(env PoolEnv) map[string]any
- func ReadEnvSetting(h, key string) (string, bool)
- func ReadFallbackChain(cfg map[string]any) []map[string]any
- func ReadIcebathOAuthCredentials(env PoolEnv) map[string]any
- func ReadStreamingErrorBody(response *http.Response, maxBytes int, timeout time.Duration) string
- func ReasoningConfigForWire(ctx context.Context, agent ChatCompletionAgent) map[string]any
- func ReasoningEchoFamily(provider, model, baseURL string) string
- func ReasoningStaleTimeoutFloor(model string) (time.Duration, bool)
- func RecordAuxUsage(ctx context.Context, response map[string]any, task, provider, baseURL string)
- func RecordCodexAppServerCompaction(agent CodexRuntimeAgent, turn *CodexTurnResult, approxTokens int, force bool) bool
- func RecordCodexAppServerUsage(agent CodexRuntimeAgent, turn *CodexTurnResult, messages []map[string]any) map[string]any
- func RecordCoreUse(h string, cfg map[string]any, version int) bool
- func RecordManagedDotenvKeys(keys []string)
- func RecoverAuthFailure(agent AuthRecoveryAgent, pool *Pool, req AuthRecoveryRequest) (bool, bool)
- func RecoverLeftCoreAtStartup(ctx context.Context, say func(string), gatewayStart bool) []string
- func RecoverLeftCoreForCommand(ctx context.Context, name string)
- func RecoverSetupExit(code *int)
- func RecurrentSpillBlocks(profile ModelProfile, spillBytes *int64) []int
- func RefreshAccountUsageAsync(ctx context.Context, providers []string) []<-chan struct{}
- func RefreshAccountUsageEntriesAsync(ctx context.Context, requests []AccountUsageRefreshRequest) []<-chan struct{}
- func RefreshAnthropicOAuthPure(env PoolEnv, refreshToken string, useJSON bool) (map[string]any, error)
- func RefreshBoundHome(ctx context.Context)
- func RefreshCatalog(force bool) bool
- func RefreshCatalogSoon()
- func RefreshCatalogs(ctx context.Context, secrets *config.Secrets) bool
- func RefreshInstalledSecretScope(ctx context.Context, h string) bool
- func RefreshReasoningCapsAsync(ctx context.Context, provider string)
- func RegisterFactory(mode APIMode, f Factory)
- func RegisterProvider(p Profile)
- func RegisterSecretSource(source SecretSource, replace, builtin bool, scope string) bool
- func RegisterStablePrefix(prefix string)
- func RegisterTransport(apiMode string, newTransport func() Transport)
- func RegisteredAPIModes() map[string]bool
- func RegistryGeneration() int64
- func RegistryInferenceBaseURL(id string) (string, bool)
- func RegistryInferenceBaseURLs() []string
- func RegistryInferenceRoutes(ctx context.Context) [][2]string
- func RegistryKeys(ctx context.Context) []string
- func RejectedReasoningFields(errorBody any, sentMessages any) map[string]bool
- func RejectedThinkingFingerprints(store RejectedThinkingStore, sessionID string) map[string]bool
- func RejoinCompressedHeadAndTail(compressedHead, tail []map[string]any) []map[string]any
- func RelayCompleteLogicalCall(ctx context.Context, apiRequestID string, o RelayLogicalCompletion) error
- func RelayExecute(ctx context.Context, request map[string]any, ...) (any, error)
- func RelayExecuteAsync(ctx context.Context, request map[string]any, ...) (any, error)
- func RelayStreamCurrent(ctx context.Context, request map[string]any, ...) (any, error)
- func ReloadSetupConfig(ctx context.Context, cfg config.Tree, save bool) error
- func ReloginCommandHint(h, provider string) string
- func RememberAccountUsage(ctx context.Context, provider string, snapshot *AccountUsageSnapshot, ...)
- func RememberReasoningFloor(provider, baseURL string, rejectedKwargs map[string]any, _ error) error
- func RememberStructuredOutputRejection(provider, baseURL string, rejectedKwargs map[string]any, err error) error
- func RememberTemperatureRejection(provider, baseURL string, rejectedKwargs map[string]any, _ error) error
- func RemoteModelSelectionGuard(ctx context.Context, before, after any) error
- func RemoveCacheFile(h, name string)
- func RemoveEnvSetting(ctx context.Context, h, key string) (bool, error)
- func RenameToolSearchBridgeForXAI(tools []map[string]any) ([]map[string]any, map[string]string)
- func RenderAccountUsageLines(snapshot *AccountUsageSnapshot, markdown bool) []string
- func RenderBar(fraction float64, width int) string
- func RenderCodexTOMLSection(servers map[string]*pyjson.Object, plugins []map[string]any, ...) (string, error)
- func RenderHistorySeed(messages []map[string]any) string
- func RenderPresets(entries []*PresetEntry) string
- func RenderToolBridgeSections(tools []any, toolChoice any, allowlist []string) ([]string, error)
- func RepairToolCallArguments(rawArgs, toolName string) string
- func RequiresAuthNotice(manifest map[string]any) string
- func ResetBedrockProbeFailureCache()
- func ResetCatalogCache()
- func ResetDelayFromMessage(message string) (time.Duration, bool)
- func ResetEntraCredentialCache()
- func ResetHint(err error, now time.Time) string
- func ResetLaunchEnvSnapshotForTests()
- func ResetSecretSourceCache(h string)
- func ResolveAWSAuthEnvVar(ctx context.Context) string
- func ResolveAffinityKey(ctx context.Context, sessionID string) string
- func ResolveAnthropicPromptCachePolicy(ctx context.Context, agent *CachePolicyAgent, dest CacheDestination) (bool, bool)
- func ResolveAnthropicToken(env PoolEnv, model string) string
- func ResolveAuthProvider(env PoolEnv, requested string) (string, error)
- func ResolveAuxTaskProvider(ctx context.Context, task string) string
- func ResolveBackend(requested string, gpuVendor *string, target string) (string, error)
- func ResolveBedrockRegion() string
- func ResolveBedrockRuntimeRegion(ctx context.Context) string
- func ResolveCacheHome(homePath string) string
- func ResolveCodexCredentialAndBase(ctx context.Context) (string, string, error)
- func ResolveCodexRuntimeCredentials(env PoolEnv, opts CodexResolveOptions) (map[string]any, error)
- func ResolveDirectStaleTimeout(ctx context.Context, agent ChatCompletionAgent, apiKwargs map[string]any) (float64, error)
- func ResolveDisplayContextLength(ctx context.Context, req DisplayContextRequest) (int, bool)
- func ResolveEffectiveModel(sessionOverrides, channelConfig, globalConfig any) string
- func ResolveEntryAPIKey(ctx context.Context, entry map[string]any) string
- func ResolveEnvCredentials(env PoolEnv, providerID, requestedProvider string) (apiKey, baseURL, defaultBase string, ok bool)
- func ResolveFallbackEntryAPIKey(ctx context.Context, h string, entry map[string]any) string
- func ResolveFastModeOverrides(model, providerName, baseURL, tier string) map[string]any
- func ResolveMoAPreset(raw any, name string) (map[string]any, error)
- func ResolveNativeCompactionCapability(model, baseURL, providerName string, isCodexBackend bool) bool
- func ResolvePersistBehavior(ctx context.Context, isGlobal, isSession, isOnce bool, explicitProvider string) bool
- func ResolvePricingProvider(provider, baseURL string) string
- func ResolvePromptCacheScope(a *CacheScopeAgent) string
- func ResolvePromptCacheScopeSafe(a *CacheScopeAgent) (scope string)
- func ResolveRequestedProvider(ctx context.Context, h, requested string) (string, error)
- func ResolveResponsesReasoning(ctx context.Context, model, providerName, baseURL string, ...) (string, bool)
- func ResolveRuntimePoolKey(provider, baseURL string, cfg map[string]any) string
- func ResolveTimeout(cfg config.Tree, key string, def time.Duration, hasDefault bool, envVar string) (time.Duration, bool)
- func ResolveXAIOAuthRuntimeCredentials(env PoolEnv, forceRefresh, refreshIfExpiring bool, refreshSkew time.Duration) (map[string]any, error)
- func ResponseStopDetails(resp *Response) any
- func ResponsesRouteIsCodexBackend(providerName, baseURL string) bool
- func RestoreAuthActiveProvider(store *Store, value any, present bool) error
- func RestoreModelCfg(ctx context.Context, h string, modelBefore any) error
- func RestorePrimaryRoute(ctx context.Context, h string, store *Store, modelBefore, activeBefore any, ...) error
- func RestoreSecretRegistration(name string, current, previous SecretSource, scope string) bool
- func RetryAfterFrom(value string) time.Duration
- func RetryAfterFromHeaders(h http.Header) (time.Duration, bool)
- func RootIcebathOAuthFile(env PoolEnv) string
- func RotateRuntimeMainAPIKey(ctx context.Context, old, new any)
- func RoughFit(totalBytes int64, budget HardwareBudget) string
- func RouteAnswer(ctx context.Context, hook, providerName string, scope any, ...) any
- func RouteKey(value any) string
- func RouteSupportedEfforts(provider, model, apiMode string) []string
- func RoutedCustomIdentity(baseURL, model string, cfg map[string]any, held string) string
- func RoutedModelRejectsVisionToolMessages(ctx context.Context, provider, model string) bool
- func RouterLaunchCtx(client *probeClient, serverURL, model string) (int, bool, error)
- func RoutesAtHosts(h string, hosts []string) bool
- func RoutingProcessHome() string
- func RowOwnedByEntry(row PooledCredential, entry map[string]any) bool
- func RunCodexAppServerTurn(agent CodexRuntimeAgent, userMessage string, originalUserMessage any, ...) (map[string]any, error)
- func RunCodexStream(ctx context.Context, agent ChatCompletionAgent, apiKwargs map[string]any, ...) (any, error)
- func RunCodexToolsMCPServer(argv []string) int
- func RunIcebathOAuthLoginPure(env PoolEnv, prompt func(label string) (string, bool)) map[string]any
- func RunOAuthSetupToken(env PoolEnv) (string, error)
- func RunSetupActionWithNavigation(ctx context.Context, label string, action func(ctx context.Context) error, ...) error
- func RunSetupSteps(steps []SetupStep) error
- func RunWithSetupNavigation(fn func() error, cancelledMessage string) error
- func RunWizardWithSetupNavigation(fn func() error, cancelledMessage string) error
- func RuntimeEntryOwner(ctx context.Context, provider, requestedProvider, baseURL string, ...) map[string]any
- func RuntimeHasCredentials(rt *Runtime) bool
- func RuntimeMainOf(ctx context.Context) map[string]any
- func RuntimesRoot() string
- func SDKStatusClass(status int) string
- func SameAuthStore(a, b string) bool
- func SameCredentialSurface(a, b BackendIdentity) bool
- func SameDeploymentIn(ctx context.Context, a, b BackendIdentity) bool
- func SameEndpoint(a, b BackendIdentity) bool
- func SanitizeBorrowedCredentialPayload(payload map[string]any, providerID string) map[string]any
- func SanitizeConsumerCodexRequest(agent any, request map[string]any) map[string]any
- func SanitizeHookPayload(value any) any
- func SanitizeLoadedCredentials()
- func SaveContextLength(ctx context.Context, model, baseURL string, length int, source string)
- func SaveEnvSetting(ctx context.Context, h, key, value string) error
- func SaveProviderContextLength(ctx context.Context, model, baseURL string, length int, providerName string)
- func SaveWindowOverride(modelID string, window int) error
- func ScopedFallbackChain(inherited []map[string]any, declared any, declaredSet bool, pinned bool, ...) []map[string]any
- func ScopedRuntimeMain(ctx context.Context, mainRuntime map[string]any) (context.Context, map[string]any)
- func ScrubANSI(text string) string
- func SecretFingerprint(material string) string
- func SecretHomeApplied(h string) bool
- func SecretScopeBound(ctx context.Context) bool
- func SecretSourceEnabled(cfg map[string]any) bool
- func SecretSourceFetchTimeout(cfg map[string]any) time.Duration
- func SecretSourceLabel(h, name string) string
- func SecretSourceNames() []string
- func SecretSourceOf(h, envVar string) string
- func SecretSourceOverrideExisting(spec SecretSourceSpec, cfg map[string]any) bool
- func SecretSourceProtectedEnvVars(spec SecretSourceSpec, cfg map[string]any) map[string]bool
- func SecretSourceRemediation(spec SecretSourceSpec, kind SecretErrorKind, cfg map[string]any) string
- func SecretSourceRestoreValues(h string) map[string]string
- func SecretSourceScopedRegistry() plugins.ScopedRegistry
- func SecretSourceTokenEnv(spec SecretSourceSpec, cfg map[string]any) string
- func SecretSourceValues(h string) map[string]string
- func SecretsCommand(ctx context.Context, h string, ns map[string]any, w io.Writer) (int, error)
- func SeedCatalogCacheFromCheckout(ctx context.Context, projectRoot string) bool
- func SelectProviderAndModel(ctx context.Context, ns map[string]any) error
- func SelectedConfigBackendName(h string) string
- func SelectionRouteChanged(modelCfg map[string]any, result ModelSwitchResult) bool
- func SendWithParameterRungs(ctx context.Context, ...) (any, error)
- func SendWithParameterRungsAsync(ctx context.Context, ...) (any, error)
- func ServeNoticesOnStderr()
- func ServerChildEnv(base map[string]string) map[string]string
- func ServesRoutedProfile(ctx context.Context) bool
- func ServiceTierWord(tier string) string
- func SessionAuxiliaryScope(ctx context.Context, auxiliary any) context.Context
- func SessionProviderIdentity(ctx context.Context, provider, requestedProvider, baseURL, model string, ...) string
- func SessionSourceFor(env *tools.Env, platform string) string
- func SetAccountingContext(ctx context.Context, db AuxUsageRecorder, sessionID string) context.Context
- func SetAnthropicLiveBlocks(m *state.Message, blocks []any)
- func SetAuxLifecycleHooks(has func(ctx context.Context, name string) bool, ...)
- func SetCodexQuotaProbe(fn func(env PoolEnv, token, baseURL string) (bool, bool)) func()
- func SetCodexRuntime(cfg map[string]any, newValue string) (string, error)
- func SetFallbackCheckCommand(...)
- func SetMultiplexActive(active bool)
- func SetPoolClock(fn func() time.Time) func()
- func SetRuntimeMain(ctx context.Context, provider, model string, opts RuntimeMainOptions) context.Context
- func SetdefaultDict(cfg map[string]any, key string) (map[string]any, error)
- func SetupConsole() *cliui.Console
- func SetupInfo(lines ...any)
- func SetupModelProvider(ctx context.Context, cfg config.Tree) error
- func SetupModuleInstalled(ctx context.Context, name string) (found bool)
- func SetupOutput() io.Writer
- func SetupPrintError(text string)
- func SetupPrintInfo(text string)
- func SetupPrintSuccess(text string)
- func SetupPrintWarning(text string)
- func SetupPrompt(question, def string, password bool) string
- func SetupSectionRule(title string)
- func SetupSystemExit(err error) (code int, message string, ok bool)
- func SetupToolsEnv(ctx context.Context) *tools.Env
- func ShapeWireCarriers(ctx context.Context, messages []map[string]any, model, baseURL string, ...) []map[string]any
- func ShouldBypassProxy(targets []string, noProxyValue *string) bool
- func ShouldClearContextPin(configuredModel, activeModel, configuredBaseURL, activeBaseURL, ... string) (clear bool)
- func ShouldSkipCandidateIn(ctx context.Context, candidate, failed BackendIdentity, scope FailureScope) bool
- func ShouldUseDirectAPICall(ctx context.Context, provider, platform string, mode APIMode) bool
- func ShouldUseOllamaNativeCatalog(ctx context.Context, provider, baseURL string, headers map[string]string) bool
- func ShutdownCachedClients(ctx context.Context)
- func ShutdownLocalRuntime() error
- func SignInFailureLines(err error, serviceHost, retryCommand string) []string
- func SkipDeepMerge(prefix, key string) bool
- func SnapshotAuthActiveProvider(store *Store) (any, bool, error)
- func SnapshotProviderRegistryForTests() func()
- func SourceChildEnv(environ *SourceEnvironment) map[string]string
- func SourceSuppliedNames() []string
- func SpentRotationSourcePath(env PoolEnv, source string) string
- func SpillOverrides(profile ModelProfile, spillBytes *int64) []string
- func SplitHistoryForPartialCompress(history []map[string]any, keepLast int) ([]map[string]any, []map[string]any)
- func SplitHostPort(value string) (string, int, bool)
- func SplitParts(path string) []string
- func SplitResponsesToolID(raw string) (string, string)
- func SpotifyAuthStatus(h string) (map[string]any, error)
- func SpotifyHTTPDo(ctx context.Context, method, rawURL string, body io.Reader, ...) (*pyhttpx.Response, error)
- func SpotifyLogin(ctx context.Context, h string, opts SpotifyLoginOptions, out io.Writer) error
- func SpotifyLogout(h string) (bool, error)
- func SpotifyResolveRuntimeCredentials(ctx context.Context, h string, forceRefresh, refreshIfExpiring bool) (map[string]any, error)
- func StampCreatedConfig(h string, cfg map[string]any)
- func StateAuxiliaryUsage(u AuxiliaryUsage) state.AuxiliaryUsage
- func StaticCatalog(ctx context.Context, provider string) []string
- func StaticCatalogProviders(ctx context.Context) []string
- func StreamCodexPassthrough(ctx context.Context, agent ChatCompletionAgent, apiKwargs map[string]any, ...) (any, error)
- func StreamDiagCaptureResponse(diag *StreamDiag, resp *http.Response)
- func StreamWriterIsCurrent(agent any, token int) bool
- func StringifyProviderMap(providers any) map[string]any
- func StripAnthropicCacheControl(messages []map[string]any) []map[string]any
- func StripAnthropicToolCacheControl(tools []map[string]any) []map[string]any
- func StripCodexContextVariantSuffix(model string) string
- func StripOpaqueReplayItems(items any) any
- func StripOrphanThinkCloseTags(text string) string
- func StripProviderPrefix(model string) string
- func StripRejectedThinking(message map[string]any, rejected map[string]bool) int
- func StripThinkBlocks(content string) string
- func StripUnverifiedReasoningItems(msgs []*state.Message, issuerKind, issuerModel string) int
- func SuggestPrefixedModelID(provider, model string) string
- func SummarizeAPIError(err error, provider string) string
- func SummarizeCompressPreview(history []map[string]any, partial bool, keepLast int, focusTopic *string, ...) map[string]any
- func SummarizeTimeoutError(err error, provider string) (string, bool)
- func SummarizeUserMessageForLog(content any, sep string) string
- func SwapBedrockProbe(fn func(context.Context, string, string) int) (prev func(context.Context, string, string) int)
- func SwapDetectServerForTests(fn func([]int) (*DetectedServer, error)) func()
- func SwapDirectWatchdogArmForTests(arm func(time.Duration, func()) *time.Timer) func()
- func SwapLeftCoreTableForTests(rows []LeftCoreFeature) func()
- func SwapNoticesOnStderrForTests(on bool) bool
- func SwapResolveBedrockRegion(fn func() string) (prev func() string)
- func SwapSetupChecklist(fn func(title string, items []string, pre map[int]bool) (map[int]bool, error)) func()
- func SwapSetupRadiolist(fn func(question string, choices []string, def int, description string) int) func()
- func SyncRegisteredProviders(profiles []Profile)
- func TakeTurnAuthorFromEnv(environ map[string]string) *pyjson.Object
- func ThinkCloseTags() [][]rune
- func ThinkOpenTags() [][]rune
- func TimeoutPhase(err error) string
- func TimeoutsSection(cfg config.Tree) map[string]any
- func ToOpenAIBaseURL(baseURL string) string
- func TokenPairsByID(entries []map[string]any) map[string]TokenPair
- func ToolModelContextLength(ctx context.Context, q tools.ContextLengthQuery) int
- func ToolRuntimeCredentials(ctx context.Context, env *tools.Env, requested, targetModel string) (string, string, error)
- func ToolSpecsFromOpenAITools(tools []any, allowlist []string) []*pyjson.Object
- func TrackPoolConns(t *http.Transport, conns ...net.Conn) *http.Transport
- func TurnAuthorEnv(author *pyjson.Object) (map[string]string, error)
- func TurnAuthorFromEnv(environ map[string]string) *pyjson.Object
- func URLPath(rawURL string) string
- func UbLogitsBytes(nVocab int64, mtpCapable, mtpPrefill bool) int64
- func UltrafastOffered(model, providerName, baseURL, accessToken string) (bool, error)
- func UnavailableReason(backend, target string) (string, error)
- func UnlistedProviderNames(ctx context.Context) map[string]bool
- func UnquoteDotenvValue(raw string) string
- func UnregisterProvider(name string)
- func UnsetReasoningDefault(ctx context.Context, agent ChatCompletionAgent) (out map[string]any)
- func UsableBesidePromptCache(live HardwareBudget, residents int) (int64, error)
- func UsageCommand(ctx context.Context, env PoolEnv, ns map[string]any, w io.Writer) (int, error)
- func UsageSnapshotDocument(snapshot *AccountUsageSnapshot) map[string]any
- func UserAgent(product string) string
- func UsesSilentCatalogDefault(provider string) bool
- func ValidateBaseURL(baseURL string) error
- func ValidateCatalogManifest(data any) bool
- func ValidateOAuthPKCEConfig(provider string, cfg OAuthPKCEConfig) error
- func ValidateProxyEnvURLs() error
- func ValidatedOpenRouterProviderSort(raw any) (string, bool)
- func VertexGetConfig(ctx context.Context) (string, string)
- func WaitNoticeText(model string, silenceSecs float64, phase string, watchdog *WatchdogDeadline) string
- func WaitReasoningCapsWarms()
- func WarmOpenRouterReasoningCapsAsync(ctx context.Context)
- func WindowOverridesPath() string
- func WithAffinityScope(ctx context.Context, scope string) context.Context
- func WithAuxiliaryEventLoop(ctx context.Context, loop interface{ ... }) context.Context
- func WithCodexWatchdogState(ctx context.Context, s *CodexWatchdogState) context.Context
- func WithConversationContext(ctx context.Context, conversationID string) context.Context
- func WithDeferredTokenMint(ctx context.Context) context.Context
- func WithFrozenRuntimeConfig(ctx context.Context, cfg map[string]any) context.Context
- func WithLaunchBody(ctx context.Context) context.Context
- func WithLaunchBodyScope(ctx context.Context, resolver func() map[string]string) context.Context
- func WithLaunchProfileRuntimeScope(ctx context.Context, launchHome string) context.Context
- func WithLaunchProfileScopeIfMultiplexed(ctx context.Context) context.Context
- func WithLeftCoreInstallsHeld(ctx context.Context) context.Context
- func WithMultiplexContext(ctx context.Context, active bool) context.Context
- func WithPromptProgressKwargs(kwargs map[string]any) map[string]any
- func WithReasoningFloor(kwargs map[string]any) map[string]any
- func WithSecretScope(ctx context.Context, secrets map[string]string, profileHome string) context.Context
- func WithSetupConsole(c *cliui.Console) func()
- func WithSetupOutput(w io.Writer) func()
- func WithStreamEmitters(emitters StreamEmitters, run func() (any, error)) (any, error)
- func WithoutGenerationModels(models []string) []string
- func WithoutUnsupportedResponseFormat(ctx context.Context, extraBody *pyjson.Object, ...) (*pyjson.Object, error)
- func WriteClaudeCodeCredentials(env PoolEnv, accessToken, refreshToken string, expiresAtMS int64, scopes []any, ...) error
- func WriteFallbackChain(cfg map[string]any, chain []map[string]any)
- func WriteIcebathOAuthCredentials(env PoolEnv, accessToken, refreshToken string, expiresAtMS int64, ...) error
- func WritePresets(entries []*PresetEntry, presetPath string) error
- func XAICredentialPoolSource() tools.CredentialPoolSource
- func XAIOAuthSectionLogin(env PoolEnv, out io.Writer) bool
- func ZAICodingOverloadRetryCeiling() int
- func ZAIPolicyNote(policy string) string
- type APIError
- type APIKeySecretResolver
- type APIMode
- func AzureFoundryModelMode(model string) APIMode
- func DetectAPIModeForURL(baseURL string) APIMode
- func DetermineModeCtx(ctx context.Context, providerName, baseURL, model string) APIMode
- func HostMandatedMode(baseURL string) APIMode
- func OpenCodeModelMode(providerID, modelID string) APIMode
- func OpencodeTransport(ctx context.Context, provider, model, baseURL string) (APIMode, string)
- type AWSCredentialError
- type AWSEventStreamException
- type AWSEventStreamFrameError
- type AWSReadTimeoutError
- type AWSServiceError
- type AccountUsageFetchOptions
- type AccountUsageRefreshRequest
- type AccountUsageSnapshot
- func CachedAccountUsage(ctx context.Context, provider, identityID, baseURL string) *AccountUsageSnapshot
- func FetchAccountUsage(ctx context.Context, provider string, opts AccountUsageFetchOptions) *AccountUsageSnapshot
- func NewAccountUsageSnapshot(provider, source string, windows []AccountUsageWindow, details []string) *AccountUsageSnapshot
- type AccountUsageWindow
- type ActiveLoginSource
- type AgentImportOptions
- type AgentNotice
- type AliasMatch
- type AmbiguousAliasError
- type AnthropicAuxiliaryClient
- type AnthropicConnectionError
- type AnthropicOAuthError
- type AnthropicStreamAccumulator
- type AppliedVar
- type ApplyReport
- type AssetFile
- type AsyncAnthropicAuxiliaryClient
- type AsyncBedrockAuxiliaryClient
- type AsyncCodexAuxiliaryClient
- type AuthData
- type AuthEpisode
- type AuthError
- type AuthExitError
- type AuthKind
- type AuthRecoveryAgent
- type AuthRecoveryRequest
- type AuthenticatedProvidersOptions
- type AuthoritativeAuxiliaryTask
- type AuxAdapter
- func (AuxAdapter) Complete(ctx context.Context, messages []*state.Message, opts tools.AuxOptions) (string, error)
- func (AuxAdapter) CompleteChat(ctx context.Context, messages []map[string]any, toolDefs []map[string]any, ...) (map[string]any, error)
- func (AuxAdapter) ResolvesVision(ctx context.Context, provider string) (bool, error)
- type AuxCallHookArgs
- type AuxCallHooks
- type AuxCancelCheck
- type AuxCancelEvent
- type AuxCancelFunc
- type AuxChatStream
- type AuxClient
- func GetTextAuxiliaryClient(ctx context.Context, task string, mainRuntime map[string]any) (AuxClient, string, error)
- func NewOpenAIClient(apiKey any, baseURL string, opts OpenAIClientOptions) AuxClient
- func ResolveProviderClient(ctx context.Context, provider, model string, opts ProviderClientOptions) (AuxClient, string, error)
- func ResolveVisionProviderClient(ctx context.Context, provider, model, baseURL string, apiKey any, ...) (string, AuxClient, string, error)
- func TryConfiguredFallbackForUnavailableClient(ctx context.Context, task, failedProvider string) (AuxClient, string, string, error)
- type AuxHookLocal
- type AuxNormalizedReply
- type AuxPickerEntry
- type AuxReplyFault
- type AuxRuntimeError
- type AuxSDKError
- type AuxStreamDeadlineFunc
- type AuxTimeoutError
- type AuxTimeoutKind
- type AuxTransportError
- func (e *AuxTransportError) Error() string
- func (e *AuxTransportError) FailedRequest() *FailedStreamRequest
- func (e *AuxTransportError) PyExceptionMRO() []string
- func (e *AuxTransportError) PyModule() string
- func (e *AuxTransportError) PyTypeName() string
- func (e *AuxTransportError) Timeout() bool
- func (e *AuxTransportError) Unwrap() error
- type AuxUsageRecorder
- type AuxiliaryClientUnavailable
- type AuxiliaryExplicitCancellation
- type AuxiliaryUsage
- type AvailabilityProvider
- type AvailableProvider
- type AzureDetection
- type AzureDetector
- type BackendIdentity
- type BackoffOptions
- type BearerValueError
- type BedrockAuxiliaryClient
- type BedrockBinding
- type BedrockModel
- type BedrockOpenAINoCredentialsError
- type BedrockScopedCredentialError
- type BillingBlock
- type BillingRoute
- type BinaryResolutionError
- type BitwardenFetchOptions
- type BitwardenSource
- type BoundedResult
- type CLIResult
- type CacheDestination
- type CachePolicyAgent
- type CacheScopeAgent
- type CacheScopeSessionStore
- func (c CacheScopeSessionStore) DeclaredScopeIdentity(sessionID string) (bool, string, error)
- func (c CacheScopeSessionStore) GetCompressionLineage(sessionID string) ([]string, error)
- func (c CacheScopeSessionStore) GetSession(ctx context.Context, sessionID string) (*pyjson.Object, error)
- func (c CacheScopeSessionStore) IsExplicitForkChild(sessionID string) (bool, error)
- func (c CacheScopeSessionStore) LatestConversationBoundary(sessionKey, source string) (int64, bool, error)
- type CacheScopeStore
- type CachedFetch
- type CachedFetchOptions
- type CachedModelsOptions
- type CanonicalProviderEntry
- type CanonicalUsage
- type CatalogConfig
- type CatalogEntry
- func (e CatalogEntry) CompanionBytes() int64
- func (e CatalogEntry) DownloadBytes(v QuantVariant) int64
- func (e CatalogEntry) DownloadFiles(v QuantVariant) []AssetFile
- func (e CatalogEntry) InstallFiles(v QuantVariant) []AssetFile
- func (e CatalogEntry) LaunchPlan(v QuantVariant, budget HardwareBudget) LaunchPlan
- func (e CatalogEntry) MTPCapable() bool
- func (e CatalogEntry) Profile(v QuantVariant) ModelProfile
- type CatalogModel
- type CatalogProviderBase
- type CatalogProviderDefaults
- type CatalogRows
- func CachedFetchAPIModels(ctx context.Context, opts CachedFetchOptions) (CatalogRows, bool)
- func FetchPickerLiveModels(ctx context.Context, apiKey any, apiURL, nativeProvider string, ...) (CatalogRows, bool)
- func MergeProfileCatalog(ctx context.Context, normalized string, profile Profile, live []string) (CatalogRows, bool)
- func ProbeProfileCatalog(ctx context.Context, normalized string, profile Profile, ...) (CatalogRows, bool)
- func ProviderModelIDs(ctx context.Context, provider string, forceRefresh bool) CatalogRows
- type CatalogSetting
- type ChatCompletionAgent
- type ChatStreamWatchdog
- type Classified
- type ClassifierHook
- type ClassifyInput
- type Client
- type ClonedGrantStrip
- type CodexAppServerClient
- func (c *CodexAppServerClient) Close(timeout time.Duration)
- func (c *CodexAppServerClient) Initialize(clientName, clientTitle, clientVersion string, capabilities any, ...) (any, error)
- func (c *CodexAppServerClient) IsAlive() bool
- func (c *CodexAppServerClient) Notify(method string, params any) error
- func (c *CodexAppServerClient) PID() int
- func (c *CodexAppServerClient) Request(method string, params any, timeout time.Duration) (any, error)
- func (c *CodexAppServerClient) Respond(requestID any, result any) error
- func (c *CodexAppServerClient) RespondError(requestID any, code int, message string, data any) error
- func (c *CodexAppServerClient) StderrTail(n int) []string
- func (c *CodexAppServerClient) TakeNotification(timeout time.Duration) any
- func (c *CodexAppServerClient) TakeServerRequest(timeout time.Duration) any
- type CodexAppServerError
- type CodexAppServerOptions
- type CodexAppServerSession
- func (s *CodexAppServerSession) Close()
- func (s *CodexAppServerSession) CompactThread(turnTimeout, notificationPollTimeout float64) (*CodexTurnResult, error)
- func (s *CodexAppServerSession) EnsureStarted() (string, error)
- func (s *CodexAppServerSession) RequestInterrupt()
- func (s *CodexAppServerSession) RequestSteer(text string) (bool, error)
- func (s *CodexAppServerSession) RunTurn(userInput any, opts CodexTurnOptions) (*CodexTurnResult, error)
- func (s *CodexAppServerSession) ThreadID() string
- type CodexAppServerSessionOptions
- type CodexAppServerTransportError
- type CodexApprovalCallback
- type CodexAuxiliaryClient
- type CodexContextCompressor
- type CodexEventProjector
- type CodexLoginArgs
- type CodexMigrateOptions
- type CodexMigrationReport
- type CodexProjectionResult
- type CodexRPCClient
- type CodexReplayControl
- type CodexRequestTimeoutError
- type CodexResetRedeemResult
- type CodexResolveOptions
- type CodexRuntimeAgent
- type CodexRuntimeStatus
- type CodexRuntimeTurnHooks
- type CodexServerRequestRouting
- type CodexSessionDB
- type CodexStreamErrorEvent
- type CodexThreadResumeError
- type CodexToolProgressExtra
- type CodexToolsImportError
- type CodexToolsServer
- type CodexTurnOptions
- type CodexTurnResult
- type CodexWatchdogClock
- type CodexWatchdogState
- type CommandSource
- type CommandTokenError
- type CommandTokenSource
- type CompressionCheckpointUnavailable
- type CompressionFastLane
- type ConfigBackendUnavailableError
- type ConfigBackendView
- type ConfigPath
- type ConfigWriteRefusedError
- type ConfiguredMatch
- type ContextLengthRequest
- type CopilotACPChatClient
- type CostResult
- type Credential
- type CredentialNotSavedError
- type CredentialPersistError
- type CredentialSource
- type CuratedFallbackModels
- type DataTrainingWarning
- type DeadlineExpiredError
- type DetectedServer
- type DeviceCodeExpiredError
- type DeviceFlowCancelledError
- type DirectAlias
- type DirectAliasTable
- type DisplayContextRequest
- type DistributionManifest
- type DotenvLoadOptions
- type EmptyStreamError
- type Engine
- type EnsureEngineOptions
- type EntraAccessToken
- type EntraBearerTransport
- type EntraIdentityConfig
- type EnvCredentialPurge
- type ErrorKind
- type EventKind
- type ExpensiveModelWarning
- type ExternalProcessSpec
- type Factory
- type FailedStreamRequest
- type FailoverReason
- type FailureScope
- type FallbackAPIModeAgent
- type FallbackCheckRedactor
- type FallbackEntryCheck
- type FastWindow
- func (f *FastWindow) BeginTurn(history []*state.Message)
- func (f *FastWindow) EffectiveRequestOverrides(route Route, anthropicBaseURL string) map[string]any
- func (f *FastWindow) FastModeUnavailable(model string) bool
- func (f *FastWindow) MarkFastModeUnavailable(model string) bool
- func (f *FastWindow) Open() bool
- type FetchModelsOptions
- type FileLockTimeoutError
- type FoundImportSource
- type GGMLDevice
- type GGUFError
- type GGUFHeader
- func (h *GGUFHeader) Architecture() string
- func (h *GGUFHeader) ExpertCount() (int64, error)
- func (h *GGUFHeader) FullAttentionInterval() (int64, error)
- func (h *GGUFHeader) HeadCountsKV() ([]int64, error)
- func (h *GGUFHeader) HeadDimK() (int64, error)
- func (h *GGUFHeader) HeadDimV() (int64, error)
- func (h *GGUFHeader) KeyLengthSWA() (int64, error)
- func (h *GGUFHeader) LazyBytes() int64
- func (h *GGUFHeader) NCtxTrain() (int64, error)
- func (h *GGUFHeader) NEmbd() (int64, error)
- func (h *GGUFHeader) NHead() (int64, error)
- func (h *GGUFHeader) NLayer() (int64, error)
- func (h *GGUFHeader) NVocab() (int64, error)
- func (h *GGUFHeader) RecurrentStateBytes() (int64, error)
- func (h *GGUFHeader) SamplingDefaults() (map[string]string, error)
- func (h *GGUFHeader) SlidingWindow() (int64, error)
- func (h *GGUFHeader) SlidingWindowPattern() ([]int64, error)
- func (h *GGUFHeader) SlidingWindowPatternPeriod() int64
- func (h *GGUFHeader) ValueLengthSWA() (int64, error)
- type GeminiAPIError
- type GoogleCredentials
- func GoogleAuthorizedUserCredentials(info map[string]any, scopes []string) (*GoogleCredentials, error)
- func GoogleDefaultCredentials(ctx context.Context, scopes []string) (*GoogleCredentials, string, error)
- func GoogleServiceAccountCredentials(info map[string]any, scopes []string) (*GoogleCredentials, error)
- func (g *GoogleCredentials) Current() (string, time.Time)
- func (g *GoogleCredentials) QuotaProject() string
- func (g *GoogleCredentials) Refresh(ctx context.Context) error
- func (g *GoogleCredentials) Seed(token string, expiry time.Time)
- func (g *GoogleCredentials) Token(ctx context.Context) (string, error)
- type GrowthDecision
- type HFFileGroup
- type HFModelHit
- type HTTPException
- type HTTPStatusError
- type HardwareBudget
- type HardwareProbeError
- type HeaderCapture
- type HeaderCarrier
- type HeaderEntry
- type HookJSONCaps
- type HostedAnswer
- type HostedModelResult
- type HostedPrompt
- type IcebathOverlay
- type ImportSource
- type InterruptedError
- type IronProxy
- func (p IronProxy) BuildProxyConfig(opts IronProxyConfigOptions) map[string]any
- func (p IronProxy) EnsureCACert(force bool) (string, string, error)
- func (p IronProxy) EnsureManagementToken(force bool) (string, error)
- func (p IronProxy) FindIronProxy(installIfMissing bool) string
- func (p IronProxy) GetStatus() IronProxyStatus
- func (p IronProxy) InstallIronProxy() (string, error)
- func (p IronProxy) IronProxyVersion(binary string) string
- func (p IronProxy) LoadMappings() ([]TokenMapping, error)
- func (p IronProxy) ReloadProxy() error
- func (p IronProxy) StartProxy(opts IronProxyStartOptions) (IronProxyStatus, error)
- func (p IronProxy) StopProxy() (bool, error)
- func (p IronProxy) WriteMappings(mappings []TokenMapping) (string, error)
- func (p IronProxy) WriteProxyConfig(cfg map[string]any) (string, error)
- type IronProxyConfigOptions
- type IronProxyStartOptions
- type IronProxyStatus
- type LMStudioLoadResult
- type LaunchPlan
- type LayerKind
- type LazyHeaders
- func (h *LazyHeaders) Contains(key string) bool
- func (h *LazyHeaders) Copy() map[string]string
- func (h *LazyHeaders) Delete(key string) bool
- func (h *LazyHeaders) Equal(other any) bool
- func (h *LazyHeaders) Get(key string) (string, bool)
- func (h *LazyHeaders) GetDefault(key, def string) string
- func (h *LazyHeaders) IOr(other map[string]string) *LazyHeaders
- func (h *LazyHeaders) Items() [][2]string
- func (h *LazyHeaders) Keys() []string
- func (h *LazyHeaders) Len() int
- func (h *LazyHeaders) Or(other map[string]string) map[string]string
- func (h *LazyHeaders) Pop(key string) (string, bool)
- func (h *LazyHeaders) PopDefault(key, def string) string
- func (h *LazyHeaders) PopItem() (string, string, bool)
- func (h *LazyHeaders) ROr(other map[string]string) map[string]string
- func (h *LazyHeaders) Reversed() []string
- func (h *LazyHeaders) Set(key, value string)
- func (h *LazyHeaders) SetDefault(key, def string) string
- func (h *LazyHeaders) String() string
- func (h *LazyHeaders) Update(pairs ...[2]string)
- func (h *LazyHeaders) Values() []string
- type LeftCoreFeature
- type LimitState
- type LlamaServerSupervisor
- func (s *LlamaServerSupervisor) BaseURL() string
- func (s *LlamaServerSupervisor) EnsureModelReady(modelID string, timeout time.Duration) (bool, error)
- func (s *LlamaServerSupervisor) IsIdle(modelID string) bool
- func (s *LlamaServerSupervisor) LoadModel(modelID string, timeout time.Duration) error
- func (s *LlamaServerSupervisor) Models(timeout time.Duration) (RouterModels, error)
- func (s *LlamaServerSupervisor) PrimaryModel() string
- func (s *LlamaServerSupervisor) ReloadPresets() error
- func (s *LlamaServerSupervisor) SetPrimaryModel(modelID string)
- func (s *LlamaServerSupervisor) Start(ctx context.Context, timeout time.Duration) error
- func (s *LlamaServerSupervisor) State() map[string]any
- func (s *LlamaServerSupervisor) Stop() error
- func (s *LlamaServerSupervisor) SweepIdle(now *float64) []string
- func (s *LlamaServerSupervisor) TouchGenerate(modelID string, timeout time.Duration) bool
- func (s *LlamaServerSupervisor) UnloadModel(modelID string) error
- type LlamacppEndpoint
- type LoadProgress
- type LocalRuntimeUnavailableError
- type LocalValidationError
- type LockTimeoutError
- type MCPToolParam
- type MCPToolServer
- type ManagedLlmStream
- type ManagedLlmStreamOptions
- type MemoPins
- type MinimaxLoginArgs
- type MoAArgs
- type MoAExitError
- type MoAPresetNotFoundError
- type ModelAssignmentRejected
- type ModelCapabilities
- type ModelCredentialSource
- type ModelDumper
- type ModelFlagParseResult
- type ModelFlowRun
- type ModelIDNormalizer
- type ModelIdentity
- type ModelProfile
- func AsLoaded(profile ModelProfile, budget HardwareBudget) ModelProfile
- func NewModelProfile(name string, weightsBytes, embdTableBytes int64, nCtxTrain int, ...) ModelProfile
- func PostureProfile(profile ModelProfile, mtpCapable, mtpPrefill bool) ModelProfile
- func ProfileFromGGUF(h *GGUFHeader) (ModelProfile, error)
- type ModelSelectionPrompt
- type ModelSwitchRequest
- type ModelSwitchResult
- type ModelVerdict
- type ModelsDevEntry
- type ModelsDevFetchDeadlineError
- type ModelsDevProvider
- type ModelsPayloadOptions
- type ModelsProbe
- type NamedDirectAlias
- type NamedProvider
- type NativeCompactionGate
- type NativePreflightEstimator
- type NonStreamWatchdogs
- type NvidiaGPUQuery
- type OAuthClient
- type OAuthHealSummary
- type OAuthLoginExitError
- type OAuthPKCEConfig
- type OAuthProviderFlow
- type OAuthResolveOptions
- type OllamaCloudFetch
- type OnePasswordApplyOptions
- type OnePasswordFetchOptions
- type OnePasswordSource
- type OpenAIClientOptions
- type Opener
- type OpenerFactory
- type Origin
- type PerModelAPIModeHook
- type PhysicsRefusal
- type PickerConfigContext
- type PickerProvidersOptions
- type PickerRadiolistOptions
- type PickerRow
- type PickerSegment
- type PluginAuthError
- type PluginManagerHooks
- type PluginOAuthManifestError
- type PluginOAuthPermissionError
- type PluginOAuthResolver
- type PluginOrigin
- type Pool
- func EntryScopedPool(pool *Pool, poolKey string, entry map[string]any) *Pool
- func LoadPool(env PoolEnv, provider string) *Pool
- func LoadRoutePool(env PoolEnv, provider, baseURL, requestedProvider string) *Pool
- func LoadRoutePoolWith(env PoolEnv, load func(PoolEnv, string) *Pool, ...) *Pool
- func LoadRuntimePool(env PoolEnv, provider, baseURL, requestedProvider string, ...) *Pool
- func LoadRuntimePoolWith(env PoolEnv, load func(PoolEnv, string) *Pool, ...) *Pool
- func NewPool(env PoolEnv, provider string, entries []PooledCredential) *Pool
- func PoolForAuxProvider(ctx context.Context, provider, poolKey string, cfg map[string]any, ...) *Pool
- func (p *Pool) AcquireLease(credentialID string) (string, bool)
- func (p *Pool) ActiveLeases() map[string]int
- func (p *Pool) AddEntry(entry PooledCredential) (PooledCredential, error)
- func (p *Pool) Credential(provider string) (Credential, bool)
- func (p *Pool) CredentialForModel(provider, model string) (Credential, bool)
- func (p *Pool) Current() (PooledCredential, bool)
- func (p *Pool) CurrentID() string
- func (p *Pool) Entries() []PooledCredential
- func (p *Pool) EntryCount() int
- func (p *Pool) EntryIDForAPIKey(apiKeyHint string) string
- func (p *Pool) Env() PoolEnv
- func (p *Pool) HasAvailable(model string) bool
- func (p *Pool) HasCredentials() bool
- func (p *Pool) LiftReopenedCooldowns(model string) bool
- func (p *Pool) LimitState(models []string) *LimitState
- func (p *Pool) MarkExhaustedAndRotate(req RotationRequest) (PooledCredential, bool)
- func (p *Pool) MoveEntry(credentialID string, priority int) (PooledCredential, bool)
- func (p *Pool) NextAvailableAt(model string) (time.Time, bool)
- func (p *Pool) Peek() (PooledCredential, bool)
- func (p *Pool) Provider() string
- func (p *Pool) Reclaim(credentialID, model string) (PooledCredential, bool)
- func (p *Pool) ReleaseLease(credentialID string)
- func (p *Pool) RemoveIndex(index int) (PooledCredential, bool)
- func (p *Pool) ResetStatus(credentialID string) (PooledCredential, bool)
- func (p *Pool) ResetStatuses() int
- func (p *Pool) ResolveTarget(target string) (int, PooledCredential, string)
- func (p *Pool) Select(model string) (PooledCredential, bool)
- func (p *Pool) Strategy() string
- func (p *Pool) TokenBenchedForModel(provider, token, model string) bool
- func (p *Pool) TokenIsBlocked(token, model string) bool
- func (p *Pool) TryRefreshCurrent() (PooledCredential, bool)
- func (p *Pool) TryRefreshMatching(apiKeyHint, credentialID string) (PooledCredential, bool)
- type PoolCredentials
- func (c *PoolCredentials) Credential(provider string) (Credential, bool)
- func (c *PoolCredentials) CredentialForEntry(poolKey string, entry map[string]any) (Credential, bool)
- func (c *PoolCredentials) CredentialForModel(provider, model string) (Credential, bool)
- func (c *PoolCredentials) Pool(poolKey string) *Pool
- func (c *PoolCredentials) Reload()
- func (c *PoolCredentials) TokenBenchedForModel(provider, token, model string) bool
- type PoolEnv
- type PoolPresenceSource
- type PooledCredential
- func ApplyPluginRefreshResult(entry PooledCredential, result map[string]any) PooledCredential
- func PooledCredentialFromMap(provider string, payload map[string]any) PooledCredential
- func RecoverFailedPluginRefresh(p *Pool, entry PooledCredential, cause error, held bool) (PooledCredential, bool, bool)
- func (e PooledCredential) ClearStatus() PooledCredential
- func (e PooledCredential) Clone() PooledCredential
- func (e PooledCredential) ExtraString(key string) string
- func (e PooledCredential) FailureReason() string
- func (e PooledCredential) MarkOK() PooledCredential
- func (e PooledCredential) RuntimeAPIKey() string
- func (e PooledCredential) RuntimeBaseURL() string
- func (e PooledCredential) ToMap() map[string]any
- func (e PooledCredential) WithExtra(key string, value any) PooledCredential
- type PreparedMainAssignment
- type PresetEntry
- func GeneratePresets(modelsDir string, budget HardwareBudget, presetPath string, ...) ([]*PresetEntry, error)
- func PlanPresets(modelsDir string, budget HardwareBudget, mtpCapable map[string]bool, ...) ([]*PresetEntry, error)
- func PresetForModel(gguf string, budget HardwareBudget, mtpCapable map[string]bool, ...) (*PresetEntry, error)
- type PricingEntry
- type PricingFetchOptions
- type PricingTable
- type ProbeResult
- type Profile
- func BundledProfiles() []Profile
- func CanonicalRegistryRows(ctx context.Context) []*Profile
- func GetProviderProfile(ctx context.Context, name string) (Profile, bool)
- func ListProviders(ctx context.Context) []Profile
- func ProfileFor(name string) (Profile, bool)
- func ProfileForHost(ctx context.Context, rawURL string, metadata bool) (Profile, bool)
- func Profiles() []Profile
- func RefreshRouteProfiles(ctx context.Context, providerName, baseURL string) []*Profile
- func RegisteredProfileForHost(ctx context.Context, rawURL string, metadata bool) *Profile
- func RegistryRow(ctx context.Context, key string) *Profile
- func (p Profile) APIModeForModel(model string, apiKey *string) APIMode
- func (p Profile) BuildAPIKwargsExtras(reasoning *Reasoning, context map[string]any) (*pyjson.Object, map[string]any)
- func (p Profile) BuildClientKwargsExtras(context map[string]any) map[string]any
- func (p Profile) BuildExtraBody(sessionID string, context map[string]any) *pyjson.Object
- func (p Profile) ClientHeaders(baseURL, apiKey string, hasImages bool) map[string]string
- func (p Profile) CreateClient(ctx context.Context, clientKwargs map[string]any) (Client, error)
- func (p Profile) CredentialRefreshNotice(reason string) string
- func (p Profile) DefaultHeaders() map[string]string
- func (p Profile) DefaultReasoningConfig(model string) *Reasoning
- func (p Profile) DefaultVisionModel(ctx context.Context) string
- func (p Profile) DiscoverModels(ctx context.Context, kwargs map[string]any) ([]map[string]any, error)
- func (p Profile) ExternalAuthEvidence(ctx context.Context) (bool, string, bool)
- func (p Profile) FetchAccountUsage(ctx context.Context, baseURL, apiKey string) (*AccountUsageSnapshot, error)
- func (p Profile) FetchModels(ctx context.Context, apiKey, baseURL string, timeout time.Duration) ([]string, bool)
- func (p Profile) GetHostname() string
- func (p Profile) GetMaxTokens(model string) int
- func (p Profile) GetModelContextLength(model string) int
- func (p Profile) GetUsageCost(model string, usage CanonicalUsage) (CostResult, bool)
- func (p Profile) InvalidateCatalogCache()
- func (p Profile) KeyEnvNames() []string
- func (p Profile) Label() string
- func (p Profile) Listed(ctx context.Context) (bool, error)
- func (p Profile) LiveContextLength(ctx context.Context, model, apiKey, baseURL string) int
- func (p Profile) MaxTokensParam(baseURL, model string) string
- func (p Profile) MissingCredentialsHint() any
- func (p Profile) ModelAliasMap() map[string]string
- func (p Profile) NormalizeModelID(ctx context.Context, model, apiKey string) string
- func (p Profile) PrepareMessages(messages []map[string]any) []map[string]any
- func (p Profile) PreparePoolEntry(ctx context.Context, entry *PooledCredential, apiKey string) string
- func (p Profile) ProbeModels(ctx context.Context, baseURL, apiKey string, timeout time.Duration) *ModelsProbe
- func (p Profile) ReasoningPayload(model string, r Reasoning, baseURL string) map[string]any
- func (p Profile) RefreshRuntimeCredentials(ctx context.Context, reason string) (string, string, bool, error)
- func (p Profile) RemoveCredentialSource(source string) ([]string, []string, bool)
- func (p Profile) ReplayMessageCarriers(values map[string]any, model, baseURL string) map[string]any
- func (p Profile) ReplaysFunctionThoughtSignature(model, baseURL string) bool
- func (p Profile) RequestHeaders(baseURL, model string, userInitiated bool) map[string]string
- func (p Profile) RequestRejectionHint(statusCode int, baseURL string) []string
- func (p Profile) ResolveAPIKeySecret(ctx context.Context) (string, string, bool)
- func (p Profile) ResolveAuxModel(ctx context.Context, vision bool) string
- func (p Profile) ResponsesIssuerKind() string
- func (p Profile) ResponsesNativeCompaction() bool
- func (p Profile) ResponsesProfileReasoning() bool
- func (p Profile) ResponsesPromptCacheKey() bool
- func (p Profile) ResponsesReplayItemIDs() bool
- func (p Profile) ResponsesTrustsCompletedStatus() bool
- func (p Profile) RuntimeBaseURL(ctx context.Context, apiKey, def, envURL string) string
- func (p Profile) SeedPoolCredentials(ctx context.Context, suppressedSources map[string]bool, ...) []map[string]any
- func (p Profile) SetupStatus(ctx context.Context, kwargs map[string]any) (map[string]any, error)
- func (p Profile) SupportedReasoningEfforts(ctx context.Context, model string) ([]string, bool, error)
- func (p Profile) TemperatureOverride() (value *float64, omit bool)
- type ProfileContextLengthHook
- type ProfileLayer
- type ProfileLiveContextLengthHook
- type PromptCachePlanOptions
- type PromptReadingClock
- type ProviderBase
- type ProviderClientOptions
- type ProviderClientResolver
- type ProviderCredentialsExhaustedError
- type ProviderDef
- type ProviderDefaults
- type ProviderDescriptor
- type ProviderEnvCredentialRemoval
- type ProviderEnvCredentialSave
- type ProviderGroup
- type ProviderHookFailureScope
- type ProviderNotConfiguredError
- type ProviderNotSignedInError
- type ProviderProfileHooks
- type ProviderRegistry
- type ProviderRegistryAPI
- type ProviderRegistryGeneration
- type ProviderRegistryOptions
- type ProviderRequestOptions
- type ProviderRequestPermissionError
- type ProviderResponse
- type ProviderStreamError
- type ProviderTxn
- type ProviderTypeError
- type ProviderWriteHook
- type QuantVariant
- type RateLimitBucket
- type RateLimitState
- type Reasoning
- type ReasoningCapabilities
- type ReasoningReplayRoute
- type RejectedThinkingStore
- type RejectedThinkingTracker
- func (t *RejectedThinkingTracker) ApplyRejectedThinkingSuppression(messages []map[string]any) int
- func (t *RejectedThinkingTracker) CarryRejectedThinkingToSession(oldSessionID string)
- func (t *RejectedThinkingTracker) RememberRejectedThinking(apiMessages []map[string]any) int
- func (t *RejectedThinkingTracker) SessionRejectedThinking(sessionID string) map[string]bool
- func (t *RejectedThinkingTracker) TracksRejectedThinking() bool
- type RelayChatAccumulator
- type RelayExecuteOptions
- type RelayLogicalCompletion
- type RelayStreamOptions
- type RemovalResult
- type RemovalStep
- type Request
- type RequestAbortHook
- type RequestOpener
- type RequestProcessor
- type Response
- type ResponsesRoute
- type RetirementApplyResult
- type RetirementIssue
- type RetrySession
- type RotationRequest
- type Route
- type RouteEntryClient
- type RouterModels
- type RunBudgetAgent
- type RunawayStreamWatch
- type Runtime
- type RuntimeBaseURLResolver
- type RuntimeCredentialSource
- type RuntimeMainOptions
- type SafeCredentialRedirectHandler
- type ScopedCredentialSource
- type SecretCache
- func (c *SecretCache) Clear(homePath string)
- func (c *SecretCache) Lookup(key string, ttl float64, homePath string, readDisk func() (CachedFetch, bool)) (CachedFetch, bool, error)
- func (c *SecretCache) Store(key string, entry CachedFetch, ttl float64, homePath string)
- func (c *SecretCache) StoreMemory(key string, entry CachedFetch)
- type SecretDiskCache
- type SecretErrorKind
- type SecretErrorRule
- type SecretFetchResult
- type SecretScope
- type SecretSource
- type SecretSourceHooks
- type SecretSourceSpec
- type SelectionContext
- type SelectionRequest
- type SelectionWarning
- type SetupAsker
- type SetupAttributeError
- type SetupExit
- type SetupStep
- type SetupTypeError
- type SignInCancelledError
- type SignInCopyError
- type SourceEnvironment
- func (e *SourceEnvironment) Get(name string) (string, bool)
- func (e *SourceEnvironment) IsProcess() bool
- func (e *SourceEnvironment) Mapping() map[string]string
- func (e *SourceEnvironment) Set(name, value string)
- func (e *SourceEnvironment) Snapshot() map[string]string
- func (e *SourceEnvironment) Unset(name string)
- func (e *SourceEnvironment) Value(name string) string
- type SourceReport
- type SpotifyLoginOptions
- type SseDoneTracker
- type StartupModelRoute
- type StartupRouteOptions
- type StaticModelConflict
- type Store
- func (s *Store) ActiveProvider() (string, error)
- func (s *Store) ActiveProviderIs(normalized string) bool
- func (s *Store) ClearProviderAuth(providerID string) (bool, error)
- func (s *Store) Credential(provider string) (Credential, bool)
- func (s *Store) DeactivateProvider() error
- func (s *Store) GetProviderAuthState(providerID string) (map[string]any, error)
- func (s *Store) GlobalPath() string
- func (s *Store) Home() string
- func (s *Store) IsSourceSuppressed(providerID, source string) bool
- func (s *Store) Load() (AuthData, error)
- func (s *Store) LoadFile(path string) (AuthData, error)
- func (s *Store) LoadGlobal() AuthData
- func (s *Store) Lock(timeout time.Duration) (func(), error)
- func (s *Store) LockPath(authPath string, timeout time.Duration) (func(), error)
- func (s *Store) MarkProviderActiveIfUnset(providerID string) error
- func (s *Store) OnProviderWrite(h ProviderWriteHook)
- func (s *Store) Path() string
- func (s *Store) PersistProviderStateToStore(providerID string, state map[string]any, target string, setActive bool) (string, error)
- func (s *Store) ProviderState(data AuthData, providerID string) map[string]any
- func (s *Store) ProviderStateWithSource(data AuthData, providerID string) (map[string]any, string)
- func (s *Store) ProviderTransaction(providerID string, timeout time.Duration, fn func(tx *ProviderTxn) error) error
- func (s *Store) ReadCredentialPool(providerID string) ([]map[string]any, error)
- func (s *Store) ReadCredentialPools() (map[string][]map[string]any, error)
- func (s *Store) Save(data AuthData) error
- func (s *Store) SaveActiveProviderState(providerID string, state map[string]any) (string, error)
- func (s *Store) SaveProviderStateToSource(data AuthData, providerID string, state map[string]any, source string) error
- func (s *Store) SaveTo(data AuthData, target string) error
- func (s *Store) StoreProviderState(data AuthData, providerID string, state map[string]any, setActive bool) error
- func (s *Store) SuppressCredentialSource(providerID, source string) error
- func (s *Store) SuppressedCredentialSources(providerID string) map[string]bool
- func (s *Store) UnsuppressCredentialSource(providerID, source string) (bool, error)
- func (s *Store) Update(fn func(data AuthData) (bool, error)) error
- func (s *Store) WriteCredentialPool(providerID string, entries []map[string]any, ...) ([]map[string]any, error)
- type StreamAbandonedError
- type StreamChunks
- type StreamDiag
- type StreamDiagAgent
- type StreamEmitters
- type StreamEvent
- type StreamEventOrderError
- type StreamFunc
- type StreamLifetimeExceededError
- type StreamRequestError
- type StreamResponseHolder
- type StreamWriterFence
- type StreamingThinkScrubber
- type SuspectableBackend
- type SwitchModelOptions
- type SwitchRoute
- type TLSSettings
- type TLSVerify
- type TaggedTokenSource
- type TimeoutPhaseError
- type TokenMapping
- type TokenPair
- type ToolFeatureState
- type ToolFeatures
- type Transport
- type UnknownAuthProviderError
- type UnscopedSecretError
- type UnsupportedProviderRequestError
- type UpstreamAdapter
- type UpstreamCredential
- type Usage
- type UsageAnchor
- type UsageAnchorState
- type UsageAnchorStore
- type UsageCostHook
- type ValidateModelOptions
- type ValueError
- type VariantChoice
- type Verdict
- type VisionCapabilities
- func (VisionCapabilities) CatalogSupportsVision(ctx context.Context, provider, model string) (supported, known bool)
- func (VisionCapabilities) DetectLocalServerType(ctx context.Context, baseURL, apiKey string) string
- func (VisionCapabilities) IsLocalEndpoint(baseURL string) bool
- func (VisionCapabilities) IsManagedEndpoint(baseURL string) bool
- func (VisionCapabilities) IsRoutingAggregator(provider string) bool
- func (VisionCapabilities) ManagedModelSupportsVision(ctx context.Context, model string) (supported, known bool)
- func (VisionCapabilities) ProviderVisionProfile(provider string) (supportsVision, supportsVisionToolMessages, found bool)
- func (VisionCapabilities) QueryOllamaSupportsVision(ctx context.Context, model, baseURL, apiKey string) (supported, known bool)
- func (VisionCapabilities) StripCodexContextVariantSuffix(model string) string
- type WaitNoticeState
- type WatchdogDeadline
- type WindowDecision
- type WindowOutcome
- type WindowsJob
- type WireAliasTransport
- type XAIGrokAdapter
- func (a *XAIGrokAdapter) AllowedPaths() map[string]bool
- func (a *XAIGrokAdapter) AuthHint() string
- func (a *XAIGrokAdapter) DisplayName() string
- func (a *XAIGrokAdapter) GetCredential() (UpstreamCredential, error)
- func (a *XAIGrokAdapter) GetRetryCredential(failed UpstreamCredential, statusCode int) (*UpstreamCredential, error)
- func (a *XAIGrokAdapter) IsAuthenticated() bool
- func (a *XAIGrokAdapter) Name() string
- type XAILoginArgs
Constants ¶
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 )
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" )
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" )
const ( PreAuxiliaryCall = "pre_auxiliary_call" PostAuxiliaryCall = "post_auxiliary_call" )
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 )
const ( TimeoutPhaseConnect = "connect" TimeoutPhaseRead = "read" TimeoutPhaseWrite = "write" TimeoutPhasePool = "pool" )
Transport timeout phases an adapter may stamp on an error
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
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
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
const ( HighEffortSilenceFloorSeconds = 300.0 CodexFirstProgressTimeoutSeconds = 300.0 )
Silence floor for high effort reasoning and the first progress grace of large Codex requests
const ( CredentialSourceEntraID = "entra-id" CredentialSourceVertexOAuth = "vertex-oauth" CredentialSourceMinimaxOAuth = "minimax-oauth" )
Credential source tags for callable keys that mint a bearer on first use
const ( IronProxyMgmtKeyEnv = "ICEBATH_IRON_PROXY_MGMT_KEY" DefaultIronTunnelPort = 9090 IronProxyNonceEnv = "ICEBATH_IRON_PROXY_NONCE" )
const ( SpeedFloorTokS = 6.0 TargetWindow = 144 * 1024 RuntimeOverheadBytes = int64(1.5 * (1 << 30)) DefaultUbatch = 512 PrefillUbatch = 2048 )
const ( GrowthActionGrow = "grow" GrowthActionHold = "hold" GrowthActionCompress = "compress-default" )
Growth verdict actions
const ( GGMLDeviceGPU = 1 GGMLDeviceIGPU = 2 )
Device types of enum ggml_backend_dev_type in ggml-backend.h
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
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" )
const ( ModelSwitchErrOnceWithGlobal = "once_with_global" ModelSwitchErrOnceRequiresTarget = "once_requires_target" ModelSwitchErrBadReasoning = "bad_reasoning" ModelSwitchErrResetWithFlags = "reset_with_flags" )
Error codes a model command request can carry
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 )
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 )
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
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
const ( DefaultProxyPort = 8645 DefaultProxyHost = "127.0.0.1" )
const ( DefaultSecretFetchTimeout = 120 * time.Second DefaultSecretCLITimeout = 30 * time.Second )
const ( HostedChoice = "choice" HostedChecklist = "checklist" HostedText = "text" HostedSecret = "secret" HostedCommand = "command" )
Kinds of question a hosted setup flow puts to its host
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
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 )
const ( BarWidth = 10 BarFill = "|" BarEmpty = " " )
Usage bar geometry, cells and the basis points of a full allowance
const ( XAIMigrationGuideURL = "https://docs.x.ai/developers/migration/may-15-retirement" XAIRetirementDate = "May 15, 2026" )
const ( // AIGatewayBaseURL is the Vercel AI Gateway OpenAI compatible root AIGatewayBaseURL = home.AIGatewayBaseURL )
const APITimeoutEnv = "ICEBATH_API_TIMEOUT"
Env var for the overall request timeout in seconds
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
const AuxExplicitCancelCause = "explicit_host_cancel"
AuxExplicitCancelCause is the frozen cause every explicit auxiliary cancellation carries
const BedrockConverseIssuerType = "bedrock.native_assistant"
BedrockConverseIssuerType names the reasoning_details record stamping the model that minted a turn
const BedrockDefaultContextLength = 128_000
BedrockDefaultContextLength is the window of a Bedrock model no source knows
const BedrockGuardrailActionField = "amazon-bedrock-guardrailAction"
BedrockGuardrailActionField is the InvokeModel body field flagging a guardrail substitution
const CharsPerToken = tools.ModelCharsPerToken
Rough chars per token ratio for ASCII text
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
const CodexContextVariantSuffix = "-900k"
CodexContextVariantSuffix is the picker only opt in suffix never sent on the wire
const CodexModelsCatalogEndpoint = "https://chatgpt.com/backend-api/codex/models"
CodexModelsCatalogEndpoint is the hard coded Codex catalog
const CodexNewestClientVersion = "99.0.0"
const CodexQuotaProbeMinInterval = 300 * time.Second
CodexQuotaProbeMinInterval throttles the live Codex quota probe per access token
const CodexStreamStallMarker = "stream stalled"
Text the context compressor reads as a retry ladder timeout
const CodexToolsMCPServerEntry = "__icebath_tools_mcp_server__"
CodexToolsMCPServerEntry is the argv[1] that turns the icebath binary into the tools MCP server
const CodexToolsMCPServerName = "icebath-tools"
CodexToolsMCPServerName is the mcp_servers key the runtime migration registers the icebath tools server under
const CodexUngatedClientVersion = "0.0.0"
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
const ContextFloor = 64 * 1024
The guaranteed and target window of every managed local model
const (
// Display label source for a key minted by a command
CredentialSourceKeyCmd = "key-cmd"
)
const (
// DaybreakProgram is the cyber access program the Daybreak switch requests
DaybreakProgram = "daybreak_blue"
)
const (
// DeepinfraDefaultBaseURL is the OpenAI compatible DeepInfra root
DeepinfraDefaultBaseURL = "https://api.deepinfra.com/v1/openai"
)
const DefaultCatalogURL = "https://icebath.app/api/model-catalog.json"
DefaultCatalogURL is the site copy of the shipped model catalog the refresh fetches
const DefaultContextCacheSwitchThreshold = 100_000
DefaultContextCacheSwitchThreshold is the context size above which a mid session switch asks first
const DefaultErrorBodyMaxBytes = 64 * 1024
Byte cap that holds any real provider error envelope while rejecting pathological bodies
const DefaultErrorBodyTimeout = 10 * time.Second
Hard deadline for the whole read, past it the connection is closed and the partial bytes kept
const DefaultFallbackContext = 256_000
DefaultFallbackContext is the window assumed when every detection source misses
const DefaultFastWindowSeconds = 60
Default bounded fast window length
const DefaultImageTokenCost = 1500
Flat per image token price before a route calibrates it from usage
const DefaultMTPDraftDepth = 3
The speculative draft depth launch flags use unless told otherwise
const DeviceCodeExpiredCode = "device_code_timeout"
DeviceCodeExpiredCode is the code a device code poller carries when the code ran out
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
const (
// ForkScopeSeparator joins a scope and a fork tag, doubled so single colon gateway keys never read as forks
ForkScopeSeparator = "::"
)
const GeminiDefaultMaxOutputTokens = geminiDefaultMaxOutputTokens
GeminiDefaultMaxOutputTokens is the maxOutputTokens the native adapter sends when no cap is set
const HookCtxKey = hookCtxKey
Params key the agent request builder stores its turn context under for the profile hooks
const HookPayloadMaxCharsEnv = "ICEBATH_PLUGIN_PAYLOAD_MAX_CHARS"
Env var overriding the serialized hook payload cap, floor 1000 chars
const (
IcebathPKCESource = "icebath_pkce"
)
Source label of the Anthropic OAuth file icebath writes, and the spelling older builds stored in auth.json
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"
)
const KimiCodeBaseURL = "https://api.kimi.com/coding"
Kimi Code endpoint selected by an sk-kimi- prefixed key
const LargeRequestHintBytes = 256 * 1024
LargeRequestHintBytes is the body size above which a refused connect may be a size limit
const LiveRetryWaitCap = 60 * time.Second
LiveRetryWaitCap is the wait a person feels so longer non rate limit waits are announced when they start
const LlamaIdleUnloadS = 15 * 60
Seconds a resident model may stay idle before the sweeper unloads it and frees its memory
const LlamacppProviderID = "llamacpp"
LlamacppProviderID is the managed llama.cpp runtime provider id the resolver and the picker Local row share
const LocalStreamStaleTimeoutEnv = "ICEBATH_LOCAL_STREAM_STALE_TIMEOUT"
Env var for the stale ceiling of a local endpoint in seconds
const MaxHistorySeedChars = 32_000
MaxHistorySeedChars caps the rendered history codex resends on every request of a fresh thread
const MinFragmentLength = 400
Fragments shorter than this are never judged for repetition
const MinimumContextLength = 64_000
MinimumContextLength is the smallest window sessions, model switches and cron jobs accept
const ModelSwitchResetToken = "reset"
ModelSwitchResetToken clears the session model override instead of naming a model
const ModelsDevURL = "https://models.dev/api.json"
ModelsDevURL is the live registry endpoint
const NearDeadlineSecs = 15.0
Seconds before a watchdog fires inside which the notice says still waiting and updates once
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
const OneshotSource = "oneshot"
Source label of finite one shot runs
const OpenRouterModelsURL = home.OpenRouterModelsURL
OpenRouter catalog endpoint
const OpencodeSessionHeader = "x-opencode-session"
Header the OpenCode relay pins a conversation to one upstream backend with
const PartialStreamStubID = "partial-stream-stub"
Response id of a stream that ended without a finish reason after delivering content
const PleasantFloorTokS = 20.0
Predicted decode speed below which a model stops feeling pleasant for agentic use
const PreferredSilentDefaultModel = "z-ai/glm-5.3"
PreferredSilentDefaultModel is the offline fallback for the model landed on when the user never picked one
const ProviderStreamEmptyFrameCode = "provider_stream_empty_frame"
Error code of an SSE frame that carried no payload at all
const ProviderStreamEmptyFrameErrorCode = "provider_stream_empty_frame"
Same rejection with an empty payload so the session switches to non streaming
const ProviderStreamNonJSONCode = "provider_stream_non_json_data"
Error code of an SSE data frame that was not JSON
const ProviderStreamNonJSONErrorCode = "provider_stream_non_json_data"
Synthetic code for a stream data field rejected before any completion chunk arrived
const ReasoningCapsDiskTTL = reasoningCapsDiskTTL
ReasoningCapsDiskTTL is how long a disk mirrored catalog counts as fresh
const ReasoningFloorEffort = "low"
ReasoningFloorEffort is the lowest effort every reasoning wire accepts
const RepetitionLoopInterrupted = "[the reply degenerated into a repetition loop and was interrupted]"
Interrupt checkpoint text used instead of a repetition dominated partial
const RetryAfterCap = 600 * time.Second
RetryAfterCap rejects pathological provider waits while covering Anthropic Tier 1 bucket resets
const SDKDefaultTimeout = auxSDKDefaultTimeout
SDKDefaultTimeout is the OpenAI SDK default request timeout in seconds
const ScopeAIAzureDefault = "https://ai.azure.com/.default"
Default Entra scope for Azure AI Foundry
const SecretSourceAPIVersion = 1
SecretSourceAPIVersion gates plugin secret source compatibility
const SetupProviderHelp = "icebath model --help"
Help command the provider setup screen points to
const SnapshotOwnerKey = "custom_entry"
SnapshotOwnerKey is the primary runtime field holding the owning entry's provenance
const StopPathMinChars = 16000
Stop path scale floor below which asked for repeats are delivered
const StreamReadTimeoutEnv = "ICEBATH_STREAM_READ_TIMEOUT"
Env var for the socket read timeout of a streaming request in seconds
const StreamStaleTimeoutEnv = "ICEBATH_STREAM_STALE_TIMEOUT"
Env var for the stale stream detector base in seconds
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
const ToolStreamingBeta = anthToolStreamingBeta
Anthropic beta that enables fine grained tool streaming, added for Claude over OpenRouter
const (
TurnAuthorEnvName = "ICEBATH_TURN_AUTHOR"
)
const UsageAnchorModelConfigKey = "_usage_anchor"
UsageAnchorModelConfigKey is the session model config key holding the persisted usage anchor
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 ¶
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*\}`) )
var ( ResponsesBypassFields = []string{"input", "tools"} ChatCompletionsBypassFields = []string{"messages", "tools"} )
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
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
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
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
var AuxRouteKeys = auxRouteKeys
Exported auxiliary route fields that travel as one unit
var BackendPackages = map[string]string{
"cuda": "llamacpp-cuda",
"vulkan": "llamacpp-vulkan",
"metal": "llamacpp-metal",
"hip": "llamacpp-hip",
"cpu": "llamacpp-cpu",
}
var BedrockCachePointPlacements = []string{"tools", "system", "messages"}
BedrockCachePointPlacements lists the Converse sections a cachePoint marker can sit in
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
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
var BoundedFastModes = map[string]bool{"auto": true, "cold": true}
Service tiers that open a bounded window per user turn or per session start
var BuildVersion = "dev"
Release string stamped into user agents and attribution tags, set by the build
var CodexLoginFlows = []string{"device_code", "browser"}
CodexLoginFlows are the login flows auth.codex_login_flow may name
var CodexMinVersion = [3]int{0, 125, 0}
CodexMinVersion is the oldest codex CLI the app server runtime accepts
var CodexTierWords = map[string]string{"priority": "fast"}
Codex app server names for the wire tiers it accepts
var CodexValidRuntimes = []string{"auto", "codex_app_server"}
Runtimes the codex runtime switch accepts
var DefaultBackoff = BackoffOptions{BaseDelay: 5 * time.Second, MaxDelay: 120 * time.Second, JitterRatio: 0.5}
DefaultBackoff matches the 5s base, 120s cap, half jitter schedule
var DefaultCatalogFallbackURLs = []string{
"https://raw.githubusercontent.com/nickheyer/icebath/main/pkg/provider/model-catalog.json",
}
DefaultCatalogFallbackURLs hold the same manifest at its repository path
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
var DefaultHookJSONCaps = HookJSONCaps{MaxDepth: 8, MaxString: 8000, MaxSequence: 200}
DefaultHookJSONCaps matches depth 8, 8000 char strings, and 200 item sequences
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
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
var DefaultProbePorts = []int{8080}
Ports probed for a llama-server beside the managed and configured ones, always on 127.0.0.1
var DeveloperRoleModels = []string{"gpt-5", "codex"}
DeveloperRoleModels are model name substrings whose system prompt is sent under the developer role
var DirectAliases = NewDirectAliasTable()
DirectAliases holds the builtin plus active profile aliases, reloaded in place when the profile config changes
var DoneSSEFrame = []byte("data: [DONE]\n\n")
DoneSSEFrame is the terminal sentinel strict OpenAI clients expect at the end of a stream
var DumpBlockedLoop = dumpBlockedLoopDiagnostics
Diagnostics dump of a dispatch goroutine that never processed its expiry, the stack dumper in production
var ErrNoAWSCredentials = errors.New("Unable to locate credentials")
ErrNoAWSCredentials is the chain walked to the end without any source answering
var ErrSecretPromptInterrupted = errors.New("KeyboardInterrupt")
ErrSecretPromptInterrupted is the Ctrl+C a masked secret prompt raises as KeyboardInterrupt
var ErrStreamStalled = errors.New(CodexStreamStallMarker)
Main model stream that stopped producing chunks after it had started
var ExternalLoginProviders = map[string]bool{"anthropic": true, "openai-codex": true}
ExternalLoginProviders are the providers whose sibling CLI login icebath may borrow
var FastArgAliases = map[string]string{"ultra": "ultrafast"}
Typed /fast shorthands to the canonical word
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
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
var GetModelContextLength func(ctx context.Context, req ContextLengthRequest) int
GetModelContextLength resolves the window through config, caches, probes, catalogs and defaults
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
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
var LlamacppAliases = map[string]bool{"llamacpp": true, "llama.cpp": true, "llama-cpp": true}
Provider names that route to the managed llama.cpp server
var LoopBlockedDumpGrace = 5 * time.Second
Grace after a deadline fires before the blocked worker is reported
var LoopbackHosts = []string{"127.0.0.1", "localhost", "::1"}
LoopbackHosts must never be dialed through a proxy
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
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
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
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
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
var NormalTierWords = map[string]bool{"": true, "normal": true, "default": true, "standard": true, "off": true, "none": true}
Words that mean the normal tier
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
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
var PluginAuthActions = []string{"add", "status", "logout", "refresh"}
Auth actions a provider plugin's auth handler can own
var PluginUsageHookDeadline = 10 * time.Second
Wall clock bound on a plugin profile account usage hook, shared by every usage surface
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
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
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
var RateLimitFailoverReasons = map[FailoverReason]bool{ReasonRateLimit: true, ReasonBilling: true, ReasonUpstreamRateLimit: true}
Failover reasons that leave the primary rate limited and so arm its cooldown
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
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
var RetryableClientReasons = map[FailoverReason]bool{ ReasonRateLimit: true, ReasonUpstreamRateLimit: true, ReasonOverloaded: true, ReasonContextOverflow: true, ReasonPayloadTooLarge: true, ReasonLongContextTier: true, ReasonThinkingSignature: true, }
Reasons the retry loop keeps retrying with backoff before any fallback cascade
var RunGitWithCredentialFallback = gitcred.RunGitWithCredentialFallback
Runs a git network verb anonymously, then with each credential the user owns for the remote host
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
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
var SingleUseOAuthSingletonFiles = []string{".anthropic_oauth.json"}
SingleUseOAuthSingletonFiles hold single use grants outside auth.json and must never be copied into a profile
var SingleUseRefreshPoolProviders = map[string]bool{"anthropic": true, "openai-codex": true, "xai-oauth": true}
SingleUseRefreshPoolProviders rotate a single use refresh token on every refresh
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
var StaticTiers = map[string]bool{"priority": true, "ultrafast": true}
Tiers sent on every request of the session
var StrayToolCallCloserPattern = regexp2.MustCompile(`</(?:`+toolTagNSPrefix+`(?:`+toolCallTagAlt+`|function))>\s*`, regexp2.IgnoreCase)
Orphan tool call or function closing tag with the whitespace after it
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
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
var SupportedPoolStrategies = map[string]bool{StrategyFillFirst: true, StrategyRoundRobin: true, StrategyRandom: true, StrategyLeastUsed: true}
var SwitchModel = switchModel
SwitchModel routes, resolves credentials for and validates a model switch shared by the CLI and gateway
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
var ThinkTagNames = []string{"think", "thinking", "reasoning", "thought", "REASONING_SCRATCHPAD", "思考", "反思", "推理", "推敲"}
Reasoning tag names every surface hides
var UITransportSources = map[string]bool{"tui": true}
Interactive UI transport labels a one shot child inherits but does not belong to
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
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
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
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 ¶
Prompt an ACP client sends for OpenAI chat messages, tools and tool choice
func AIGatewayHeaders ¶
AIGatewayHeaders is the AI Gateway attribution header set for callers outside the package
func AIGatewayModelIDs ¶
AIGatewayModelIDs returns just the AI Gateway model id strings
func AWSErrorClassName ¶
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 ¶
AddLoopbackNoProxy appends the loopback hosts to both NO_PROXY casings in env keeping operator entries
func AddOpenAIClientResponseHook ¶
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 ¶
AdoptExternalLoginsEnabled is auth.adopt_external_logins, default true, logged once when off
func AdoptLegacyEngine ¶
Moves the newest verified pre PM install of backend into PM's store and records it, never fails, true when moved
func AffinityScope ¶
Declared routing affinity scope the context carries, empty when unset
func AffordableMaxTokensFromError ¶
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 ¶
AnsweredByRequestedModel reports a provider reported model that is the requested one or a dated snapshot of it, an empty report matching
func AnthropicBaseClientQuery ¶
Normalized Anthropic base URL with the default query Azure endpoints need, nil for every other endpoint
func AnthropicLiveBlocks ¶
AnthropicLiveBlocks is the live ordered Messages content block sidecar of a message, false when it has none
func AnthropicMaxOutput ¶
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 ¶
Whether an Anthropic compatible base URL authenticates with a bearer token instead of x-api-key
func AnthropicResponseGuardrailIntervened ¶
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 ¶
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 ¶
ApplyDaybreak adds the daybreak cyber access program when enabled and the request credential and model are listed
func ApplyDefaultAgentSettings ¶
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 ¶
Resolved headers with model.default_headers and model.extra_headers merged over them, user values winning
func ApplyUserMoAPresets ¶
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 ¶
AsyncCallLLM runs an auxiliary LLM request on the async client surface under the async task limit
func AtomicWriteCacheJSON ¶
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 ¶
AutoCacheTTLForSource resolves the auto tier, 5m for machine paced sources and 1h for human paced ones
func AutoDetectLocalModel ¶
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 ¶
AuxClientCredential is the rotating key source of an SDK client when it has one, else its static key
func AuxClientCustomHeaders ¶
Copy of the custom default headers a routed SDK client sends, nil when the client keeps none
func AuxClientDefaultHeaders ¶
AuxClientDefaultHeaders is the header set an SDK client sends on every request, nil for adapters
func AuxClientEffectiveProvider ¶
Provider a routed auxiliary client was stamped with, empty when the client carries no stamp
func AuxExcTypeName ¶
AuxExcTypeName exposes the Python class name of the outermost auxiliary client error
func AuxFallbackEntryAPIKey ¶
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 ¶
Python TimeoutError, connection error check of the auxiliary client for summary failure classification
func AuxModelForProvider ¶
Cheap auxiliary model of a provider, the live catalog fast tier first when preferFast is set
func AuxProbeMode ¶
AuxProbeMode resolves provider availability under the returned context without building real SDK clients
func AuxProgressHook ¶
AuxProgressHook installs the forward progress callback for auxiliary calls under the context
func AuxReadMainModel ¶
AuxReadMainModel exports the main model reader for the plugin LLM facade
func AuxReadMainProvider ¶
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 ¶
AuxThreadLocalHook installs one timing hook for calls under the context, a nil hook keeping the previous one
func AuxiliaryMaxTokensParam ¶
Max tokens kwarg for the auxiliary provider, max_completion_tokens for direct OpenAI, declaring profiles and newer OpenAI models
func AuxiliaryTaskConfig ¶
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 ¶
Number of foundation models the Bedrock control plane lists for a region, one attempt with a ten second read limit
func BedrockGuardrailConfig ¶
BedrockGuardrailConfig is the configured Converse guardrail of the home the context serves
func BedrockModelRoutableFromRegion ¶
BedrockModelRoutableFromRegion is true when the model id can be invoked from the region's endpoint
func BedrockRegionGeoPrefix ¶
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 ¶
BindImageTokenCost binds the learned per image price of model and base URL for the rest of the turn
func BindProfileSecretScope ¶
BindProfileSecretScope binds the built secret scope of a profile home on ctx the way plugin_host bind sets it
func Blake2bSum ¶
BLAKE2b digest of data with the given output size in bytes
func BodyRetryAfter ¶
Positive cooldown a retry_after field declares at the top of an SDK error body or under its error object
func BotAuthorID ¶
Bot author id, bot:profile on this install and bot:origin/profile for one on another install
func BoundRegistryKey ¶
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 ¶
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 ¶
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 ¶
BuildNvidiaNIMHeaders returns the NIM cloud attribution headers for integrate.api.nvidia.com traffic
func BuildORHeaders ¶
BuildORHeaders returns the OpenRouter headers plus response cache headers, env over config over default, nil config read from disk
func BuildOpenAIToolCall ¶
OpenAI compatible tool call for downstream handling
func BuildPlanPrompt ¶
BuildPlanPrompt builds the plan mode turn prompt, an empty task asking the agent to infer it from context
func BuildProfileSecretScope ¶
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 ¶
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 ¶
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 ¶
CallLLM runs an auxiliary LLM request under the configured task limit and relay identity
func CallableKeyIdentity ¶
CallableKeyIdentity is the closure identity of a callable credential, false for a static key
func CanonicalAPIMode ¶
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 ¶
CapToRunBudget caps an implicit stale timeout at half the remaining run budget, never under sixty seconds
func CaptureLaunchEnv ¶
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 ¶
CarrierRecord is the private reasoning_details record of one response message, nil when it carries nothing
func CatalogCachePath ¶
CatalogCachePath is the per profile disk cache file
func CatalogItemIsGeneration ¶
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 ¶
CatalogProviderAlias resolves a picker alias to its provider with built in aliases beating plugin ones
func CatalogProviderAliases ¶
CatalogProviderAliases returns every alias pair, built in first then plugin declared
func CatalogProviderLabel ¶
CatalogProviderLabel returns the short display label for a slug, empty when unknown
func CatalogRefreshInterval ¶
CatalogRefreshInterval is the configured TTL as the gateway poll cadence, at least one minute
func ChatCatalogIDs ¶
ChatCatalogIDs lists the model ids of a models payload minus generation rows
func ChatWireNeedsKeyOrder ¶
Whether a builder key order puts the keys a chat completions body keeps in another order than the encoder default
func CheckCodexBinary ¶
Verifies the codex CLI is installed at the minimum version, the version text or the failure message
func CheckCodexBinaryOK ¶
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 ¶
ClaimKeptNotices takes every notice kept for the active home, for a turn someone sees
func ClaimStreamWriter ¶
Claims the delta sink for a stream attempt, zero when the agent lacks the fence or the claim panics
func ClampEffort ¶
Nearest weaker supported effort, the request verbatim when supported or outside the ladder
func ClampReasoningEffortToSupported ¶
ClampReasoningEffortToSupported keeps a supported level verbatim else the nearest weaker supported level
func ClampTimeout ¶
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 ¶
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 ¶
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 ¶
ClearCatalogFetchBackoff forgets the active profile's fetch failures so an explicit refresh retries every URL
func ClearCodexPoolQuotaCooldowns ¶
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 ¶
ClearProviderModelsCache drops one provider's cache row under the cache lock
func ClearWindowOverride ¶
Drops a model's growth state, leaving the file untouched when it has none
func CmdMoA ¶
CmdMoA manages Mixture of Agents presets for the icebath moa command, list when no subcommand is given
func CmdModel ¶
CmdModel is icebath model after the terminal check, the cache refresh then the picker under setup navigation
func CmdProxy ¶
CmdProxy dispatches icebath proxy <subcommand>, a missing or unknown one printing the short help
func CodexCatalogCredentialIdentity ¶
CodexCatalogCredentialIdentity names the principal and route live discovery would use for the cache key
func CodexCatalogURLs ¶
CodexCatalogURLs builds the catalog urls against a gateway base or the hard coded endpoint
func CodexCloudflareHeaders ¶
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 ¶
Runtime named by the command argument, nil with no argument, an error line for an unknown name
func CodexStaleTimeoutFloor ¶
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 ¶
CoerceAPIErrorDetail renders a structured provider error field as display text
func CoerceFloat ¶
CoerceFloat reads a config number with a default for malformed values
func CoerceInsecure ¶
CoerceInsecure reads an ssl_verify setting as a request to disable verification
func CoerceLLMMessage ¶
CoerceLLMMessage pulls the message out of a response or returns a bare message, nil for an empty choices list
func CoercePositiveTimeout ¶
Positive float timeout of a raw config value, false for missing, non numeric or non positive values
func CoercePrivacyFilter ¶
CoercePrivacyFilter normalizes the MoA privacy filter to off, display or full
func CoerceProviderID ¶
CoerceProviderID renders a provider identity field as a trimmed string
func CoerceToolName ¶
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 ¶
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 ¶
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 ¶
Configured custom provider ids of the active config
func ConfiguredProviderName ¶
Configured section provider from the read only config, stripped
func ConnectExhaustedNotice ¶
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 ¶
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 ¶
Conversation lineage root id the context carries, empty when unset
func CoreDeclaredEnvNames ¶
CoreDeclaredEnvNames lists every name core declares, static entries plus provider profile entries
func CountImages ¶
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 ¶
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 ¶
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 ¶
CuratedCatalogRows returns a copy of every curated row with the xAI rows resolved
func CurrentAuxProgressHook ¶
Forward progress hook bound to the calling scope
func CurrentAuxStreamDeadline ¶
Auxiliary stream deadline bound to the calling scope
func CurrentCachePath ¶
CurrentCachePath is the home level cache file, deleting a legacy copy under cache first
func CurrentImageTokenCost ¶
CurrentImageTokenCost is the per image price bound to the running turn, else the flat default
func CurrentPromptReadingHook ¶
Prompt reading hook installed on the context, nil when none
func CurrentSecretScope ¶
CurrentSecretScope is the active mapping, nil when no scope is installed
func CurrentSecretScopeHome ¶
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 ¶
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 ¶
CustomProviderSlug is the stable custom identity, keyed providers entries by their config key
func DaybreakOffered ¶
DaybreakOffered reports whether the Codex subscription route and the account catalog list daybreak for the model
func DeclaredAuthProviders ¶
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 ¶
Declared model ids of a provider entry's models config in declaration order
func DeclaresModelProviderKind ¶
Whether a plugin manifest declares the model provider kind, the exported form plugins reach through Services
func DecodeJWTClaims ¶
DecodeJWTClaims returns the unverified payload object of a three part JWT or an empty map
func DecodeMoATurn ¶
DecodeMoATurn splits a hidden one shot MoA marker into its prompt and normalized preset, nil when not a marker
func DecorateXAIEntitlementError ¶
DecorateXAIEntitlementError appends the Premium+ hint once to an xAI permission denied detail
func DeepinfraBaseURL ¶
DeepinfraBaseURL is the config section base_url, then the env override, then the default
func DeepinfraModelIDs ¶
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 ¶
DefaultContextLengths exposes the family fallback table as a map
func DefaultModelFromCatalogCache ¶
DefaultModelFromCatalogCache returns the manifest's labeled default from memory, disk, then the shipped manifest, never a fetch
func DeferStartupNotice ¶
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 ¶
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 ¶
DescribePrimary is the one line model (via provider) of the configured primary, empty for none
func DetectLocalServerType ¶
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 ¶
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 ¶
DirectAliasRuntimeRequest returns the provider to resolve and the explicit key, custom whenever the alias names a URL
func DiscoverFlag ¶
Reports whether live model discovery is enabled for a provider entry
func DiscoverUncoveredProviders ¶
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 ¶
Assignments with a value of a utf-8-sig dotenv file interpolated like python-dotenv dotenv_values
func DotenvUnreadable ¶
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 ¶
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 ¶
Endpoint binds replayed Responses item ids to a connection so replay must drop them
func DumpIfModel ¶
Plain dict of an SDK model, any other value unchanged
func EagerFallbackStatus ¶
func EagerFallbackStatus(cl *Classified, isUpstream, isTransport bool) string
func EffectiveAuxTimeout ¶
Explicit timeout first, then the task config, compression floored so long summaries are not cut off
func EffectiveCacheTTL ¶
Cache lifetime the route honours for the configured TTL
func EffectiveRuntimeProvider ¶
EffectiveRuntimeProvider is the identity to persist for a resolved fallback entry, the configured name over bare custom
func EffortDisplayLabel ¶
EffortDisplayLabel is the picker and reasoning status label for a level on a route
func EffortLadderIndex ¶
EffortLadderIndex is the position of a reasoning effort on the ladder, -1 when absent
func EgressCommand ¶
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 ¶
EnabledSecretSourceNames are the sources an apply would fetch for the home right now
func EnsureAuditLog ¶
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 EntryDeclaresCredential ¶
EntryDeclaresCredential reports whether a custom entry names its own credential
func EntryModelsDiscovered ¶
Reports whether a provider entry marks its models as discovered
func EnvWriterLaunchDenylist ¶
EnvWriterLaunchDenylist is every external process launch env name plus every left core row's launch env
func EnvelopeToolPartCacheMarkersSupported ¶
Reports whether the route accepts cache markers on tool parts
func EstimateMessageTokensRough ¶
Memoized rough token weight of one message row at the given per image cost
func EstimateMessagesTokens ¶
Memoized rough token estimate of a message list for preflight decisions
func EstimateNativeAnthropicMessagesTokens ¶
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 ¶
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 ¶
Memoized tokens of dict message rows with every priced key of each dict counted
func EstimateTokens ¶
Rough token estimate, CJK codepoints one token each and the rest ceil of UTF8 bytes over four
func EstimateToolsTokens ¶
Rough token estimate of tool schemas, names, descriptions and parameters JSON, memoised per tools list
func EvictOldScreenshots ¶
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 ¶
ExactMoAPresetName returns the text when it names an enabled preset, empty otherwise
func ExcStatusCode ¶
HTTP status carried on the error itself or on its response, zero when absent
func ExpandDirectAPIAlias ¶
Provider openai expanded onto custom plus the configured OpenAI endpoint, other providers unchanged
func ExternalProcessLaunchEnvNames ¶
ExternalProcessLaunchEnvNames lists the env names that choose an external provider's executable or argv
func ExtractAPIErrorContext ¶
ExtractAPIErrorContext pulls reason, message, and reset_at out of a provider error body, headers, and text
func ExtractCompressFlags ¶
Remaining args with preview, dry run and aggressive tokens removed anywhere, plus whether each was present
func ExtractContentOrReasoning ¶
ExtractContentOrReasoning is the response content without think blocks, else its reasoning fields bounded when the cap is not negative
func ExtractFallbackFromModelCfg ¶
ExtractFallbackFromModelCfg pulls provider, model, base_url and api_mode out of a config model snapshot
func ExtractToolCallsFromText ¶
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 ¶
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 ¶
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 ¶
FetchModelMetadata returns the OpenRouter catalog, cached for an hour in memory and on disk
func FetchModelsDev ¶
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 ¶
FindBws resolves the bws binary from PATH or the tool store, installing on a miss when asked
func FindCustomProviderIdentity ¶
FindCustomProviderIdentity maps an endpoint URL back to its canonical custom menu key
func FindCustomProviderIdentityByModel ¶
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 ¶
Index and length of the earliest case insensitive tag in buf, minus one and zero when none
func FindOp ¶
FindOp resolves a usable op binary, a pinned path is used verbatim and never falls back to PATH
func FindProviderEntry ¶
FindProviderEntry returns the stored key and block matching a provider key by string identity
func FingerprintSecretValue ¶
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 ¶
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 ¶
Renders Outer(msg) <- Inner(msg) walking the wrapped causes, deduplicated and at most four deep
func FlattenMessageText ¶
FlattenMessageText exports the visible text join of message content shapes
func FloorReasoningConfig ¶
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 ¶
ForceCloseTCPSockets aborts in flight TCP reads and writes on every pool socket of the client
func ForgetMessageTokenMemo ¶
ForgetMessageTokenMemo evicts entries pinning any long string of the messages that keep does not hold
func ForgetPluginGrants ¶
ForgetPluginGrants drops every grant of a plugin key from the active profile
func FormatAuthError ¶
FormatAuthError maps an auth failure onto concise user facing guidance
func FormatCostLabel ¶
FormatCostLabel renders zero as $0.00, sub cent amounts at four places and everything else at two
func FormatCount ¶
FormatCount renders 7999856 as 8.0M and 33599 as 33.6K
func FormatDurationCompact ¶
FormatDurationCompact renders seconds as s, m, h m or fractional days
func FormatEgressStatusText ¶
FormatEgressStatusText is the plain text egress status for slash commands
func FormatFallbackEntry ¶
FormatFallbackEntry renders one chain entry as model (via provider) with the base URL when set
func FormatModelForDisplay ¶
FormatModelForDisplay strips opaque proxy prefixes from a model id for status output only
func FormatPercentUsed ¶
FormatPercentUsed floors the used share to a whole percent, a sliver reading below one percent
func FormatPricePerMtok ¶
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 ¶
FormatResetWindow renders a ceilinged ~9h or ~45 min label for quota reopening copy
func FormatResetsIn ¶
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 ¶
FormatRuntimeProviderError renders a resolution failure as concise user facing guidance
func FormatSeconds ¶
FormatSeconds renders 58s, 2m 14s, or 1h 2m
func FormatSecretSourceSuffix ¶
FormatSecretSourceSuffix is the from X suffix naming the external source, empty for .env and shell keys
func FrozenRuntimeConfig ¶
FrozenRuntimeConfig is the frozen session config scoped on the context, nil outside a frozen scope
func GGUFReadSkippable ¶
Reports whether err is one callers treat as an unreadable model, a ValueError or an OS error
func GetAPIKeyProviderStatus ¶
GetAPIKeyProviderStatus is the status snapshot for an API key provider
func GetAnthropicKey ¶
First usable Anthropic credential over the registry env vars, the home dotenv beating a stale shell export
func GetAuthStatus ¶
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 ¶
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 ¶
GetCatalog returns the fetched or cached manifest, else the shipped one, serving a stale disk copy while refreshing off thread
func GetCodexAuthStatus ¶
GetCodexAuthStatus is the read only Codex status snapshot, pool first then the legacy provider state
func GetCodexModelIDs ¶
GetCodexModelIDs is live discovery with a token, else config default, local cache and defaults as a curated fallback
func GetConfiguredCodexBinary ¶
Configured model.codex_bin as one argv element, bare codex from PATH when unset
func GetContextLengthFromProviderError ¶
GetContextLengthFromProviderError returns a provider reported limit lower than the current window
func GetCurrentCodexRuntime ¶
Configured model.openai_runtime, auto when unset, empty or unrecognized
func GetCustomProviderPoolKey ¶
GetCustomProviderPoolKey is the preferred pool key for a custom provider, durable slug else custom name
func GetDefaultModelForProvider ¶
GetDefaultModelForProvider is the cost safe non interactive default for a configured provider without a model
func GetEnvPreferDotenv ¶
GetEnvPreferDotenv resolves a credential env var preferring the profile .env over the scope
func GetExternalProcessProviderStatus ¶
GetExternalProcessProviderStatus is the structural status of a provider that runs a local subprocess
func GetFallbackChain ¶
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 ¶
GetMinimaxOAuthAuthStatus is the MiniMax OAuth status snapshot
func GetNamedCustomProvider ¶
GetNamedCustomProvider is the named endpoint entry with credentials resolved, nil when none matches
func GetPoolStrategy ¶
GetPoolStrategy is the configured selection strategy for a provider
func GetPreferredSilentDefaultModel ¶
GetPreferredSilentDefaultModel is the cached manifest's labeled default else the shipped constant
func GetPrefillProgress ¶
Prompt tokens processed by the busiest processing slot for model, ok false when idle, unreachable or foreign
func GetProviderLabel ¶
GetProviderLabel returns the label override, else the models.dev or profile name, else the canonical id
func GetProviderRequestTimeout ¶
Configured provider request timeout in seconds from the home config
func GetProviderStaleTimeout ¶
Configured provider stale timeout in seconds from the home config
func GetQwenAuthStatus ¶
Qwen OAuth status of the status command, refresh validated so a stale CLI token never reads as logged in
func GetSecretStr ¶
GetSecretStr is GetSecret with a default, an unscoped read still panics
func GetXAIOAuthAuthStatus ¶
GetXAIOAuthAuthStatus is the xAI OAuth status snapshot, device code being the only xAI flow
func GrokSupportsReasoningEffort ¶
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 ¶
HasAWSCredentials reports whether any AWS credential source resolves for the process
func HasAccountUsage ¶
HasAccountUsage reports a provider that can report usage windows through a built in fetcher or a profile hook
func HasCodexContextVariant ¶
HasCodexContextVariant is the picker side alias of the eligibility check
func HasCompactionCheckpoint ¶
HasCompactionCheckpoint reports whether a reasoning sidecar carries a compaction checkpoint
func HasCuratedCatalog ¶
HasCuratedCatalog reports whether the curated table has a row for the provider
func HasKnownPricing ¶
HasKnownPricing reports whether any rate card covers the model route
func HasNamedCustomProvider ¶
Reports whether the home's config defines a providers or custom_providers entry for the name
func HasRateLimitHeaders ¶
HasRateLimitHeaders reports any x-ratelimit prefixed header
func HasUsableSecret ¶
True for a string secret of at least minLength characters that is no known placeholder
func HeaderKeys ¶
HeaderKeys are the keys of a header map in the order a Python dict of them iterates
func HomeRawConfig ¶
HomeRawConfig is the raw config.yaml of a home, empty when missing, unreadable or not a mapping
func HomeRawConfigForWrite ¶
HomeRawConfigForWrite is the raw config.yaml at a path for a write back, empty when missing, failing on malformed YAML
func HomeYAMLLayers ¶
HomeYAMLLayers is the config.yaml of a home as the gateway loader reads it, env references expanded and the managed overlay applied
func HookFailed ¶
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 ¶
Env keys a base URL host would receive, then its host derived vendor key
func HostInstallHint ¶
HostInstallHint names the install sentence for a left core host whose providers are all unregistered
func HostMatches ¶
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 ¶
Reports whether a model section can open straight at the named picker row or registered provider profile
func Hostname ¶
Hostname returns the lowercase host of a URL without port, userinfo, or trailing dot
func HydrateProfileSecretSources ¶
HydrateProfileSecretSources resolves one profile's sources into a private mapping without touching the process env
func IcebathOAuthFile ¶
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 ¶
ImageCostContext scopes a per image price over the returned context, nil restoring the flat default
func ImageDimensionsFromBytes ¶
ImageDimensionsFromBytes is the width and height read from PNG or JPEG headers, false when unreadable
func ImagesAllWithinManyImageLimit ¶
Whether every image payload fits the per image limit that applies once many images ride one request
func InstallBws ¶
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 ¶
InvalidateBedrockRuntimeClient evicts every read timeout slot of one region's runtime clients
func InvalidateCachedContextLength ¶
Exported invalidation for tests of other packages
func IronAllowlistedEnv ¶
IronAllowlistedEnv is the infrastructure only environment, never the operator's secrets
func IsActualRoute ¶
IsActualRoute identifies Actual Computer by provider alias or its hosted endpoint
func IsAggregatorModelProvider ¶
Whether a provider is one of the aggregators that want vendor prefixed model names
func IsAggregatorProvider ¶
IsAggregatorProvider reports membership in the catalog aggregator set including plugin admissions
func IsAnthropicFastModeModel ¶
IsAnthropicFastModeModel accepts vendor prefixed, dotted, variant and dated spellings
func IsAnthropicOAuthToken ¶
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 ¶
IsBorrowedCredentialSource reports whether a pool source is reference only and must never persist secrets
func IsCancelled ¶
IsCancelled is true for an interrupted prompt, a closed stdin, or a clean exit
func IsCapabilityRejection ¶
IsCapabilityRejection reports whether a structured output rejection speaks to the route capability rather than one schema
func IsClaudeCodeTokenValid ¶
IsClaudeCodeTokenValid is a non expired access token with a 60s buffer, a missing expiry means managed key
func IsCodex900kBase ¶
IsCodex900kBase is the single source of truth for 900k eligibility
func IsCodexContextVariant ¶
IsCodexContextVariant requires both the suffix and an eligible base
func IsCodexGPT54OrGPT55 ¶
True for the 272K capped gpt-5.4 to 5.6 and gpt-6 families on the Codex OAuth route
func IsCodexSpark ¶
True for gpt-5.3-codex-spark on the Codex OAuth route
func IsCustomRuntime ¶
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 ¶
IsEntitlementFailure detects subscription 401 or 403 bodies that a token refresh cannot fix
func IsEnvSettingKey ¶
IsEnvSettingKey reports whether a bare config key is stored in .env rather than config.yaml
func IsExpiring ¶
IsExpiring reports whether an ISO expiry is missing, unparseable or within skew of now
func IsExternalProcessProvider ¶
Provider runs as a local external process rather than an HTTP endpoint
func IsForeignProviderEndpoint ¶
IsForeignProviderEndpoint reports whether the base URL is another built in provider's canonical endpoint
func IsForkCacheScope ¶
IsForkCacheScope reports whether the scope carries a fork tag
func IsGeminiNativeProviderName ¶
IsGeminiNativeProviderName reports a provider name served by the native Gemini client
func IsGlobalEnv ¶
IsGlobalEnv is true for process deployment settings that are never profile secrets
func IsGrok46Family ¶
IsGrok46Family reports whether the id belongs to the Grok 4.6 family
func IsImportSourceName ¶
IsImportSourceName reports whether name is one of the importers
func IsKnownNonChatModel ¶
IsKnownNonChatModel is true when the name shape or an already parsed catalog item says not chat
func IsLiveFirstPickerProvider ¶
IsLiveFirstPickerProvider reports whether live entries lead the picker for the provider
func IsLlamaCppAlias ¶
IsLlamaCppAlias reports whether the name addresses the managed llama.cpp runtime
func IsLocalEndpoint ¶
IsLocalEndpoint is true for loopback, container DNS, unqualified, private, link local and Tailscale hosts
func IsLocalValidationError ¶
IsLocalValidationError reports a local bug rather than a provider, transport, or stream failure
func IsLoopbackHost ¶
IsLoopbackHost reports whether the host names the local machine
func IsManagedEndpoint ¶
True when the URL is the server the managed runtime state file points at
func IsManagedLocalEndpoint ¶
IsManagedLocalEndpoint reports whether a base URL targets the llama-server this install manages
func IsManagedProvider ¶
Whether provider and baseURL point at the managed server, custom only when baseURL is that endpoint
func IsMandatoryThinkingClaude ¶
Claude model that always thinks and rejects a thinking disable
func IsModelsDevPreferred ¶
IsModelsDevPreferred reports whether models.dev beats the curated list for the provider
func IsMultiplexActive ¶
IsMultiplexActive is true in a multiplexing process or for a task under multiplex semantics
func IsNativeAnthropicHost ¶
IsNativeAnthropicHost is true when the base URL is exactly api.anthropic.com or empty
func IsNativeCompactionRejection ¶
IsNativeCompactionRejection reports a structured 400 rejection of context_management
func IsNativeGeminiBaseURL ¶
IsNativeGeminiBaseURL reports whether a base URL is served by the native Gemini adapter
func IsNetworkError ¶
IsNetworkError is true for connection, DNS, and timeout failures from the transport
func IsNetworkResolutionFailure ¶
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 ¶
IsOAuthToken reports an OAuth or setup token shape rather than a Console API key
func IsOfficialOpenAIHost ¶
IsOfficialOpenAIHost reports whether the URL points at api.openai.com or a data residency subdomain
func IsOpencodeTarget ¶
IsOpencodeTarget reports whether the provider or base URL addresses the OpenCode relay
func IsOutputCapError ¶
IsOutputCapError reports a max_tokens cap rejection that is not an oversized input
func IsPresetFieldPath ¶
IsPresetFieldPath reports whether split config path parts name a preset field or an aggregator slot field
func IsProcessHome ¶
Reports whether a home is the process home, the exported face for pkg/mcp
func IsPromptInterrupt ¶
IsPromptInterrupt reports the KeyboardInterrupt or EOFError a picker prompt raised
func IsProviderEnabled ¶
IsProviderEnabled reports whether a providers block is enabled, with only an explicit false hiding it
func IsProviderExplicitlyConfigured ¶
IsProviderExplicitlyConfigured is true only when the user configured the provider through an explicit flow
func IsProviderStreamParseError ¶
IsProviderStreamParseError reports a wire level stream frame parse failure rather than local JSON validation
func IsProxyLoopbackHost ¶
IsProxyLoopbackHost is true for localhost or any loopback IP literal including the v4 mapped form
func IsRateLimitedAuthError ¶
IsRateLimitedAuthError reports an auth failure that is upstream rate limiting rather than a credential problem
func IsReasoningFieldRejection ¶
IsReasoningFieldRejection matches a 400 rejecting a reasoning wire control by name
func IsReasoningLevelRejection ¶
IsReasoningLevelRejection matches a 400 refusing the disabled level against a closed effort set
func IsReasoningRequiredRejection ¶
IsReasoningRequiredRejection matches a 400 saying reasoning cannot be switched off
func IsRefreshableOAuthProvider ¶
IsRefreshableOAuthProvider is the built in refreshable set or a plugin profile shipping refresh_credential
func IsRegisteredEnvName ¶
IsRegisteredEnvName reports whether icebath itself enumerates the variable name
func IsRepetitionDominated ¶
IsRepetitionDominated reports a contiguous run of exact repeats covering at least half the text
func IsRotationConsumedUncommitted ¶
IsRotationConsumedUncommitted is true when the secret belongs to a rotation that was spent but not committed
func IsRoutableProvider ¶
Whether a provider name currently resolves to a routable route under the context home config
func IsRoutingAggregator ¶
IsRoutingAggregator excludes flat namespace resellers whose catalog is first party
func IsRunawayRepetition ¶
IsRunawayRepetition requires domination plus mostly duplicate lines when the text has line structure
func IsSecretPayloadKey ¶
Exported payload key secret classification
func IsSensitiveHookKey ¶
IsSensitiveHookKey reports a credential bearing key such as api_key, authorization, or any _api_key suffix
func IsSetupHiddenEnv ¶
IsSetupHiddenEnv reports whether a variable is self configuring and stays out of setup forms
func IsSlotKeyedCacheRoute ¶
IsSlotKeyedCacheRoute reports whether the cache key pins one server side slot per conversation as xAI does
func IsStreamEventOrderError ¶
Whether a stream failed because an event arrived before message_start
func IsStreamStall ¶
Whether a failure is a stream that stopped producing output after it had started
func IsTerminalAnthropicRefreshError ¶
IsTerminalAnthropicRefreshError is true when retrying the same refresh token cannot succeed
func IsTerminalPluginRefreshError ¶
IsTerminalPluginRefreshError is a structured auth error asking for re-login or carrying a grant dead code
func IsTokenProvider ¶
IsTokenProvider reports a callable token minter rather than a string key
func IsTruthyValue ¶
Reports whether a config or env value spells a truthy flag the way is_truthy_value does
func IsValidEnvName ¶
IsValidEnvName is true for a legal environment variable name
func IsVertexExpressBaseURL ¶
Whether an aiplatform base URL speaks the native Gemini API with an API key
func IsZAICodingOverload ¶
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 ¶
KV bytes per f16 element factor, q8_0 with flash attention and f16 without
func KillProcessTree ¶
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 LabelFromToken ¶
LabelFromToken picks the email like claim of a JWT as the display label
func LadderReason ¶
func LadderReason(reason FailoverReason) bool
LadderReason reports a transient transport verdict the post exhaustion recovery ladder may wait out
func LadderStopHint ¶
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 ¶
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 ¶
Model block plus the endpoint definition it selects, copied as written, empty when the source has no model
func LaunchSecretScope ¶
Launch profile secret mapping, its env file and external sources winning over the launch env
func LaunchSecretScopeCtx ¶
Launch profile secret mapping with the task's multiplex semantics deciding frozen or live launch env
func LaunchTerminalEnv ¶
Frozen launch TERMINAL_ overlay for a launch profile turn's terminal scope
func LearnedImageTokenCost ¶
LearnedImageTokenCost is the learned per image price for model at the base URL host, else the flat default
func LeftCoreFailedRecently ¶
LeftCoreFailedRecently reports a last failure younger than an hour doubled per failure, capped at a week
func LeftCoreFailureStamp ¶
LeftCoreFailureStamp is the path of the stamp a failed automatic plugin install leaves in a home
func LeftCoreFirstCause ¶
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 ¶
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 ¶
ListCustomPoolProviders lists every custom prefixed pool key that holds rows in auth.json
func ListModelsDevModels ¶
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 ¶
LlamacppContext reads the runtime n_ctx from props else the router launch ctx size
func LoadConfigSafe ¶
LoadConfigSafe is the context's frozen runtime config else the home's read only config, nil on any error
func LoadDotenvFile ¶
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 ¶
Model metadata rows of the on disk cache keyed by model id
func LoadWindowOverrides ¶
Model id to granted window, empty on any read problem
func LocalModelsActivate ¶
LocalModelsActivate starts the job making a downloaded model the default for new chats with the server up
func LocalModelsCatalog ¶
LocalModelsCatalog prices every catalog entry for this machine with the recommended pick marked
func LocalModelsHardware ¶
LocalModelsHardware reports the machine budget as plain facts with live NVIDIA readings where present
func LocalModelsHumanGB ¶
LocalModelsHumanGB renders bytes as gibibytes with one decimal
func LocalModelsJobView ¶
LocalModelsJobView is the job view the terminal flow renders, a KeyError for an unknown id
func LocalModelsPauseJob ¶
LocalModelsPauseJob raises a job's pause switch, false when the job has none
func LocalModelsQuickstart ¶
LocalModelsQuickstart starts the one job installing the runtime, downloading this machine's build and making it the default
func LocalModelsRuntimeInstall ¶
LocalModelsRuntimeInstall starts the job installing the pinned engine, fetching missing drafts and restarting a stale server
func LocalModelsStatus ¶
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 ¶
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 ¶
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 ¶
LoginOpenAICodex runs the Codex login, device code by default and browser PKCE when opted in
func LoginXAIOAuth ¶
LoginXAIOAuth signs in to xAI Grok OAuth through the device code flow and makes it the provider
func LogoutCommand ¶
LogoutCommand clears the auth state of the named, active, or config selected provider
func LongDecodeStaleMultiplier ¶
Hop count that scales the non streaming stale budget of one api payload
func LongestDefaultContextMatch ¶
Context length of the longest default table key contained in the lowercase model name
func LooksLikeOpenRouterKey ¶
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 ¶
LowerHeaders flattens a header set to lowercase names with first values
func LowerKey ¶
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 ¶
Ground truth vision capability of a model staged with the managed runtime, nil when it is not ours
func MarkRotationConsumedUncommitted ¶
MarkRotationConsumedUncommitted records the pre rotation pair of a refresh whose replacement never committed
func MaskAPIKeyForLogs ¶
MaskAPIKeyForLogs hides a key to its head and tail and names a bearer callable instead of invoking it
func MaskedSecretPrompt ¶
Masked terminal prompt for a secret value, the exported form plugins reach through Services
func MatchesReasoningEchoFamily ¶
MatchesReasoningEchoFamily reports membership in one must echo family, a KeyError text for an unknown family
func MaterializeBearerForHTTP ¶
MaterializeBearerForHTTP mints one bearer from a token provider or returns a non empty string key
func MaxPartialThinkSuffix ¶
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 ¶
MergeHeaderMaps is the dict merge of header maps left to right, later values keeping earlier slots and new keys appended
func MergeInterimReasoningItems ¶
MergeInterimReasoningItems keeps prior checkpoints when a continuation carries none of its own
func MergeModelCooldowns ¶
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 ¶
MergeSnapshotAuthPreservingLiveSingleUseGrants restores a snapshot store without reviving spent single use OAuth generations
func MessageField ¶
MessageField reads a field from a dict shaped message or the matching attribute of a struct, nil when absent
func MessageFingerprint ¶
MessageFingerprint is a stable digest of one message over its provider visible persisted fields
func MigrateAllLeftCoreHomes ¶
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 ¶
MinSwitchResetFromConfig reads fallback.min_switch_reset_seconds, zero or unreadable means off
func MintProxyToken ¶
MintProxyToken is an opaque token with a recognizable prefix and a 128 bit random hex suffix
func MissingCredentialsSuffix ¶
A space led hint from the provider's profile for a missing credentials message, else empty
func MissingProviderCredentialsMessage ¶
MissingProviderCredentialsMessage is the remedy for an explicit provider with no credentials, from the registry
func ModelAliasCanonical ¶
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 ¶
What Windows charges to commit for a model estimated at modelBytes of device memory
func ModelConsumesThoughtSignature ¶
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 ¶
ModelDerivedAPIMode is the api mode re-derived from the final model, false when the endpoint fixes the wire
func ModelIDFromStem ¶
Model id from a GGUF file stem with any split part suffix removed
func ModelIDIsGeneration ¶
ModelIDIsGeneration reports whether the id names an image or video generation surface
func ModelSearchText ¶
ModelSearchText is the haystack for substring model search and never changes the wire id
func ModelSectionHasCredentials ¶
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 ¶
ModelSupportsFastMode reports whether the fast toggle is exposed for the model
func ModelSupportsUltrafast ¶
ModelSupportsUltrafast reports whether OpenAI publishes the ultrafast tier for the exact slug
func ModelsConfigIsAllowlist ¶
Reports whether a models config acts as an allowlist over discovered models
func ModelsDevIDFor ¶
The models.dev id for an exact icebath provider id
func ModelsDevProviderMap ¶
Icebath provider id to models.dev id, static map then profile declarations
func ModelsNormalizeProvider ¶
Is, aliases collapsed and an empty name meaning openrouter
func MovedCommandHint ¶
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 ¶
Resolved named endpoint entry with credentials, nil when no entry matches
func NamedCustomProviderEntry ¶
Named endpoint entry a provider name selects in cfg without reading credentials, nil when none matches
func NativeAnthropicAccountingProjection ¶
NativeAnthropicAccountingProjection returns the native Anthropic wire shadow of the messages and the replayed thinking texts
func NativeAnthropicPreservesPriorThinking ¶
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 ¶
NeedsReasoningEcho reports whether the route 400s on a tool call turn without reasoning_content
func NegotiateRequestTier ¶
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 ¶
NoProxyEntries splits a NO_PROXY value, reading both environment casings when nil is passed
func NoProxyEntryMatches ¶
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 ¶
NormalizeActualBaseURL gives hosted or loopback Actual roots their /v1 surface and the default when empty
func NormalizeAuxProvider ¶
Canonical auxiliary provider slug of a configured provider name
func NormalizeBaseURLForMatch ¶
Exported base URL match form, trimmed, lowercased and without trailing slashes
func NormalizeCustomProviderEntry ¶
NormalizeCustomProviderEntry returns the runtime shape of one providers or custom_providers block or nil
func NormalizeExtraHeaders ¶
NormalizeExtraHeaders renders a raw extra_headers mapping as string pairs in declaration order, dropping nil values
func NormalizeFinishReason ¶
NormalizeFinishReason folds a wire finish reason to the lowercase OpenAI value, passing non strings and empty through
func NormalizeGeminiBaseURL ¶
NormalizeGeminiBaseURL strips the OpenAI compatibility suffix and trailing slashes from a Gemini base URL
func NormalizeMainModelAssignment ¶
Main slot provider and model as persisted for the home in ctx
func NormalizeMoAConfig ¶
Normalized moa config block with presets, default preset and settings
func NormalizeModelForProvider ¶
NormalizeModelForProvider is NormalizeModelForProviderCtx for a caller holding no context
func NormalizeModelForProviderCtx ¶
NormalizeModelForProviderCtx rewrites a model name into the target provider's form, profile hooks reading the call's home
func NormalizeOpenCodeBaseURL ¶
NormalizeOpenCodeBaseURL heals the relay path and the /v1 tail for the wire protocol on opencode.ai hosts
func NormalizeOpenCodeModelID ¶
NormalizeOpenCodeModelID strips the family prefix from an OpenCode config model id
func NormalizeProvider ¶
NormalizeProvider lowercases a provider name and collapses every alias onto its canonical id
func NormalizeProviderDef ¶
NormalizeProviderDef resolves aliases and casing to the canonical models.dev keyed provider id
func NormalizeRouteBaseURL ¶
NormalizeRouteBaseURL canonicalizes only the URL components proven equivalent for route identity
func NoteCatalogItem ¶
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 ¶
OAuthAdmissionProblems adds catalog admission checks to the shape, declared variables and no core id clash
func OAuthAdmissionWarnings ¶
OAuthAdmissionWarnings flags hosts outside the IdP domains and plugin code naming a token URL
func OAuthNotice ¶
OAuthNotice is the install and show text for the declared clients, empty when none are declared
func OAuthReloginCommand ¶
OAuthReloginCommand is the exact re-login command for a rejected OAuth grant
func OAuthSurface ¶
OAuthSurface is one line per client for the re-pin consent delta
func OfferAgentImport ¶
OfferAgentImport offers to import the agents found on this computer and returns the labels whose import changed config.yaml or .env
func OfferedModelIDs ¶
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 OpenAIModelRejectsReasoning ¶
OpenAIModelRejectsReasoning is true for chat era ids that 400 on any reasoning field
func OpenAIReasoningFamily ¶
OpenAIReasoningFamily is the all_turns family a model belongs to, empty for every other model
func OpenBrowserTab ¶
Opens a URL in a new tab through the browser registry for callers outside the package
func OpenCodeFamily ¶
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 ¶
OpenRouterModelIDs returns just the OpenRouter model id strings
func OpenRouterVariantBase ¶
OpenRouterVariantBase returns the base id of a routing variant suffix or empty
func OpencodeFamilyForCustom ¶
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 ¶
List of request messages with every message that carries a recorded key order turned into its ordered dict
func OrderedHeaders ¶
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 ¶
OverrideContextWindow is the explicit model_overrides context window for the bound home
func OwnerSecretScope ¶
Secret mapping for a body owned by the home, the launch scope for this process's own home
func ParseAbsoluteTimestamp ¶
ParseAbsoluteTimestamp converts epoch seconds, epoch milliseconds or ISO 8601 text into epoch seconds
func ParseAvailableOutputTokensFromError ¶
ParseAvailableOutputTokensFromError extracts the output budget from a max_tokens too large error
func ParseCodexVersion ¶
Major, minor and patch of codex --version output, false when no version is present
func ParseContextLimitFromError ¶
ParseContextLimitFromError returns the context window a provider error quotes
func ParseExactServiceTier ¶
ParseExactServiceTier pins normal for an empty word and rejects an unknown word instead of reading it as normal
func ParseISOTimestamp ¶
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 ¶
Partial flag, keep count and focus topic from the text after compress, nil focus for the partial forms
func ParseReasoningEffort ¶
Reasoning effort config of a level, nil for empty or unrecognized input and enabled false for a disable spelling
func ParseRetryAfter ¶
ParseRetryAfter reads a numeric or HTTP date Retry-After value into a duration clamped at zero
func ParseServiceTier ¶
ParseServiceTier maps a user or config word to a stored tier, empty for normal and unknown words
func ParseTurnAuthor ¶
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 ¶
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 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 ¶
PlatformConfiguredOn reports a platform switched on, or holding a token without an enabled key, in the merged gateway config
func PlatformInstallHint ¶
PlatformInstallHint names the install command for an unknown platform that left core, else empty
func PlatformTLSConfig ¶
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 ¶
PluginHomeLabel names a home by its profile, else by its path
func PluginInstallCommand ¶
PluginInstallCommand is the exact command installing a plugin into a home, bare only for the sticky default
func PluginKey ¶
PluginKey is the plugin's path under the plugins root it lives in, the store key of its grants
func PluginLoadError ¶
PluginLoadError returns the import error a home plugin dir raised, empty when it loaded
func PluginOAuthKey ¶
Grant store key of a plugin directory, the key plugins remove forgets its sign ins under
func PluginPresent ¶
PluginPresent reports the plugin installed in the home, enabled or not
func PluginRefreshHookExists ¶
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 ¶
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 ¶
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 ¶
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 ¶
Runs the picker listing once per process in the background so the disk catalog cache is warm
func PricingCacheScope ¶
PricingCacheScope is the current endpoint identity a provider's pricing cache is keyed on, resolved locally
func PrimaryFailureWording ¶
PrimaryFailureWording returns the log phrase and user phrase of a primary provider failure that triggers the fallback chain
func PrimaryModelConfig ¶
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 ¶
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 ¶
ProfileCLISelector is the -p name selector pinning copy pasteable guidance to the active named profile
func ProfileConfigScope ¶
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 ¶
Key env names then the base URL env name of a profile, the order its env_vars tuple lists them
func ProfileModelAPIMode ¶
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 ¶
PromptCachingDisabledFromConfig reports whether the bound config turns prompt caching off
func PromptChecklist ¶
PromptChecklist asks for several items, returning sorted picked indices, cancel keeping the preselection
func PromptChoice ¶
PromptChoice asks for one of the choices with arrow keys, a cancel outside setup keeping the default
func PromptReadingHook ¶
Context whose work hears each stretch of prompt reading through the hook, nil uninstalling it
func PromptYesNo ¶
Yes or no answer, headless runs taking the default, inside setup and the TUI through the menu
func ProviderAllowsModelWhitespace ¶
ProviderAllowsModelWhitespace reports whether a spaced id is a real selection rather than a cloud catalog typo
func ProviderAuthKind ¶
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 ¶
ProviderGroupForSlug returns the group id a slug belongs to, empty when ungrouped
func ProviderHasCredentials ¶
ProviderHasCredentials reports whether a provider can be switched to without typing a key
func ProviderInstallHint ¶
ProviderInstallHint names the install, enable or update command for a provider a left core plugin supplies
func ProviderLabel ¶
ProviderLabel is the human friendly label for a provider id or alias
func ProviderLeftCore ¶
ProviderLeftCore reports a provider a plugin supplies that no registered profile serves now
func ProviderOwnsRoute ¶
ProviderOwnsRoute reports whether a base URL is the provider's own endpoint and whether that can be known
func ProviderResetDelay ¶
ProviderResetDelay converts a provider declared reset instant into a positive wait or reports none
func ProviderRetiredAliases ¶
ProviderRetiredAliases returns the retired ids a provider still auto detects
func ProviderRetryAfter ¶
ProviderRetryAfter returns the positive provider declared cooldown from header or retry_after body field
func ProviderSetupFailureLines ¶
ProviderSetupFailureLines are the lines to print when the setup wizard's provider step fails
func ProviderSource ¶
ProviderSource names where the current registration of a provider came from, empty when unregistered
func ProviderStateIn ¶
ProviderStateIn returns a shallow copy of one provider entry
func ProvidersDictToCustomProviders ¶
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 ¶
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 ¶
ReadClaudeCodeCredentials reads the borrowed login from Keychain and file, preferring the only valid one
func ReadEnvSetting ¶
ReadEnvSetting resolves .env first, then a stale top level config.yaml copy which is reported on stderr
func ReadFallbackChain ¶
ReadFallbackChain is the normalized chain merged with the legacy fallback_model, always fresh copies
func ReadIcebathOAuthCredentials ¶
Reads the icebath managed PKCE credentials of the home
func ReadStreamingErrorBody ¶
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 ¶
ReasoningEchoFamily names the first must echo family the route matches in table order, empty for none
func ReasoningStaleTimeoutFloor ¶
ReasoningStaleTimeoutFloor returns the stale detector floor for a known reasoning model slug
func RecordAuxUsage ¶
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 ¶
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 ¶
RecoverLeftCoreAtStartup makes one migration attempt per process per home, delivering or keeping every outcome
func RecoverLeftCoreForCommand ¶
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 ¶
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 ¶
RefreshBoundHome rescans the bound home's plugin dirs now and forgets its remembered misses
func RefreshCatalog ¶
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 ¶
RefreshCatalogs force refreshes the manifest and the OpenRouter live list
func RefreshInstalledSecretScope ¶
RefreshInstalledSecretScope replaces the bound mapping with a fresh build of the home's secrets
func RefreshReasoningCapsAsync ¶
RefreshReasoningCapsAsync forces a background refetch of a provider's capability catalog
func RegisterFactory ¶
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 ¶
RegisterTransport binds an api mode to the constructor of its transport, the seam a provider plugin dialect uses
func RegisteredAPIModes ¶
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 ¶
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 ¶
Registry ids paired with their inference base URL in registry order, hidden rows left out
func RegistryKeys ¶
Keys of the provider registry of the bound home in storage order, alias keys included
func RejectedReasoningFields ¶
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 ¶
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 ¶
ReloadSetupConfig replaces cfg in place with the config on disk, saving it back when save is set
func ReloginCommandHint ¶
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 ¶
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 ¶
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 ¶
RemoveEnvSetting removes the .env entry and any stale config.yaml copy and reports whether either existed
func RenameToolSearchBridgeForXAI ¶
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 ¶
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 ¶
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 ¶
Prompt sections carrying the forwarded tool schemas and the tool choice hint, empty when neither applies
func RepairToolCallArguments ¶
RepairToolCallArguments fixes truncated, trailing comma, or control character argument JSON, else returns {}
func RequiresAuthNotice ¶
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 ¶
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 ¶
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 ¶
ResolveAWSAuthEnvVar names the active AWS auth source of the process, empty when none
func ResolveAffinityKey ¶
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 ¶
ResolveAnthropicToken resolves an Anthropic token from env, pool and the borrowed Claude Code login in order
func ResolveAuthProvider ¶
Canonical provider id auth resolution picks for a requested provider name
func ResolveAuxTaskProvider ¶
Configured provider of a task with no explicit args, auto when nothing is configured
func ResolveBackend ¶
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 ¶
ResolveBedrockRuntimeRegion is the region every Bedrock endpoint of the home must use
func ResolveCacheHome ¶
ResolveCacheHome is the given home else the process home
func ResolveCodexCredentialAndBase ¶
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 ¶
ResolveEffectiveModel picks the session override, then the channel, then the global model
func ResolveEntryAPIKey ¶
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 ¶
Fallback entry key, inline api_key else key_env through the home's secret scope
func ResolveFastModeOverrides ¶
ResolveFastModeOverrides returns the fast or priority request overrides, nil when unsupported
func ResolveMoAPreset ¶
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 ¶
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 ¶
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 ¶
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 ¶
ResponseStopDetails returns the stop_details object a Messages reply carried, nil when it carried none
func ResponsesRouteIsCodexBackend ¶
Route is the ChatGPT codex backend by exact provider name or chatgpt.com codex path
func RestoreAuthActiveProvider ¶
RestoreAuthActiveProvider writes a snapshotted active_provider back, removing the key when it was absent
func RestoreModelCfg ¶
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 ¶
RetryAfterFrom parses a Retry-After header value in seconds or HTTP date form
func RetryAfterFromHeaders ¶
RetryAfterFromHeaders reads Retry-After from a header set trying both casings
func RootIcebathOAuthFile ¶
The global root PKCE file inside a named profile, empty in classic mode
func RotateRuntimeMainAPIKey ¶
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 RouteSupportedEfforts ¶
Reasoning efforts the route of a provider, model and API mode accepts
func RoutedCustomIdentity ¶
RoutedCustomIdentity names the configured entry a bare custom pick on a URL or model resolves to
func RoutedModelRejectsVisionToolMessages ¶
Whether the route or the aggregator targeted model's profile rejects image tool parts
func RouterLaunchCtx ¶
RouterLaunchCtx reads the ctx size flag from the router launch args of the model
func RoutesAtHosts ¶
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 ¶
RunCodexToolsMCPServer is the tools MCP server entry, 2 when it cannot start and 1 when it crashes
func RunIcebathOAuthLoginPure ¶
Runs the icebath native PKCE flow and returns the credential state
func RunOAuthSetupToken ¶
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 ¶
RunSetupSteps runs labelled sections with left arrow navigation between and inside them
func RunWithSetupNavigation ¶
RunWithSetupNavigation runs fn under a navigation scope, a cancel printing the message instead of unwinding
func RunWizardWithSetupNavigation ¶
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 ¶
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 ¶
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 ¶
SDKStatusClass is the openai SDK error class an HTTP status raises
func SameAuthStore ¶
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 ¶
SanitizeBorrowedCredentialPayload strips raw secret fields from borrowed pool rows and leaves owned rows unchanged
func SanitizeHookPayload ¶
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 ¶
SaveContextLength persists a discovered window under model at base url, source marks Bedrock provenance
func SaveEnvSetting ¶
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 ¶
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 SecretFingerprint ¶
SecretFingerprint is a SHA-256 prefix used as a cache key, never logged or displayed
func SecretHomeApplied ¶
Reports whether every external secret source of a home applied, the exported face for pkg/mcp
func SecretScopeBound ¶
True while a secret scope is bound to the context
func SecretSourceEnabled ¶
SecretSourceEnabled reads the enabled flag of a section
func SecretSourceFetchTimeout ¶
SecretSourceFetchTimeout is the wall clock budget enforced around a fetch
func SecretSourceLabel ¶
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 ¶
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 ¶
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 ¶
SecretSourceValues is the external secret value snapshot for a home
func SecretsCommand ¶
SecretsCommand runs icebath secrets from the parsed namespace, printing help when no integration was named
func SeedCatalogCacheFromCheckout ¶
SeedCatalogCacheFromCheckout overwrites the disk cache with the checkout's shipped manifest
func SelectProviderAndModel ¶
SelectProviderAndModel runs the provider picker, the provider's credential and model flow, and the effort step
func SelectedConfigBackendName ¶
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 ¶
Returns a copy of base without any variable whose uppercased name carries a credential marker
func ServesRoutedProfile ¶
ServesRoutedProfile is true when the task runs for a profile other than the process's own
func ServiceTierWord ¶
ServiceTierWord is the user facing word for a stored tier
func SessionAuxiliaryScope ¶
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 ¶
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 ¶
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 ¶
SetCodexQuotaProbe swaps the live quota probe and returns the function that puts the previous one back
func SetCodexRuntime ¶
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 ¶
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 ¶
SetdefaultDict is the section under key, created when absent, a SetupTypeError when the value is not a mapping
func SetupConsole ¶
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 ¶
SetupModelProvider runs the shared provider and model picker, then reloads and resaves the config it wrote
func SetupModuleInstalled ¶
SetupModuleInstalled reports whether the dependency environment finds a Python module, false when the probe fails
func SetupOutput ¶
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 ¶
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 ¶
SetupSystemExit is the exit code and message of a Python SystemExit leaving a setup flow, false for any other error
func SetupToolsEnv ¶
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 ¶
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 ¶
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 ¶
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 ¶
SignInFailureLines are the lines to print when a device code or browser sign in fails for a non timeout reason
func SkipDeepMerge ¶
SkipDeepMerge reports whether the missing config recursion must not descend into the named preset map
func SnapshotAuthActiveProvider ¶
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 ¶
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 ¶
SplitHostPort is the lowercased host and optional port of a URL, a bracketed v6, a host with port or a bare host
func SplitParts ¶
Every on disk part of the split path belongs to, first first, nil unless another part exists
func SplitResponsesToolID ¶
SplitResponsesToolID splits a stored tool id into the call id and the response item id
func SpotifyAuthStatus ¶
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 ¶
SpotifyLogin runs the loopback PKCE login, first time setup included, and stores the tokens under providers.spotify
func SpotifyLogout ¶
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 ¶
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 ¶
StaticCatalog returns a provider's built in curated row else the bound home's plugin static models
func StaticCatalogProviders ¶
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 ¶
True while token is the active writer, a zero token or a fenceless agent cannot prove supersession
func StringifyProviderMap ¶
StringifyProviderMap copies a providers mapping so every key is a string
func StripAnthropicCacheControl ¶
Removes cache control markers from the request messages
func StripAnthropicToolCacheControl ¶
Removes cache control markers from the tool schemas
func StripCodexContextVariantSuffix ¶
StripCodexContextVariantSuffix removes a valid 900k suffix, an ineligible alias is returned unchanged
func StripOpaqueReplayItems ¶
Opaque replay items with encrypted payloads removed, the shape the budget estimator charges
func StripOrphanThinkCloseTags ¶
Text with close tags lacking a matching open removed with their trailing whitespace
func StripProviderPrefix ¶
Model id with a known provider prefix such as openrouter or local removed
func StripRejectedThinking ¶
StripRejectedThinking drops rejected thinking blocks from one request copy, every block when rejected is nil
func StripThinkBlocks ¶
StripThinkBlocks removes reasoning blocks and stray tool call XML from assistant text
func StripUnverifiedReasoningItems ¶
StripUnverifiedReasoningItems drops replayed items without an exact issuer and model stamp, returning the count
func SuggestPrefixedModelID ¶
SuggestPrefixedModelID returns the unambiguous catalogue id for a bare model name or empty
func SummarizeAPIError ¶
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 ¶
SummarizeTimeoutError names the timeout phase and the setting to raise, false for other errors
func SummarizeUserMessageForLog ¶
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 ¶
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 ¶
Sets whether kept notices are served on stderr and returns the previous setting, for tests that restore it
func SwapResolveBedrockRegion ¶
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 ¶
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 ¶
TimeoutPhase reports connect or read for a timeout in the cause chain, empty for other errors
func TimeoutsSection ¶
TimeoutsSection reads the timeouts root section of the config, empty when absent or malformed
func ToOpenAIBaseURL ¶
ToOpenAIBaseURL is the OpenAI compatible sibling of a dual surface Anthropic URL
func TokenPairsByID ¶
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 ¶
Flattens OpenAI tools into name, description and parameters specs, skipping malformed entries and those outside a non nil allowlist
func TrackPoolConns ¶
TrackPoolConns tracks the transport's pool and seeds it with conns for tests that sweep a known socket
func TurnAuthorEnv ¶
Environment entry a dispatcher merges into a child env with the compact JSON author
func TurnAuthorFromEnv ¶
Author the dispatcher placed in the turn author variable of environ, nil environ reading the process environment
func URLPath ¶
URLPath returns the URL path lowercased without a trailing slash, empty for a bare host or a bad netloc
func UbLogitsBytes ¶
GPU logits buffer bytes of the microbatch posture launch flags choose, priced from the vocab
func UltrafastOffered ¶
UltrafastOffered reports whether ultrafast is offered on the route, the Codex plan gated by its own catalog
func UnavailableReason ¶
Why backend cannot run on target, empty when built upstream and pinned, empty target meaning this host
func UnlistedProviderNames ¶
UnlistedProviderNames returns registered profiles discovery surfaces must not offer, a failing gate hiding its profile
func UnquoteDotenvValue ¶
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 ¶
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 ¶
UserAgent builds the attribution header value sent to aggregators, the product and its base version
func UsesSilentCatalogDefault ¶
UsesSilentCatalogDefault reports whether a provider's silent default comes from the catalog label
func ValidateBaseURL ¶
ValidateBaseURL rejects an http or https custom endpoint URL whose port cannot be parsed
func ValidateCatalogManifest ¶
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 ¶
ValidatedOpenRouterProviderSort is the normalized provider.sort value, false when absent or invalid
func VertexGetConfig ¶
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 ¶
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 ¶
Child context publishing the declared routing affinity scope, an empty scope clears it
func WithAuxiliaryEventLoop ¶
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 ¶
Child context publishing the conversation lineage root id for sticky routing, an empty id clears it
func WithDeferredTokenMint ¶
WithDeferredTokenMint resolves routes without exchanging short lived OAuth tokens up front
func WithFrozenRuntimeConfig ¶
WithFrozenRuntimeConfig scopes resolution under the returned context to a session's frozen config over the defaults
func WithLaunchBody ¶
Marks a standalone launch profile body so a mid body fail closed flip resolves from the launch scope
func WithLaunchBodyScope ¶
WithLaunchBodyScope records the launch profile mapping a body entered before multiplexing started
func WithLaunchProfileRuntimeScope ¶
Binds the launch home override, launch secret scope and terminal policy over the frozen launch overlay
func WithLaunchProfileScopeIfMultiplexed ¶
Exported form of the launch profile scope binding for the gateway and serve hosts
func WithLeftCoreInstallsHeld ¶
WithLeftCoreInstallsHeld marks a context whose resolutions never attempt a left core migration
func WithMultiplexContext ¶
WithMultiplexContext runs the task under multiplex semantics regardless of the process flag
func WithPromptProgressKwargs ¶
Copy of chat completions kwargs asking llama server for prompt progress chunks through extra_body
func WithReasoningFloor ¶
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 ¶
WithSetupConsole makes c the console setup prompts read and print on, the returned func restores the previous one
func WithSetupOutput ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 (*APIError) Retryable ¶
Retryable reports whether the same route may be tried again after a backoff
func (*APIError) SetRetryAfterHeader ¶
Records the Retry-After header of the failed response beside the cooldown the retry loop reads
type APIKeySecretResolver ¶
APIKeySecretResolver is a provider owned credential resolution returning the runtime key and its source
type APIMode ¶
type APIMode string
Wire protocol a route speaks
func AzureFoundryModelMode ¶
AzureFoundryModelMode returns codex_responses for Responses only Azure deployments or empty
func DetectAPIModeForURL ¶
DetectAPIModeForURL is the api mode a base url implies by its path and host, empty when none
func DetermineModeCtx ¶
DetermineModeCtx is DetermineMode resolving the route and the provider table under ctx
func HostMandatedMode ¶
HostMandatedMode returns the wire protocol an endpoint requires or empty when any works
func OpenCodeModelMode ¶
OpenCodeModelMode picks the wire protocol an OpenCode Zen or Go model is served on
type AWSCredentialError ¶
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 ¶
Botocore parser error class of a malformed frame
func (*AWSEventStreamFrameError) Error ¶
func (e *AWSEventStreamFrameError) Error() string
type AWSReadTimeoutError ¶
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
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 ¶
AgentNotice is an out of band notice each driver renders its own way
type AliasMatch ¶
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 ¶
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 ¶
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 ¶
One downloadable file with its repo relative path, exact size, local name override and source repo
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
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) BaseURL ¶
func (c *AsyncBedrockAuxiliaryClient) BaseURL() string
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
type AuthEpisode ¶
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
type AuthExitError ¶
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
func AuthKindOf ¶
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 ¶
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 ¶
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 ¶
AuxCancelFunc adapts a plain function into a cancel source
func (AuxCancelFunc) CancelRequested ¶
func (f AuxCancelFunc) CancelRequested() (bool, error)
CancelRequested runs the function
type AuxChatStream ¶
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
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 ¶
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 ¶
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 {
NoProvider bool
}
AuxiliaryClientUnavailable reports that no auxiliary client could be built for the task
func (*AuxiliaryClientUnavailable) Error ¶
func (e *AuxiliaryClientUnavailable) Error() string
type AuxiliaryExplicitCancellation ¶
type AuxiliaryExplicitCancellation struct{}
AuxiliaryExplicitCancellation is the host hard cancel of one auxiliary attempt, never a transport failure
func (*AuxiliaryExplicitCancellation) Cause ¶
func (*AuxiliaryExplicitCancellation) Cause() string
Cause names the explicit host cancel so nothing re-queries a mutable host event after unwinding
func (*AuxiliaryExplicitCancellation) Error ¶
func (*AuxiliaryExplicitCancellation) Error() string
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 ¶
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 ¶
AzureDetector probes an Azure endpoint for its transport and model list
type BackendIdentity ¶
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 ¶
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 (e *BedrockOpenAINoCredentialsError) Error() string
func (*BedrockOpenAINoCredentialsError) Unwrap ¶
func (e *BedrockOpenAINoCredentialsError) Unwrap() error
type BedrockScopedCredentialError ¶
type BedrockScopedCredentialError struct{}
BedrockScopedCredentialError refuses a multiplexed profile that would borrow the launch identity
func (BedrockScopedCredentialError) Error ¶
func (BedrockScopedCredentialError) Error() string
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 ¶
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 ¶
func (s *BitwardenSource) Spec() SecretSourceSpec
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 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 (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 ¶
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 ¶
CachedModelsOptions tune one disk cached catalog read
type CanonicalProviderEntry ¶
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 ¶
func (u CanonicalUsage) Add(o CanonicalUsage) CanonicalUsage
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 ¶
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 ¶
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 ¶
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 ¶
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
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 NewGeminiNativeClient ¶
NewGeminiNativeClient is the native Gemini generateContent client of a route
type ClonedGrantStrip ¶
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 ¶
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 (e *CodexAppServerTransportError) Error() string
func (*CodexAppServerTransportError) PyTypeName ¶
func (e *CodexAppServerTransportError) PyTypeName() string
type CodexApprovalCallback ¶
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 ¶
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 ¶
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
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 ¶
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 ¶
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
type CompressionCheckpointUnavailable ¶
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 ¶
func (e *CompressionCheckpointUnavailable) Error() string
type CompressionFastLane ¶
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 ¶
ConfigBackendUnavailableError means the config backend cannot be reached with a source supplied credential
func (*ConfigBackendUnavailableError) Error ¶
func (e *ConfigBackendUnavailableError) Error() string
type ConfigBackendView ¶
ConfigBackendView is what the secret loader needs to know about the selected config backend
type ConfigPath ¶
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 ¶
Config path of the entry the active home runtime routes a provider through, reading no credential
type ConfigWriteRefusedError ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
func (*DeviceFlowCancelledError) Error() string
type DirectAlias ¶
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) 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 ¶
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 ¶
func EnsureEngine ¶
Installs the resolved backend's pinned engine through PM and returns the current engine, only deliberate jobs call it
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 ¶
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
type EntraIdentityConfig ¶
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 ¶
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 FailedStreamRequest ¶
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 ¶
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 ¶
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 ¶
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 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
type GrowthDecision ¶
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 ¶
Refusal carrying a status code and the detail the user sees
func (*HTTPException) Error ¶
func (e *HTTPException) Error() string
type HTTPStatusError ¶
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 ¶
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 ¶
HeaderCarrier exposes the response headers of a failed call for reset and welcome tier parsing
type HeaderEntry ¶
HeaderEntry is one default header, Fn computing the value on first read when set
type HookJSONCaps ¶
HookJSONCaps bounds the depth, string length, and sequence length of a sanitized payload
type HostedAnswer ¶
HostedAnswer is the reply of the host, Cancelled when the user backed out of the question
type HostedModelResult ¶
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 ¶
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 ¶
EnsureCACert generates or returns the 10 year CA cert and key through the host openssl
func (IronProxy) EnsureManagementToken ¶
EnsureManagementToken returns the management API bearer key, minting it on first call
func (IronProxy) FindIronProxy ¶
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 ¶
InstallIronProxy is the explicit setup or repair install
func (IronProxy) IronProxyVersion ¶
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 ¶
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 ¶
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
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 ¶
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 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 ¶
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 ¶
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 ¶
The llamacpp alias endpoint, APIKey empty for a detected 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 {
}
LocalRuntimeUnavailableError means the selected model is the managed local runtime and its server is not serving
func (*LocalRuntimeUnavailableError) Error ¶
func (e *LocalRuntimeUnavailableError) Error() string
func (*LocalRuntimeUnavailableError) ErrorCode ¶
func (e *LocalRuntimeUnavailableError) ErrorCode() string
ErrorCode names the readiness probe code for the managed server being down
type LocalValidationError ¶
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 ¶
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 ¶
func (s *ManagedLlmStream) Iter() *ManagedLlmStream
Iterator the stream is consumed through, the stream itself
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 MinimaxLoginArgs ¶
MinimaxLoginArgs are the MiniMax login flags
type MoAArgs ¶
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 ¶
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 ¶
ModelIDNormalizer is a provider profile hook that returns the native id for a model or empty for generic rules
type ModelIdentity ¶
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 ¶
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 ¶
ModelsDevFetchDeadlineError reports a download abandoned at the whole exchange cap
func (*ModelsDevFetchDeadlineError) Error ¶
func (e *ModelsDevFetchDeadlineError) Error() string
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 ¶
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 ¶
OAuthHealSummary reports one forked grant consolidation into the root store
type OAuthLoginExitError ¶
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 ¶
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 ¶
func (s *OnePasswordSource) Spec() SecretSourceSpec
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
type OpenerFactory ¶
type OpenerFactory func(redirect *SafeCredentialRedirectHandler) RequestOpener
OpenerFactory is the explicit test seam building the opener around the redirect handler
type Origin ¶
Origin is the normalized scheme, hostname and effective port of a URL, Port -1 when none applies
type PerModelAPIModeHook ¶
PerModelAPIModeHook answers the wire for one model with a key or no key, empty for the declared mode
type PhysicsRefusal ¶
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 ¶
GroupProviders folds an ordered slug list into picker rows, a group at its first member's position
type PickerSegment ¶
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 (e *PluginOAuthPermissionError) Error() string
func (*PluginOAuthPermissionError) Unwrap ¶
func (e *PluginOAuthPermissionError) Unwrap() error
type PluginOAuthResolver ¶
PluginOAuthResolver returns the auth headers and request URL for one origin checked request
type PluginOrigin ¶
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 ¶
EntryScopedPool is the rows the custom entry owns, the pool itself when it owns all, nil when none
func LoadPool ¶
LoadPool reads a provider's rows, seeds them from singletons env and config, and persists changes
func LoadRoutePool ¶
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 ¶
AcquireLease takes a soft lease on the given entry, else the least leased available one
func (*Pool) ActiveLeases ¶
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) Entries ¶
func (p *Pool) Entries() []PooledCredential
Entries is a snapshot of the rows
func (*Pool) EntryIDForAPIKey ¶
EntryIDForAPIKey is the stable id of the runtime credential in use, the current selection when it still supplies the hint
func (*Pool) HasAvailable ¶
HasAvailable reports at least one entry outside exhaustion cooldown for model
func (*Pool) HasCredentials ¶
HasCredentials reports whether any row exists
func (*Pool) LiftReopenedCooldowns ¶
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 ¶
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) 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 ¶
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 ¶
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) TokenBenchedForModel ¶
TokenBenchedForModel reports a model cooldown on the token
func (*Pool) TokenIsBlocked ¶
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 ¶
HomePoolEnv is the pool environment of home h for callers outside the package
type PoolPresenceSource ¶
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 ¶
func (e PooledCredential) Clone() PooledCredential
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 ¶
func (e PooledCredential) MarkOK() PooledCredential
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 ¶
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
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 ¶
CanonicalRegistryRows is the PROVIDER_REGISTRY values of the bound home for callers outside the package
func GetProviderProfile ¶
GetProviderProfile looks a provider profile up by name or alias in the bound home
func ListProviders ¶
ListProviders returns every registered profile once, the bound home's plugins shadowing process wide ones
func ProfileFor ¶
ProfileFor resolves a provider id or alias to its registry row, else to its registered profile
func ProfileForHost ¶
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 ¶
Profiles overriding the runtime credential refresh for the route
func RegisteredProfileForHost ¶
Registry owned profile claiming the url host, one identity per registration so per profile hook memos hold
func RegistryRow ¶
Registry row of the bound home stored under one key, nil when the key is absent
func (Profile) APIModeForModel ¶
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 ¶
BuildClientKwargsExtras returns client constructor extras, empty by default
func (Profile) BuildExtraBody ¶
BuildExtraBody returns provider specific extra_body fields, empty by default
func (Profile) ClientHeaders ¶
ClientHeaders returns client headers for the endpoint, nil for the default headers
func (Profile) CreateClient ¶
CreateClient returns a provider specific client, nil for the standard construction path
func (Profile) CredentialRefreshNotice ¶
CredentialRefreshNotice returns the status line after a refresh, empty for the generic wording
func (Profile) DefaultHeaders ¶
Resolved default headers, the lazy map winning over the plain one when set
func (Profile) DefaultReasoningConfig ¶
DefaultReasoningConfig returns the reasoning config applied when the user set none
func (Profile) DefaultVisionModel ¶
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 ¶
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 ¶
GetHostname returns the declared hostname, else the base url host, else empty
func (Profile) GetMaxTokens ¶
GetMaxTokens returns the output cap for a model, the profile default when not overridden
func (Profile) GetModelContextLength ¶
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 ¶
KeyEnvNames returns the API key env names without URL shaped entries
func (Profile) Listed ¶
Listed reports whether discovery surfaces may offer the provider, hidden ones once a pool row exists
func (Profile) LiveContextLength ¶
LiveContextLength returns the context window from the live credentialed catalog, zero for none
func (Profile) MaxTokensParam ¶
MaxTokensParam names the output cap field, empty for the transport default
func (Profile) MissingCredentialsHint ¶
MissingCredentialsHint returns the hook's answer for missing credential messages, nil for none
func (Profile) ModelAliasMap ¶
ModelAliasMap returns the provider native model alias table
func (Profile) NormalizeModelID ¶
NormalizeModelID returns the provider native id, empty for the generic normalization
func (Profile) PrepareMessages ¶
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 ¶
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 ¶
RemoveCredentialSource returns sources to suppress and hints, false for the generic removal
func (Profile) ReplayMessageCarriers ¶
ReplayMessageCarriers returns captured carriers to put back on a replayed assistant message
func (Profile) ReplaysFunctionThoughtSignature ¶
ReplaysFunctionThoughtSignature reports whether replayed tool calls keep function thought signatures
func (Profile) RequestHeaders ¶
RequestHeaders returns per request headers, empty by default
func (Profile) RequestRejectionHint ¶
RequestRejectionHint returns lines explaining an endpoint's hard rejection of any route
func (Profile) ResolveAPIKeySecret ¶
ResolveAPIKeySecret returns the provider owned runtime key and source, false for the generic ladder
func (Profile) ResolveAuxModel ¶
ResolveAuxModel returns the cheap auxiliary model, empty for the generic choice
func (Profile) ResponsesIssuerKind ¶
ResponsesIssuerKind is the persisted stamp for encrypted reasoning minted here, empty means URL derived
func (Profile) ResponsesNativeCompaction ¶
ResponsesNativeCompaction is false when context_management must never be sent
func (Profile) ResponsesProfileReasoning ¶
ResponsesProfileReasoning is true when reasoning comes from the profile payload plus summary without include
func (Profile) ResponsesPromptCacheKey ¶
ResponsesPromptCacheKey reports whether the Responses body carries prompt_cache_key
func (Profile) ResponsesReplayItemIDs ¶
ResponsesReplayItemIDs reports whether replayed Responses message items keep their id
func (Profile) ResponsesTrustsCompletedStatus ¶
ResponsesTrustsCompletedStatus is false when a reasoning only completed response continues
func (Profile) RuntimeBaseURL ¶
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 ¶
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 ¶
Fixed temperature of the profile, omit true for the server managed sentinel
type ProfileContextLengthHook ¶
ProfileContextLengthHook is a profile qualified context bound, zero declines
type ProfileLayer ¶
one layer's kind and f16 KV bytes per token
type ProfileLiveContextLengthHook ¶
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
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 ¶
ProviderCredentialsExhaustedError reports an explicit provider whose credential pool is fully exhausted
func (*ProviderCredentialsExhaustedError) Error ¶
func (e *ProviderCredentialsExhaustedError) Error() string
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 ¶
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 ¶
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 ¶
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 ¶
func (e *ProviderNotConfiguredError) Error() string
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 (e *ProviderRequestPermissionError) Error() string
func (*ProviderRequestPermissionError) Unwrap ¶
func (e *ProviderRequestPermissionError) Unwrap() error
type ProviderResponse ¶
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
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 ¶
ProviderWriteHook observes every provider state replacement so guest handoff records can be kept
type QuantVariant ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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
type RouteEntryClient ¶
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 ¶
Router models in listing order with their status values
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 ¶
Credential as the runtime dict holds it, the callable token source when no static key was resolved
type RuntimeBaseURLResolver ¶
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) 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 ¶
func (r *SecretFetchResult) Fail(err string, kind SecretErrorKind) *SecretFetchResult
Fail records the error and kind and returns the result
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
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 ¶
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
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 ¶
SignInCancelledError is an interactive login the user interrupted or ended at EOF
func (*SignInCancelledError) Error ¶
func (e *SignInCancelledError) Error() string
type SignInCopyError ¶
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 ¶
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 ¶
Store persists auth.json for one icebath home with the global root as read only fallback
func (*Store) ActiveProvider ¶
ActiveProvider returns the active provider id from the store
func (*Store) ActiveProviderIs ¶
ActiveProviderIs reports whether the active provider equals the normalized id
func (*Store) ClearProviderAuth ¶
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 ¶
DeactivateProvider clears active_provider without deleting credentials
func (*Store) GetProviderAuthState ¶
GetProviderAuthState returns persisted provider state profile first then global root
func (*Store) GlobalPath ¶
GlobalPath is the global root auth.json or empty when the store is the global root itself
func (*Store) IsSourceSuppressed ¶
IsSourceSuppressed reports whether the user suppressed a credential source
func (*Store) LoadFile ¶
LoadFile parses one auth.json, quarantining corrupt content and failing on unreadable files
func (*Store) LoadGlobal ¶
LoadGlobal returns the global root store as a memoised read only fallback or an empty map
func (*Store) LockPath ¶
LockPath takes the cross process lock of an explicit auth path like _auth_store_lock with target_path
func (*Store) MarkProviderActiveIfUnset ¶
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) 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 ¶
ProviderState returns provider state with the global root fallback
func (*Store) ProviderStateWithSource ¶
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 ¶
ReadCredentialPool returns one provider's pool rows with the global root as fallback when the profile has none
func (*Store) ReadCredentialPools ¶
ReadCredentialPools returns every provider's rows with per provider global fallback
func (*Store) SaveActiveProviderState ¶
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 ¶
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 ¶
SuppressCredentialSource records that a credential source must not be reseeded
func (*Store) SuppressedCredentialSources ¶
SuppressedCredentialSources returns every suppressed source for a provider
func (*Store) UnsuppressCredentialSource ¶
UnsuppressCredentialSource clears a suppression marker and reports whether one existed
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
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 ¶
StreamLifetimeExceededError is a stream attempt cut by the agent.stream_max_lifetime cap
func (*StreamLifetimeExceededError) Error ¶
func (e *StreamLifetimeExceededError) Error() string
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 ¶
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 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
type TimeoutPhaseError ¶
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 ¶
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 ¶
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 ¶
func (e *UnsupportedProviderRequestError) Error() string
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 ¶
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
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
XAILoginArgs are the xAI login flags
Source Files
¶
- account_usage.go
- account_usage_cache.go
- account_usage_json.go
- acp_client_prompt.go
- acp_model_catalog_export.go
- acp_openai_bridge.go
- agent_hooks.go
- agent_import.go
- agent_notice.go
- anthropic.go
- anthropic_cache.go
- anthropic_convert.go
- anthropic_credentials.go
- anthropic_endpoints.go
- anthropic_plain_data.go
- anthropic_stream.go
- anthropic_thinking.go
- anthropic_wire_order.go
- auth_codex.go
- auth_codex_browser.go
- auth_commands.go
- auth_commands_interactive.go
- auth_commands_manage.go
- auth_constants.go
- auth_device_flow.go
- auth_error_copy.go
- auth_external_process.go
- auth_flows.go
- auth_loopback_unix.go
- auth_minimax.go
- auth_model_picker.go
- auth_oauth_grants.go
- auth_oauth_pkce_plugin.go
- auth_openrouter.go
- auth_plugin_providers.go
- auth_plugin_registry.go
- auth_qwen.go
- auth_registry_view.go
- auth_store_source_labels.go
- auth_xai.go
- auth_zai_kimi.go
- auxiliary_accounting.go
- auxiliary_accounting_state.go
- auxiliary_async_rebuild.go
- auxiliary_call_outcome.go
- auxiliary_client_anthropic_adapter.go
- auxiliary_client_anthropic_images.go
- auxiliary_client_anthropic_sdk.go
- auxiliary_client_cache.go
- auxiliary_client_call.go
- auxiliary_client_classify.go
- auxiliary_client_codex_adapter.go
- auxiliary_client_codex_guard.go
- auxiliary_client_credentials.go
- auxiliary_client_custom.go
- auxiliary_client_factory.go
- auxiliary_client_fallback.go
- auxiliary_client_gemini.go
- auxiliary_client_headers.go
- auxiliary_client_hosts.go
- auxiliary_client_interrupt.go
- auxiliary_client_main.go
- auxiliary_client_max_tokens.go
- auxiliary_client_message.go
- auxiliary_client_normalize.go
- auxiliary_client_openai.go
- auxiliary_client_policy.go
- auxiliary_client_pool.go
- auxiliary_client_progress.go
- auxiliary_client_provider_adapter.go
- auxiliary_client_recovery.go
- auxiliary_client_registry.go
- auxiliary_client_relay.go
- auxiliary_client_resolve.go
- auxiliary_client_route.go
- auxiliary_client_runtime_main.go
- auxiliary_client_sdk.go
- auxiliary_client_stream.go
- auxiliary_client_task.go
- auxiliary_client_timeout.go
- auxiliary_client_unhealthy.go
- auxiliary_client_vision.go
- auxiliary_codex_response.go
- auxiliary_error_shapes.go
- auxiliary_fallback_recovery.go
- auxiliary_health.go
- auxiliary_hooks.go
- auxiliary_key_rotation.go
- auxiliary_local_runtime.go
- auxiliary_managed_local.go
- auxiliary_plugin_oauth.go
- auxiliary_rate_limit_backoff.go
- auxiliary_reasoning_floor.go
- auxiliary_stream_watchdog.go
- auxiliary_structured_output.go
- auxiliary_task_config.go
- auxiliary_unavailable.go
- auxiliary_wire.go
- aws_client.go
- aws_credentials.go
- aws_eventstream.go
- aws_tty_linux.go
- aws_tty_unix.go
- azure.go
- azure_identity.go
- azure_identity_broker.go
- azure_msal.go
- bedrock.go
- bedrock_converse.go
- bedrock_converse_convert.go
- bedrock_converse_stream.go
- bedrock_converse_wire.go
- bedrock_transport.go
- billing_links.go
- bounded_response.go
- cache_bounds.go
- catalog_list.go
- catalog_static.go
- chain.go
- chat_catalog.go
- chat_completion_agent.go
- chat_completion_direct.go
- chat_completion_direct_call.go
- chat_completion_fallback_mode.go
- chat_completion_local.go
- chat_completion_nonstream.go
- chat_completion_nonstream_agent.go
- chat_completion_relay_stream.go
- chat_completion_stream_agent.go
- chat_completion_stream_diag.go
- chat_completion_stream_monitor.go
- chat_completion_streaming_anthropic.go
- chat_completion_streaming_call.go
- chat_completion_streaming_errors.go
- chat_completion_streaming_monitor.go
- chat_completion_summary.go
- chat_completion_wait_notice.go
- chat_completions.go
- chat_completions_convert.go
- chat_completions_stream.go
- chat_completions_stream_guards.go
- chat_completions_tool_args.go
- chat_completions_transport.go
- chat_wire_order.go
- classify.go
- codex_app_server.go
- codex_app_server_session.go
- codex_app_server_unix.go
- codex_convert.go
- codex_event_projector.go
- codex_headers.go
- codex_models.go
- codex_request.go
- codex_responses.go
- codex_runtime.go
- codex_runtime_command.go
- codex_runtime_history_seed.go
- codex_runtime_items.go
- codex_runtime_plugin_migration.go
- codex_runtime_switch.go
- codex_runtime_turn.go
- codex_service_tiers.go
- codex_stream.go
- codex_stream_run.go
- codex_tools_mcp_server.go
- compression_checkpoint.go
- config_bridge.go
- config_facade_bridge.go
- config_language_bridge.go
- config_multiplex_hook.go
- config_mutation.go
- config_providers.go
- cooldown.go
- copilot_acp.go
- copilot_activation.go
- copilot_catalog.go
- copilot_credentials.go
- copilot_setup.go
- credential_lifecycle.go
- credential_persistence.go
- credential_recovery.go
- credential_source.go
- cron_default_provider.go
- custom.go
- custom_entry_pool.go
- custom_identity.go
- deadline.go
- deadline_tree.go
- do.go
- dotenv_parse.go
- dotenv_values.go
- egress_cli.go
- env_credentials.go
- env_loader.go
- fallback_check.go
- fallback_command.go
- fallback_routes.go
- fast_mode.go
- fast_mode_overrides.go
- file_lock.go
- gateway_hooks.go
- gcp_auth.go
- gcp_auth_export.go
- gemini.go
- gemini_convert.go
- gemini_long_decode.go
- gemini_schema.go
- gemini_stream.go
- git_credentials.go
- header_capture.go
- home_credentials.go
- hooks.go
- image_token_cost.go
- inventory.go
- inventory_capabilities_export.go
- inventory_exports.go
- iron_proxy.go
- iron_proxy_unix.go
- launch_profile_policy.go
- launch_profile_policy_export.go
- left_core_hint.go
- left_core_install_state_export.go
- left_core_migration.go
- left_core_support.go
- local_models.go
- local_prompt_progress.go
- local_runtime_binaries.go
- local_runtime_bootstrap.go
- local_runtime_capabilities.go
- local_runtime_catalog.go
- local_runtime_context_policy.go
- local_runtime_detect.go
- local_runtime_devices.go
- local_runtime_endpoint.go
- local_runtime_estimator.go
- local_runtime_gguf.go
- local_runtime_growth.go
- local_runtime_hardware.go
- local_runtime_hardware_other.go
- local_runtime_hf_browse.go
- local_runtime_load_progress.go
- local_runtime_native_cstring.go
- local_runtime_native_dl.go
- local_runtime_presets.go
- local_runtime_processes.go
- local_runtime_processes_posix.go
- local_runtime_psproc.go
- local_runtime_psproc_linux.go
- local_runtime_psproc_posix.go
- local_runtime_recovery.go
- local_runtime_supervisor.go
- local_runtime_supervisor_posix.go
- local_runtime_supervisor_reap.go
- log.go
- main_provider_setup.go
- main_provider_setup_tasks.go
- mcp_tool_server.go
- metadata.go
- metadata_cache.go
- metadata_codex.go
- metadata_errors.go
- metadata_memo.go
- metadata_probe.go
- metadata_resolve.go
- migrate_command.go
- moa_cmd.go
- moa_config.go
- model_assignment.go
- model_command.go
- model_guards.go
- model_normalize.go
- model_normalize_export.go
- model_search.go
- model_setup_flows.go
- model_setup_flows_azure.go
- model_setup_flows_bedrock.go
- model_setup_flows_common.go
- model_setup_flows_custom.go
- model_setup_flows_local.go
- model_switch.go
- model_switch_alias.go
- model_switch_apply.go
- model_switch_parse.go
- model_switch_providers.go
- model_switch_route.go
- models.go
- models_cache_lock.go
- models_detect.go
- models_dev.go
- models_fetch.go
- models_fileid_unix.go
- models_local.go
- models_profile_cache.go
- models_seams.go
- models_validate.go
- onepassword_secrets_cli.go
- opencode_affinity.go
- partial_compress.go
- plan_prompt.go
- plugin_actual.go
- plugin_ai_gateway.go
- plugin_alibaba.go
- plugin_alibaba_coding.go
- plugin_anthropic.go
- plugin_commandcode.go
- plugin_copilot.go
- plugin_custom.go
- plugin_deepinfra.go
- plugin_entry_bridge.go
- plugin_fireworks.go
- plugin_gemini.go
- plugin_gmi_novita.go
- plugin_hosted_profiles.go
- plugin_kimi.go
- plugin_lmstudio.go
- plugin_meta_ai.go
- plugin_minimax.go
- plugin_nebius.go
- plugin_nvidia.go
- plugin_oauth.go
- plugin_oauth_unattended.go
- plugin_ollama_cloud.go
- plugin_opencode.go
- plugin_openrouter.go
- plugin_provider_requests.go
- plugin_qwen.go
- plugin_router.go
- plugin_small_rows.go
- plugin_tokenhub.go
- plugin_upstage.go
- plugin_vertex.go
- plugin_zai.go
- plugins_bundled.go
- pm_bridge.go
- pool.go
- pool_admin.go
- pool_entry.go
- pool_key_source.go
- pool_persist.go
- pool_plugin.go
- pool_select.go
- pool_timestamps.go
- pricing.go
- process_bootstrap.go
- profile_base.go
- profile_distribution.go
- profile_model_assign.go
- profile_model_seed.go
- profile_secret_source.go
- profiles.go
- profiles_active.go
- profiles_plugins.go
- profiles_table.go
- prompt_cache_scope.go
- provider_base.go
- provider_cliui_bridge.go
- provider_registry.go
- provider_route_hooks.go
- provider_route_hooks_registry.go
- provider_timeouts.go
- providers.go
- proxy_adapter_xai.go
- proxy_adapters.go
- proxy_bypass.go
- proxy_cli.go
- proxy_server.go
- proxy_sse_done.go
- py_text.go
- py_url.go
- qwen_auth_status_export.go
- ratelimit.go
- reasoning_caps.go
- reasoning_carriers.go
- reasoning_replay.go
- registry.go
- relay_llm.go
- relay_turn_identity.go
- resolve.go
- resolve_auto.go
- resolve_azure.go
- resolve_bridge.go
- resolve_local.go
- retry.go
- route_identity.go
- routing_scope.go
- runtime_fallback_export.go
- runtime_provider_backends.go
- runtime_readiness_export.go
- sdk_transform_bypass.go
- sdk_wire_headers.go
- secret_prompt.go
- secret_scope.go
- secret_source_attribution_export.go
- secret_source_bitwarden.go
- secret_source_command.go
- secret_source_command_unix.go
- secret_source_loader.go
- secret_source_onepassword.go
- secret_source_onepassword_exports.go
- secret_source_plugins.go
- secret_sources.go
- secrets_cli.go
- secrets_common.go
- session_info_exports.go
- session_source.go
- setup_banner.go
- setup_host.go
- setup_host_additions.go
- setup_host_aws.go
- setup_host_plugins.go
- setup_navigation.go
- setup_prompts.go
- setup_qwen_device.go
- setup_reasoning_effort.go
- setup_sections.go
- setup_tts_xai.go
- setup_tui_flows.go
- setup_tui_model.go
- shell_command_unix.go
- sigv4.go
- skills_prefix_bridge.go
- slash_commands_login_export.go
- spotify_auth.go
- sse.go
- ssl_verify.go
- store.go
- store_credential.go
- store_lock_unix.go
- stream_consumer_think_export.go
- stream_diag.go
- stream_single_writer.go
- subcommands_secrets.go
- tokens.go
- tool_features.go
- tools_config_bridge.go
- transport.go
- tui_server_export.go
- turn_author.go
- turn_author_relay.go
- types.go
- urllib_security.go
- usage_anchor.go
- usage_bars.go
- usage_command.go
- vertex.go
- vision_capabilities.go
- xai_credential_pool_source.go
- xai_oauth_section_login.go
- xai_retirement.go