Documentation
¶
Index ¶
- Constants
- Variables
- func BuildClaudeSettings(base []byte, env map[string]string, opts ...ApplyOption) ([]byte, error)
- func BuildContextWindowsFromRules(cfg *Config) map[string]int
- func BuiltinDir(configDir string) string
- func BuiltinRuleUUID(scenario typ.RuleScenario, model string) string
- func CacheDir(configDir string) string
- func ConfigPath(configDir string) string
- func CustomDir(configDir string) string
- func DBDir(configDir string) string
- func DBPath(configDir string) string
- func Dir(configDir string) string
- func EnsurePath(configDir string) (string, error)
- func EnterpriseContextKeyPaths(configDir string) (string, string)
- func FindConfig(configDir string) (string, error)
- func GenerateEnterpriseContextPEMs() (privatePEM, publicPEM []byte, err error)
- func GenerateModelToken() (string, error)
- func GenerateSecureToken(prefix string) (string, error)
- func GenerateUUID() string
- func GenerateUserToken() (string, error)
- func HistoryPath(configDir string) string
- func ImHookEntries() map[string]interface{}
- func InstallIMHookScript() (scriptPath string, created bool, err error)
- func InstallNotifyScript() (scriptPath string, created bool, err error)
- func InstallStatusLineScript() (scriptPath string, created bool, err error)
- func IsDefaultToken(token string) bool
- func IsTacticValid(tactic *typ.Tactic) bool
- func IsWildcardRuleName(name string) bool
- func MarshalConfig(cfg guardrailscore.Config) ([]byte, error)
- func Migrate(c *Config) error
- func NotifyHookEntries() map[string]interface{}
- func RegistryCachePath(configDir string) string
- func RemoteDir(configDir string) string
- func RenderCodexConfigTOML(baseURL string, models []string, prefs *CodexPrefs, writeCatalog bool, ...) ([]byte, error)
- func RenderCodexModelCatalog(models []string, contextWindows map[string]int) ([]byte, error)
- func RenderDshCredentialsYAML(apiKey string) ([]byte, error)
- func RenderDshSettingsYAML(baseURL string, models []string, prefs *DshPrefs) ([]byte, error)
- func SmartGuideRuleUUID(botUUID string) string
- func SortProviderModels(provider *typ.Provider, models []string)
- func TrimContext1M(model string) string
- func WriteEnterpriseContextKeys(privatePath, publicPath string, privatePEM, publicPEM []byte) error
- func WriteFileAtomic(path string, data []byte) error
- type ApplyOption
- type ApplyResult
- func ApplyClaudeOnboarding(payload map[string]interface{}) (*ApplyResult, error)
- func ApplyClaudeSettingsFromEnv(env map[string]string, opts ...ApplyOption) (*ApplyResult, error)
- func ApplyClaudeSettingsToPath(targetPath string, env map[string]string, opts ...ApplyOption) (*ApplyResult, error)
- func ApplyCodexAuth(mode CodexAuthMode, apiKey string, tokens *CodexChatGPTTokens) (*ApplyResult, error)
- func ApplyCodexConfig(baseURL string, models []string, prefs *CodexPrefs, writeCatalog bool) (*ApplyResult, error)
- func ApplyCodexConfigWithContextWindows(baseURL string, models []string, prefs *CodexPrefs, writeCatalog bool, ...) (*ApplyResult, error)
- func ApplyDshCredentials(apiKey string) (*ApplyResult, error)
- func ApplyDshSettings(baseURL string, models []string, prefs *DshPrefs) (*ApplyResult, error)
- func ApplyImHooks() (*ApplyResult, error)
- func ApplyNotifyHooks() (*ApplyResult, error)
- func ApplyOpenCodeConfig(payload map[string]interface{}) (*ApplyResult, error)
- func ClearCodexGatewayConfig() (*ApplyResult, error)
- type BackupInfo
- type ClaudeSettingsPayload
- type CodexAuthMode
- type CodexChatGPTTokens
- type CodexPrefs
- type Config
- func (c *Config) AddOrUpdateRequestConfigByRequestModel(reqConfig typ.Rule) error
- func (c *Config) AddProvider(provider *typ.Provider) error
- func (c *Config) AddProviderByName(name, apiBase, token string) error
- func (c *Config) AddRequestConfig(reqConfig typ.Rule) error
- func (c *Config) AddRule(rule typ.Rule) error
- func (c *Config) ApplyHTTPTransportConfig()
- func (c *Config) CloseStores() error
- func (c *Config) CreateDefaultConfig() error
- func (c *Config) CreateProfile(baseScenario typ.RuleScenario, name string, unified bool) (typ.ProfileMeta, error)
- func (c *Config) CredentialStore() (*guardrailsutils.ProtectedCredentialStore, error)
- func (c *Config) DeleteProfile(baseScenario typ.RuleScenario, profileID string) error
- func (c *Config) DeleteProvider(uuid string) error
- func (c *Config) DeleteRule(ruleUUID string) error
- func (c *Config) EnsureSmartGuideRuleForBot(botUUID, botName, providerUUID, modelID string) error
- func (c *Config) FetchAndSaveProviderModels(uid string) error
- func (c *Config) GetAPITokenAlgorithm() string
- func (c *Config) GetAPITokenIssuer() string
- func (c *Config) GetAPITokenSecret() string
- func (c *Config) GetDebug() bool
- func (c *Config) GetDefaultMaxTokens() int
- func (c *Config) GetDefaultRequestConfig() *typ.Rule
- func (c *Config) GetDefaultRequestID() int
- func (c *Config) GetDefaults() (requestModel, responseModel string)
- func (c *Config) GetEffectiveAffinity(rule *typ.Rule) time.Duration
- func (c *Config) GetGUIDebug() bool
- func (c *Config) GetGUIPort() int
- func (c *Config) GetGUIVerbose() bool
- func (c *Config) GetInternalAPIToken() string
- func (c *Config) GetJWTSecret() string
- func (c *Config) GetMCPRuntimeConfig() *typ.MCPRuntimeConfig
- func (c *Config) GetModelManager() *data.ModelListManager
- func (c *Config) GetModelToken() string
- func (c *Config) GetOpenBrowser() bool
- func (c *Config) GetProfile(baseScenario typ.RuleScenario, profileID string) (typ.ProfileMeta, bool)
- func (c *Config) GetProfiles(baseScenario typ.RuleScenario) []typ.ProfileMeta
- func (c *Config) GetProviderByName(name string) (*typ.Provider, error)
- func (c *Config) GetProviderByUUID(uuid string) (*typ.Provider, error)
- func (c *Config) GetProviderStore() *db.ProviderStore
- func (c *Config) GetRequestConfigs() []typ.Rule
- func (c *Config) GetRequestModel() string
- func (c *Config) GetResponseModel() string
- func (c *Config) GetRuleByRequestModelAndScenario(requestModel string, scenario typ.RuleScenario) *typ.Rule
- func (c *Config) GetRuleByUUID(UUID string) *typ.Rule
- func (c *Config) GetScenarioConfig(scenario typ.RuleScenario) *typ.ScenarioConfig
- func (c *Config) GetScenarioExtensionBool(scenario typ.RuleScenario, key string) bool
- func (c *Config) GetScenarioExtensionString(scenario typ.RuleScenario, key string) string
- func (c *Config) GetScenarioFlag(scenario typ.RuleScenario, flagName string) bool
- func (c *Config) GetScenarioIntFlag(scenario typ.RuleScenario, flagName string) int
- func (c *Config) GetScenarioRecordingMode(scenario typ.RuleScenario) typ.RecordingMode
- func (c *Config) GetScenarioStringFlag(scenario typ.RuleScenario, flagName string) string
- func (c *Config) GetScenarios() []typ.ScenarioConfig
- func (c *Config) GetServerHost() string
- func (c *Config) GetServerPort() int
- func (c *Config) GetSmartGuideRuleForBot(botUUID string) *typ.Rule
- func (c *Config) GetTemplateManager() *data.TemplateManager
- func (c *Config) GetToken() string
- func (c *Config) GetToolConfig(toolType string, target interface{}) bool
- func (c *Config) GetUUIDByRequestModel(requestModel string) string
- func (c *Config) GetUUIDByRequestModelAndScenario(requestModel string, scenario typ.RuleScenario) string
- func (c *Config) GetUserToken() string
- func (c *Config) GetVerbose() bool
- func (c *Config) HasModelToken() bool
- func (c *Config) HasToken() bool
- func (c *Config) HasUserToken() bool
- func (c *Config) InsertDefaultRule() error
- func (c *Config) IsGlobalTokenDisabled() bool
- func (c *Config) IsMultiTenantEnabled() bool
- func (c *Config) IsRequestModel(modelName string) bool
- func (c *Config) IsRequestModelInScenario(modelName string, scenario typ.RuleScenario) bool
- func (c *Config) IsScenarioRecordingEnabled(scenario typ.RuleScenario) bool
- func (c *Config) ListOAuthProviders() ([]*typ.Provider, error)
- func (c *Config) ListProviders() []*typ.Provider
- func (c *Config) MatchRuleByModelAndScenario(requestModel string, scenario typ.RuleScenario) *typ.Rule
- func (c *Config) RefreshStatsFromStore() error
- func (c *Config) RegisterProviderDeleteHook(hook ProviderDeleteHook)
- func (c *Config) RegisterProviderUpdateHook(hook ProviderUpdateHook)
- func (c *Config) RemoveRequestConfig(index int) error
- func (c *Config) ResolveProfileAlias(baseScenario typ.RuleScenario, alias string) (string, bool)
- func (c *Config) ResolveProfileNameOrID(baseScenario typ.RuleScenario, input string) (string, error)
- func (c *Config) ResolveProviderModels(forceRefresh, forceUpstream bool, uid string) (ResolvedModels, error)
- func (c *Config) Save() error
- func (c *Config) SetDebug(debug bool) error
- func (c *Config) SetDefaultMaxTokens(maxTokens int) error
- func (c *Config) SetDefaultRequestID(id int) error
- func (c *Config) SetGUIDebug(debug bool) error
- func (c *Config) SetGUIPort(port int) error
- func (c *Config) SetGUIVerbose(verbose bool) error
- func (c *Config) SetModelToken(token string) error
- func (c *Config) SetMultiTenantConfig(config MultiTenantConfig) error
- func (c *Config) SetMultiTenantEnabled(enabled bool) error
- func (c *Config) SetOpenBrowser(openBrowser bool) error
- func (c *Config) SetRequestConfigs(requestConfigs []typ.Rule) error
- func (c *Config) SetScenarioConfig(config typ.ScenarioConfig) error
- func (c *Config) SetScenarioExtensions(scenario typ.RuleScenario, values map[string]interface{}) error
- func (c *Config) SetScenarioFlag(scenario typ.RuleScenario, flagName string, value bool) error
- func (c *Config) SetScenarioIntFlag(scenario typ.RuleScenario, flagName string, value int) error
- func (c *Config) SetScenarioStringFlag(scenario typ.RuleScenario, flagName string, value string) error
- func (c *Config) SetServerHost(host string) error
- func (c *Config) SetServerPort(port int) error
- func (c *Config) SetTemplateManager(tm *data.TemplateManager)
- func (c *Config) SetToken(token string) error
- func (c *Config) SetToolConfig(toolType string, config interface{}) error
- func (c *Config) SetUserToken(token string) error
- func (c *Config) SetVerbose(verbose bool) error
- func (c *Config) StoreManager() *db.StoreManager
- func (c *Config) UpdateClaudeCodeProfileConfig(baseScenario typ.RuleScenario, profileID string, ...) error
- func (c *Config) UpdateProfile(baseScenario typ.RuleScenario, profileID string, name string, unified *bool) error
- func (c *Config) UpdateProvider(uuid string, provider *typ.Provider) error
- func (c *Config) UpdateRequestConfigAt(index int, reqConfig typ.Rule) error
- func (c *Config) UpdateRequestConfigByRequestModel(requestModel string, reqConfig typ.Rule) error
- func (c *Config) UpdateRequestConfigByUUID(uuid string, reqConfig typ.Rule) error
- func (c *Config) UpdateRule(uid string, rule typ.Rule) error
- type ConfigOption
- type DshPrefs
- type EnterpriseContextJWTConfig
- type EnterpriseContextPublicKey
- type GUIConfig
- type GenericMCPConfig
- type HTTPTransportConfig
- type ModelListSource
- type MultiTenantConfig
- type OpenCodeConfigPayload
- type OpenCodeProviderConfig
- type ProviderDeleteHook
- type ProviderUpdateHook
- type ResolvedModels
- type RestoreResult
- type Watcher
- func (cw *Watcher) AddCallback(callback func(*Config))
- func (cw *Watcher) AddWatchFile(filepath string) error
- func (cw *Watcher) GetWatchFiles() []string
- func (cw *Watcher) RemoveWatchFile(filepath string) error
- func (cw *Watcher) Start() error
- func (cw *Watcher) Stop() error
- func (cw *Watcher) TriggerReload() error
Constants ¶
const ( // Very old / pre-scenario-split legacy UUIDs. Still present in configs // written before the scenario model was introduced. RuleUUIDTingly = "tingly" RuleUUIDClaudeCode = "claude-code" // Legacy built-in UUIDs (hyphenated "built-in-*" form). Live configs are // renamed to the modern RuleUUID* values by migrate20260612; these // constants remain so older migrations and compatibility fallbacks can // still address pre-rename configs. RuleUUIDBuiltinOpenAI = "built-in-openai" RuleUUIDBuiltinAnthropic = "built-in-anthropic" RuleUUIDBuiltinCodex = "built-in-codex" RuleUUIDBuiltinOpenCode = "built-in-opencode" RuleUUIDBuiltinAgent = "built-in-agent" RuleUUIDBuiltinAgentClaw = "built-in-agent-claw" RuleUUIDBuiltinTeam = "built-in-team" // Legacy Claude Code built-in UUIDs. Live configs are renamed to the // modern RuleUUIDCC* values by migrate20260611; these constants remain so // older migrations (which run before the rename) and compatibility // fallbacks can still address pre-rename configs. RuleUUIDBuiltinCC = "built-in-cc" RuleUUIDBuiltinCCHaiku = "built-in-cc-haiku" RuleUUIDBuiltinCCSonnet = "built-in-cc-sonnet" RuleUUIDBuiltinCCOpus = "built-in-cc-opus" RuleUUIDBuiltinCCDefault = "built-in-cc-default" RuleUUIDBuiltinCCSubagent = "built-in-cc-subagent" // Modern built-in rules — "builtin:<scenario>:<tier>" form. // These are the target UUIDs after migrate20260612 renames the legacy ones. RuleUUIDOpenAI = "builtin:openai:default" RuleUIDAnthropic = "builtin:anthropic:default" RuleUUIDCodex = "builtin:codex:default" RuleUUIDOpenCode = "builtin:opencode:default" // RuleUUIDAgent / RuleUUIDAgentClaw are deprecated — the "agent" scenario // (OpenClaw) was renamed to "custom". These constants remain only as // migration source keys: legacySimpleRuleUUIDs renames a live rule's UUID // to RuleUUIDCustom / RuleUUIDCustomClaw, and migrateAgentScenarioToCustom // (migration.go) separately renames its Scenario field. RuleUUIDAgent = "builtin:agent:default" RuleUUIDAgentClaw = "builtin:agent:claw" // RuleUUIDCustom / RuleUUIDCustomClaw are the migration *targets* for the // RuleUUIDAgent* rename above — a UUID a pre-existing rule gets renamed // to, never a template DefaultRules seeds for new installs. "custom" is a // bring-your-own-request-model scenario; it intentionally starts empty. RuleUUIDCustom = "builtin:custom:default" RuleUUIDCustomClaw = "builtin:custom:claw" // Claude Code built-in rules (modern "builtin:<scenario>:<tier>" form) RuleUUIDCC = "builtin:claude_code:cc" RuleUUIDCCDefault = "builtin:claude_code:default" RuleUUIDCCHaiku = "builtin:claude_code:haiku" RuleUUIDCCSonnet = "builtin:claude_code:sonnet" RuleUUIDCCOpus = "builtin:claude_code:opus" RuleUUIDCCSubagent = "builtin:claude_code:subagent" // Claude Desktop built-in rules (locked, using builtin: prefix) RuleUUIDBuiltinClaudeDesktopSonnet46 = "builtin:claude_desktop:claude-sonnet-4-6" RuleUUIDBuiltinClaudeDesktopOpus46 = "builtin:claude_desktop:claude-opus-4-6" RuleUUIDBuiltinClaudeDesktopOpus47 = "builtin:claude_desktop:claude-opus-4-7" RuleUUIDBuiltinClaudeDesktopHaiku45 = "builtin:claude_desktop:claude-haiku-4-5" )
Built-in rule UUID constants
const Context1MSuffix = "[1m]"
Context1MSuffix is the model-name suffix Claude clients use to advertise the 1M context window (Claude Code strips it back off and sends the context-1m beta header; Claude Desktop picks names verbatim from /v1/models).
const SmartGuideRuleUUIDPrefix = "_internal_smart_guide_"
SmartGuideRuleUUIDPrefix is the prefix for internal SmartGuide rules Each bot will have its own rule: _internal_smart_guide_{botUUID}
const ToolTypeMCPRuntime = "mcp_runtime"
ToolTypeMCPRuntime is the ToolConfigs key for the MCP runtime tool config. Tool configs live in config.json (GetToolConfig/SetToolConfig); the constant used to live in internal/db next to a store that was never wired up.
const (
WildcardRuleName = "*"
)
Wildcard rule names that match any model
Variables ¶
var DefaultRules []typ.Rule
Functions ¶
func BuildClaudeSettings ¶ added in v0.260801.1
BuildClaudeSettings renders a complete Claude settings document from the supplied base without touching disk. Generated runtime artifacts use this to publish one complete snapshot instead of exposing intermediate writes.
func BuildContextWindowsFromRules ¶ added in v0.260611.1
BuildContextWindowsFromRules maps each active Codex rule carrying the context_1m flag to the 1M context window. Keys are the rules' request models verbatim — exactly the names collectCodexRuleModels feeds into the catalog — so the override always lands on its catalog entry.
func BuiltinDir ¶ added in v0.260709.1
func BuiltinRuleUUID ¶ added in v0.260611.1
func BuiltinRuleUUID(scenario typ.RuleScenario, model string) string
BuiltinRuleUUID builds a built-in rule UUID in the modern "builtin:<scenario>:<model>" form — the target convention all built-in rules will eventually converge on (the legacy "built-in-*" constants above predate it). Works for profiled scenarios too, since the scenario name carries the profile suffix: BuiltinRuleUUID("claude_code:p1", "haiku") = "builtin:claude_code:p1:haiku".
func ConfigPath ¶ added in v0.260709.1
func EnsurePath ¶ added in v0.260709.1
EnsurePath returns the guardrails config path, lazily choosing the default location when no config has been written yet. Used by the editor-style endpoints, which are allowed to create the default file on first write.
func EnterpriseContextKeyPaths ¶ added in v0.260801.1
EnterpriseContextKeyPaths returns the on-disk paths for a config dir's enterprise-context RS256 key pair. Exported so callers that need to provision or inspect the key slots directly (e.g. a harness pre-seeding key material — see internal/protocoltest) don't have to reimplement the layout.
func FindConfig ¶ added in v0.260709.1
FindConfig locates the guardrails config file, checking the nested directory first and falling back to legacy flat-file locations.
func GenerateEnterpriseContextPEMs ¶ added in v0.260801.1
GenerateEnterpriseContextPEMs generates a fresh RSA-2048 key pair and returns it PEM-encoded (private PKCS1, public PKIX). Exported alongside WriteEnterpriseContextKeys so a caller that needs to provision key material ahead of config creation (e.g. a harness pre-seeding many config dirs from one generated pair — see internal/protocoltest) can reuse the exact same generation/encoding logic ensureEnterpriseContextRS256KeyPair uses.
func GenerateModelToken ¶ added in v0.260409.1540
func GenerateSecureToken ¶
GenerateSecureToken generates a cryptographically random token for user authentication The token is a 256-bit (32 byte) random value, hex-encoded, with a "tingly-box-" prefix
func GenerateUserToken ¶ added in v0.260409.1540
func HistoryPath ¶ added in v0.260709.1
func ImHookEntries ¶ added in v0.260507.1
func ImHookEntries() map[string]interface{}
ImHookEntries defines the Claude Code hooks to install for INTERACTIVE approval via IM. This includes PreToolUse (all tool calls) and permission-type notifications.
func InstallIMHookScript ¶ added in v0.260507.1
InstallIMHookScript installs the tingly-im-hook.sh script (interactive approval) to ~/.claude/ Returns the path to the installed script and whether it was newly created
func InstallNotifyScript ¶
InstallNotifyScript installs the tingly-notify.sh script (push-only) to ~/.claude/ Returns the path to the installed script and whether it was newly created
func InstallStatusLineScript ¶
InstallStatusLineScript installs the tingly-statusline.sh script to ~/.claude/ Returns the path to the installed script and whether it was newly created
func IsDefaultToken ¶
IsDefaultToken checks if the given token is the default token
func IsTacticValid ¶
IsTacticValid checks if the tactic params are valid (not zero values)
func IsWildcardRuleName ¶
IsWildcardRuleName checks if the given rule name is a wildcard that matches any model. This function is thread-safe as it only performs constant string comparisons and does not access any shared state. It can be called without holding Config.mu.
func MarshalConfig ¶ added in v0.260709.1
func MarshalConfig(cfg guardrailscore.Config) ([]byte, error)
MarshalConfig serializes a guardrails config to its on-disk YAML form.
func Migrate ¶
Migrate runs every registered migration step in order and persists the config once at the end if any step reported a change, instead of each step saving independently.
func NotifyHookEntries ¶
func NotifyHookEntries() map[string]interface{}
NotifyHookEntries defines the Claude Code hooks to install for PUSH-ONLY notifications. This includes Stop events and completion-type notifications. For interactive approval hooks (PreToolUse, permission notifications), use ImHookEntries instead.
func RegistryCachePath ¶ added in v0.260709.1
func RenderCodexConfigTOML ¶ added in v0.260514.1
func RenderCodexConfigTOML(baseURL string, models []string, prefs *CodexPrefs, writeCatalog bool, bearerToken string) ([]byte, error)
RenderCodexConfigTOML returns the TOML that would be written to a fresh ~/.codex/config.toml — i.e. the merge applied to an empty starting point. Used by the preview endpoint so the UI can show exactly what's pending.
func RenderCodexModelCatalog ¶ added in v0.260531.1
renderCodexModelCatalog produces the JSON payload for ~/.codex/tingly-model-catalog.json. Each model becomes one ModelInfo entry with the required fields populated using conservative defaults that match the OpenAI Responses API surface (text-in/text-out, reasoning summaries on, no verbosity knob). Codex 0.124+ deserializes this into `protocol::openai_models::ModelsResponse`; field names and value types must stay in sync with that struct.
The contextWindows parameter allows overriding the default context window for specific models (e.g., 1M context window models). If nil, uses default.
func RenderDshCredentialsYAML ¶ added in v0.260819.0
RenderDshCredentialsYAML returns the YAML that would be written to a fresh .credentials.yaml — i.e. just the tingly-managed key. Used by the preview endpoint; the real ApplyDshCredentials merges into any existing file.
func RenderDshSettingsYAML ¶ added in v0.260819.0
RenderDshSettingsYAML returns the YAML that would be written to a fresh settings.yaml — i.e. the merge applied to an empty starting point. Used by the preview endpoint so the UI can show exactly what's pending.
func SmartGuideRuleUUID ¶
SmartGuideRuleUUID generates a unique rule UUID for a specific bot
func SortProviderModels ¶ added in v0.260709.1
SortProviderModels applies the canonical display ordering to a provider's model list in place. It is the single source of truth for model ordering served to clients — callers (fetch + serving boundaries) invoke it instead of relying on the frontend to sort.
Default: alphabetical by model id. OpenRouter additionally tags free models with a ":free" suffix; those are promoted to the front, sorted alphabetically among themselves and ahead of the paid models (which are also alphabetical).
func TrimContext1M ¶ added in v0.260611.1
TrimContext1M removes the [1m] context-window suffix from a model name.
func WriteEnterpriseContextKeys ¶ added in v0.260801.1
WriteEnterpriseContextKeys writes a PEM key pair into configDir's key slots (see EnterpriseContextKeyPaths).
func WriteFileAtomic ¶ added in v0.260709.1
WriteFileAtomic keeps config/history writes crash-safe: it writes to a temp file in the same directory then renames it into place.
Types ¶
type ApplyOption ¶ added in v0.260423.0
type ApplyOption func(*applyOptions)
ApplyOption is a functional option for ApplyClaudeSettingsToPath
func WithBackup ¶ added in v0.260423.0
func WithBackup(enable bool) ApplyOption
WithBackup enables or disables backup when applying settings. Default is true (create backup).
func WithBackupRetention ¶ added in v0.260507.1
func WithBackupRetention(n int) ApplyOption
WithBackupRetention overrides the default number of backups to keep after rotation. n <= 0 means use the package default.
func WithDefaultMode ¶ added in v0.260709.1
func WithDefaultMode(mode string) ApplyOption
WithDefaultMode sets the Claude Code defaultMode value in settings.json.
func WithExtra ¶ added in v0.260423.0
func WithExtra(key string, value any) ApplyOption
WithExtra sets a single extra key-value pair to merge into the settings.
func WithShowThinkingSummaries ¶ added in v0.260819.0
func WithShowThinkingSummaries(show bool) ApplyOption
WithShowThinkingSummaries sets the Claude Code top-level showThinkingSummaries value in settings.json.
type ApplyResult ¶
type ApplyResult struct {
Success bool `json:"success"`
BackupPath string `json:"backupPath,omitempty"`
Message string `json:"message"`
Created bool `json:"created,omitempty"`
Updated bool `json:"updated,omitempty"`
}
ApplyResult contains the result of applying a configuration
func ApplyClaudeOnboarding ¶
func ApplyClaudeOnboarding(payload map[string]interface{}) (*ApplyResult, error)
ApplyClaudeOnboarding applies Claude onboarding configuration It merges top-level keys, preserving existing keys not in payload
func ApplyClaudeSettingsFromEnv ¶
func ApplyClaudeSettingsFromEnv(env map[string]string, opts ...ApplyOption) (*ApplyResult, error)
ApplyClaudeSettingsFromEnv applies Claude settings configuration with env vars This is the safe version - env map is controlled by backend
func ApplyClaudeSettingsToPath ¶
func ApplyClaudeSettingsToPath(targetPath string, env map[string]string, opts ...ApplyOption) (*ApplyResult, error)
ApplyClaudeSettingsToPath applies Claude settings env vars to a specific target file. If the file exists, it merges the env section into the existing config (with backup). If not, it creates a new file with only the env section.
func ApplyCodexAuth ¶ added in v0.260514.1
func ApplyCodexAuth(mode CodexAuthMode, apiKey string, tokens *CodexChatGPTTokens) (*ApplyResult, error)
ApplyCodexAuth writes `~/.codex/auth.json`. The previous version (if any) is backed up before modification; existing top-level keys outside the managed set are preserved.
Mode semantics:
- CodexAuthAPIKey: sets `OPENAI_API_KEY` to the supplied key (gateway mode).
- CodexAuthChatGPT: writes `tokens` / `last_refresh` / `auth_mode: "chatgpt"` and clears `OPENAI_API_KEY`. Tokens come from the caller; tingly-box does not subsequently refresh them.
- CodexAuthHybrid: the gateway credential lives in config.toml (not here), so auth.json only needs to carry the native ChatGPT login. With tokens supplied it behaves like CodexAuthChatGPT; with tokens nil it is a no-op that leaves any existing auth.json (e.g. a prior `codex login`) untouched.
func ApplyCodexConfig ¶ added in v0.260514.1
func ApplyCodexConfig(baseURL string, models []string, prefs *CodexPrefs, writeCatalog bool) (*ApplyResult, error)
ApplyCodexConfig merges tingly-box Codex settings into ~/.codex/config.toml and writes ~/.codex/tingly-model-catalog.json with one entry per supplied model so Codex's `/model` picker can see them.
This is the backward-compatible version that uses default context windows. For context window support, use ApplyCodexConfigWithContextWindows.
func ApplyCodexConfigWithContextWindows ¶ added in v0.260611.1
func ApplyCodexConfigWithContextWindows(baseURL string, models []string, prefs *CodexPrefs, writeCatalog bool, contextWindows map[string]int, bearerToken string) (*ApplyResult, error)
ApplyCodexConfigWithContextWindows merges tingly-box Codex settings into ~/.codex/config.toml and writes ~/.codex/tingly-model-catalog.json with one entry per supplied model so Codex's `/model` picker can see them.
The contextWindows parameter overrides the catalog's default context window for specific models (e.g., 1M for models with the context_1m flag); nil uses defaults.
MERGE semantics: only fields tingly-box manages are overwritten. Everything else the user put in config.toml — other top-level keys, other entries under `[model_providers.*]`, and unrelated `[profiles.*]` blocks — is left alone.
Managed fields:
- top-level `model` (set to models[0] when models is non-empty)
- top-level `model_provider = "tingly-box"`
- top-level `model_catalog_json` (set to the absolute path of the catalog file when models is non-empty; cleared otherwise so we don't point at a missing file)
- `[model_providers.tingly-box]` (always re-pinned to the supplied base URL)
- `[profiles.<sanitized(model)>]` for each model — overwritten unconditionally under that key; `agent restore codex` recovers the previous file if needed
- the whitelisted user prefs (see codexPrefSpec, e.g. `model_reasoning_effort`, `model_reasoning_summary`, `model_supports_reasoning_summaries`, `model_verbosity`) at the top level and inside each managed profile
Note: Codex's `model_catalog_json` REPLACES the bundled catalog (it does not merge), and is read on startup only — switching via `/model` doesn't reload it. Users wanting native OpenAI entries in `/model` should keep the bundled catalog (i.e. not run apply) or merge by hand.
Orphan tingly profiles from earlier applies are NOT garbage-collected; if the user has trimmed their rules they can remove stale profiles by hand.
The previous config.toml and catalog (if any) are backed up before being rewritten.
bearerToken (hybrid mode) is embedded into the tingly-box provider stanza as experimental_bearer_token; pass "" for the classic gateway path where the key is written to auth.json instead.
func ApplyDshCredentials ¶ added in v0.260819.0
func ApplyDshCredentials(apiKey string) (*ApplyResult, error)
ApplyDshCredentials writes $DSH_HOME/.credentials.yaml, setting only the tingly-box managed env var key; other keys already in the file (other providers' credentials) are preserved. The previous file (if any) is backed up before modification.
func ApplyDshSettings ¶ added in v0.260819.0
func ApplyDshSettings(baseURL string, models []string, prefs *DshPrefs) (*ApplyResult, error)
ApplyDshSettings merges tingly-box's provider entry into $DSH_HOME/settings.yaml.
MERGE semantics: only the `llm-pi-ai.providers.tingly-box` stanza is overwritten; everything else the user has in settings.yaml — other providers, unrelated top-level keys — is left alone. The previous file (if any) is backed up before rewrite.
func ApplyImHooks ¶ added in v0.260507.1
func ApplyImHooks() (*ApplyResult, error)
ApplyImHooks installs the IM hook script (interactive approval) and merges IM hooks into settings.json. This is independent of the agent apply flow — it can be called standalone. Existing hooks with different matchers are preserved.
func ApplyNotifyHooks ¶
func ApplyNotifyHooks() (*ApplyResult, error)
ApplyNotifyHooks installs the notify script and merges notification hooks into settings.json. This is independent of the agent apply flow — it can be called standalone. Existing hooks with different matchers are preserved.
func ApplyOpenCodeConfig ¶
func ApplyOpenCodeConfig(payload map[string]interface{}) (*ApplyResult, error)
ApplyOpenCodeConfig applies OpenCode configuration It merges the provider map while preserving other providers and settings
func ClearCodexGatewayConfig ¶ added in v0.260604.1
func ClearCodexGatewayConfig() (*ApplyResult, error)
ClearCodexGatewayConfig removes tingly-managed top-level keys from ~/.codex/config.toml so that when a user switches to native ChatGPT OAuth mode the codex CLI falls back to its own defaults rather than trying to route requests through the (now-unused) tingly-box gateway.
Only the tingly-managed top-level fields are removed; everything else (other provider entries, profiles, user prefs) is left intact. The previous config.toml is backed up before modification.
type BackupInfo ¶ added in v0.260507.1
BackupInfo describes a single backup file for an original config path.
func ListBackups ¶ added in v0.260507.1
func ListBackups(originalPath string) ([]BackupInfo, error)
ListBackups returns all backup files for originalPath in <dir>/backup/, ordered newest-first. Files that do not match the "<base>.bak-<timestamp><ext>" pattern are ignored.
type ClaudeSettingsPayload ¶
ClaudeSettingsPayload contains the payload for applying Claude settings
type CodexAuthMode ¶ added in v0.260604.1
type CodexAuthMode string
CodexAuthMode selects how `~/.codex/auth.json` is populated.
const ( // CodexAuthAPIKey writes only `OPENAI_API_KEY` — used when codex CLI // should talk to tingly-box as a gateway. CodexAuthAPIKey CodexAuthMode = "apikey" // CodexAuthChatGPT exports a native ChatGPT-login auth.json so codex CLI // can talk to OpenAI directly using OAuth tokens previously obtained by // tingly-box. tingly-box does NOT refresh these tokens afterwards — // codex CLI owns their lifecycle from that point on. CodexAuthChatGPT CodexAuthMode = "chatgpt" // CodexAuthHybrid keeps requests flowing through the tingly-box gateway // (the gateway token lives in config.toml's provider stanza as // experimental_bearer_token) WHILE preserving a native ChatGPT login in // auth.json so Codex App still recognizes the official account (remote // control, plugins, account display). When ChatGPT tokens are supplied // they are materialized into auth.json; when absent, auth.json is left // untouched so an existing `codex login` survives. CodexAuthHybrid CodexAuthMode = "hybrid" )
type CodexChatGPTTokens ¶ added in v0.260604.1
type CodexChatGPTTokens struct {
IDToken string
AccessToken string
RefreshToken string
AccountID string
}
CodexChatGPTTokens carries the OAuth credentials needed to materialize a native ChatGPT-login `auth.json`.
type CodexPrefs ¶ added in v0.260531.1
type CodexPrefs struct {
ModelReasoningEffort string `json:"model_reasoning_effort,omitempty"`
ModelReasoningSummary string `json:"model_reasoning_summary,omitempty"`
ModelVerbosity string `json:"model_verbosity,omitempty"`
ModelSupportsReasoningSummaries string `json:"model_supports_reasoning_summaries,omitempty"`
}
CodexPrefs is the typed, user-tunable surface of Codex's config.toml. JSON tags map 1:1 to the config.toml keys, so the frontend round-trips the same field names. Values are kept as strings so empty = omit (let Codex use its own default), avoiding the "0/false means unset" ambiguity.
The struct itself is the whitelist: only these keys can ever be set from a request, so prefs can never clobber tingly-managed fields (model, model_provider, model_catalog_json, model_providers.*) or inject arbitrary TOML. Scope is deliberately limited to model/reasoning knobs (not approval_policy / sandbox_mode safety toggles).
func CodexPrefsFromConfig ¶ added in v0.260801.1
func CodexPrefsFromConfig(cfg map[string]interface{}) *CodexPrefs
CodexPrefsFromConfig is the inverse of (*CodexPrefs).toConfig: it extracts the typed, whitelisted CodexPrefs keys from a parsed config.toml top-level map. Only the four managed keys are read; enum values are validated (invalid values dropped) and the bool field is normalized back to "true"/"" so it round-trips through the same JSON shape the frontend edits. Keys outside the whitelist are ignored — a hand-edited config.toml can never smuggle extra fields into the prefs surface.
func DefaultCodexPrefs ¶ added in v0.260531.1
func DefaultCodexPrefs() *CodexPrefs
DefaultCodexPrefs returns the defaults for the CLI path and no-prefs fallback. All fields are empty so tingly-box stays out of the way for third-party providers that may not support OpenAI reasoning-summary extensions. Users who need reasoning summaries can enable them via the Quick Config form.
func ReadCodexConfig ¶ added in v0.260801.1
func ReadCodexConfig() (prefs *CodexPrefs, writeCatalog bool, exists bool, err error)
ReadCodexConfig reads ~/.codex/config.toml and returns the typed prefs, the inferred writeCatalog state (true when model_catalog_json is set), and whether a tingly-managed config exists. A missing or unparseable file yields empty prefs, writeCatalog=false, exists=false. exists is true only when the file is tingly-managed (see isTinglyManagedCodexConfig) so a never-configured machine reads as "not applied" and the form falls back to defaults.
type Config ¶
type Config struct {
// Rules is the in-memory working set of routing rules. It is hydrated from
// SQLite (db.RuleStore) at startup and written back through Save(); it is
// deliberately NOT serialized to config.json anymore — the database is the
// authority. The in-memory copy stays because the hot request path matches
// rules under RLock and services carry hydrated runtime stats.
Rules []typ.Rule `yaml:"rules" json:"-"`
// LegacyRules receives the file's "rules" array on load. It is consumed
// exactly once, by hydrateRulesFromStore (one-time import into the
// database on upgraded installs); after hydration the field stays nil and
// file rules are ignored on reload. The "rules" key itself keeps being
// written by Save() as a live mirror of Rules during the transition
// period, purely for downgrade compatibility — see Save().
LegacyRules []typ.Rule `yaml:"-" json:"rules"`
DefaultRequestID int `yaml:"default_request_id" json:"default_request_id"` // Index of the default Rule
UserToken string `yaml:"user_token" json:"user_token"` // User token for UI and control API authentication
ModelToken string `yaml:"model_token" json:"model_token"` // Model token for OpenAI and Anthropic API authentication
InternalAPIToken string `json:"-"` // Internal API token for probe testing (generated at startup, not persisted)
EncryptProviders bool `yaml:"encrypt_providers" json:"encrypt_providers"` // Whether to encrypt provider info (default false)
Scenarios []typ.ScenarioConfig `yaml:"scenarios" json:"scenarios"` // Scenario-specific configurations
GUI GUIConfig `json:"gui"` // GUI-specific settings
RandomUUID string `json:"random_uuid"` // A random uuid to help protocol transform for some special provider
ClaudeCodeDeviceID string `json:"claude_code_device_id"` // Calc from random claude code device id with sha256
// Merged fields from Config struct
// ProvidersV1 and Providers are legacy JSON-config storage for providers.
// Providers now live in SQLite (db.ProviderStore); these fields are only
// populated on load for one-time migration to the database and are cleared
// by migrateProvidersToDB. The non-omitempty tags ensure that clearing them
// results in a JSON null that overrides any stale value in the existing file.
ProvidersV1 map[string]*typ.Provider `json:"providers"`
Providers []*typ.Provider `json:"providers_v2"`
ServerPort int `json:"-"`
ServerHost string `json:"-"` // Server host address (e.g., "localhost", "0.0.0.0", "192.168.1.100")
JWTSecret string `json:"jwt_secret"`
// Server settings
DefaultMaxTokens int `json:"default_max_tokens"` // Default max_tokens for anthropic API requests
Verbose bool `json:"verbose"` // Verbose mode for detailed logging
Debug bool `json:"-"` // Debug mode for Gin debug level logging
OpenBrowser bool `yaml:"-" json:"-"` // Auto-open browser in web UI mode (default: true)
// Generic tool configs map for all tool types
// Key is tool_type (e.g., "tool_interceptor", "code_execution")
// Value is the JSON-encoded config for that tool type
ToolConfigs map[string]json.RawMessage `json:"tool_configs,omitempty"`
// Health monitor settings
HealthMonitor loadbalance.HealthMonitorConfig `json:"health_monitor,omitempty" yaml:"health_monitor,omitempty"`
// Profiles stores scenario profile metadata, keyed by base scenario name.
// Each entry is a list of profiles for that scenario.
Profiles map[string][]typ.ProfileMeta `json:"profiles" yaml:"profiles"`
// Enterprise context JWT validation settings for TBE->TB proxy calls.
EnterpriseContextJWT EnterpriseContextJWTConfig `json:"enterprise_context_jwt,omitempty" yaml:"enterprise_context_jwt,omitempty"`
// HTTP Transport settings for upstream API connections
HTTPTransport HTTPTransportConfig `json:"http_transport,omitempty" yaml:"http_transport,omitempty"`
// Generic MCP path feature flags
// When enabled, routes traffic through the new generic MCP architecture
GenericMCP GenericMCPConfig `json:"generic_mcp,omitempty" yaml:"generic_mcp,omitempty"`
// ProviderTemplateSource supports three modes:
// 1. Empty/default -> use embedded templates (default GitHub sync behavior)
// 2. file:///path/to/template.json -> load from local file
// 3. https://example.com/template.json -> load from HTTP URL
ProviderTemplateSource string `yaml:"provider_template_source,omitempty" json:"provider_template_source,omitempty"`
// MultiTenantConfig holds settings for multi-tenant API token authentication
MultiTenantConfig MultiTenantConfig `yaml:"multi_tenant,omitempty" json:"multi_tenant,omitempty"`
// MigrationsCompleted tracks which one-time migrations have already been applied.
// This prevents idempotency-breaking migrations (e.g. service auto-fill) from
// re-running on every restart and overwriting intentional user changes.
MigrationsCompleted []string `json:"migrations_completed,omitempty" yaml:"migrations_completed,omitempty"`
ConfigFile string `yaml:"-" json:"-"` // Not serialized to YAML (exported to preserve field)
ConfigDir string `yaml:"-" json:"-"`
// contains filtered or unexported fields
}
Config represents the global configuration
func NewConfig ¶
func NewConfig(opts ...ConfigOption) (*Config, error)
NewConfig creates a new global configuration manager with the given options If no config directory is specified, uses the default tingly config directory
func NewConfigWithDir ¶
func NewConfigWithDir(configDir string, opts ...ConfigOption) (*Config, error)
NewConfigWithDir creates a new global configuration manager with a custom config directory This is a convenience function that calls NewConfig with WithConfigDir option For backward compatibility with existing code
func NewDefaultConfig ¶
NewDefaultConfig creates a new global configuration manager with default settings Uses the default tingly config directory and runs migrations
func (*Config) AddOrUpdateRequestConfigByRequestModel ¶
AddOrUpdateRequestConfigByRequestModel adds a new Rule or updates an existing one by request model name
func (*Config) AddProvider ¶
AddProvider adds a new provider using Provider struct
func (*Config) AddProviderByName ¶
AddProviderByName adds a new AI provider configuration by name, API base, and token
func (*Config) AddRequestConfig ¶
AddRequestConfig adds a new Rule. If a rule with the same UUID already exists, it is rejected instead of adding a duplicate.
func (*Config) ApplyHTTPTransportConfig ¶
func (c *Config) ApplyHTTPTransportConfig()
ApplyHTTPTransportConfig applies the HTTP transport configuration to the global transport pool. Called at runtime when the operator updates transport settings via the config API. Default behavior (all fields nil): providers without proxy_url connect directly, ignoring env proxy.
func (*Config) CloseStores ¶ added in v0.260716.1
CloseStores releases every database handle the config owns: the shared store-manager connection (which every store, including the one the ModelListManager wraps, now runs on) and the guardrails credential store, a separate file holding three descriptors with WAL on. The long-lived server closes the store manager from Stop; short-lived embedders (tests, harness environments) call this so each instance does not leak SQLite descriptors for the process lifetime. Safe to call more than once.
func (*Config) CreateDefaultConfig ¶
func (*Config) CreateProfile ¶
func (c *Config) CreateProfile(baseScenario typ.RuleScenario, name string, unified bool) (typ.ProfileMeta, error)
CreateProfile adds a new profile to a base scenario. Returns the created ProfileMeta. The unified parameter determines whether to use unified mode (single model) or separate mode (individual models).
func (*Config) CredentialStore ¶ added in v0.260819.0
func (c *Config) CredentialStore() (*guardrailsutils.ProtectedCredentialStore, error)
CredentialStore returns the protected-credential sqlite store shared by request-time masking (AI Model API) and the admin credential CRUD (WebUI Management API), building it on first use.
The Config owns it for the same reason it owns the other stores: the store holds a lazily-opened SQLite connection, and something has to be able to close it. This used to be a free function handing out a fresh store per call, which left a new connection behind on every credential-cache refresh — i.e. on the request path.
func (*Config) DeleteProfile ¶
func (c *Config) DeleteProfile(baseScenario typ.RuleScenario, profileID string) error
DeleteProfile removes a profile by ID and cleans up all associated rules.
func (*Config) DeleteProvider ¶
DeleteProvider removes a provider by UUID
func (*Config) DeleteRule ¶
func (*Config) EnsureSmartGuideRuleForBot ¶
EnsureSmartGuideRuleForBot ensures the _smart_guide rule exists for a specific bot If the rule doesn't exist, it creates it. If it exists but the configuration differs, it updates the rule. The rule is persisted to config.json.
Each bot gets its own rule with UUID: _internal_smart_guide_{botUUID} The rule name uses the bot's name (if provided), otherwise uses botUUID
func (*Config) FetchAndSaveProviderModels ¶
FetchAndSaveProviderModels fetches a provider's models and persists API results, warming the DB cache. It is retained for callers that only need to trigger a fetch (e.g. TUI cache-warming); callers that need the effective list should use ResolveProviderModels instead.
Contract: returns nil when a real API list was persisted OR when the API is unavailable but an embedded template exists to fall back on; returns an error only when neither a real nor a template list can be produced.
func (*Config) GetAPITokenAlgorithm ¶ added in v0.260418.2200
GetAPITokenAlgorithm returns the JWT signing algorithm for API tokens
func (*Config) GetAPITokenIssuer ¶ added in v0.260418.2200
GetAPITokenIssuer returns the issuer claim for API tokens
func (*Config) GetAPITokenSecret ¶ added in v0.260418.2200
GetAPITokenSecret returns the API token secret, falling back to JWTSecret
func (*Config) GetDefaultMaxTokens ¶
GetDefaultMaxTokens returns the configured default max_tokens
func (*Config) GetDefaultRequestConfig ¶
GetDefaultRequestConfig returns the default Rule
func (*Config) GetDefaultRequestID ¶
GetDefaultRequestID returns the index of the default Rule
func (*Config) GetDefaults ¶
GetDefaults returns all default values from the default Rule
func (*Config) GetEffectiveAffinity ¶ added in v0.260611.1
GetEffectiveAffinity returns the effective affinity TTL for a rule. session_affinity is rule-only — there is no scenario-level inheritance. The built-in Claude Code / Claude Desktop / Codex rules seed 1800s by default (init + migration); every other rule is disabled unless it sets an explicit value. Returns 0 (disabled) when the rule's value is 0.
func (*Config) GetGUIDebug ¶
GetGUIDebug returns the GUI debug setting
func (*Config) GetGUIPort ¶
GetGUIPort returns the GUI port setting (0 means use ServerPort)
func (*Config) GetGUIVerbose ¶
GetGUIVerbose returns the GUI verbose setting
func (*Config) GetInternalAPIToken ¶
GetInternalAPIToken returns the internal API token for probe testing The token is generated at startup and stored in memory only (not persisted to config file)
func (*Config) GetJWTSecret ¶
GetJWTSecret returns the JWT secret for token generation
func (*Config) GetMCPRuntimeConfig ¶ added in v0.260409.1540
func (c *Config) GetMCPRuntimeConfig() *typ.MCPRuntimeConfig
GetMCPRuntimeConfig returns the global MCP runtime config.
func (*Config) GetModelManager ¶
func (c *Config) GetModelManager() *data.ModelListManager
func (*Config) GetModelToken ¶
GetModelToken returns the model token
func (*Config) GetOpenBrowser ¶
GetOpenBrowser returns the open browser setting
func (*Config) GetProfile ¶
func (c *Config) GetProfile(baseScenario typ.RuleScenario, profileID string) (typ.ProfileMeta, bool)
GetProfile returns a single profile by base scenario and profile ID.
func (*Config) GetProfiles ¶
func (c *Config) GetProfiles(baseScenario typ.RuleScenario) []typ.ProfileMeta
GetProfiles returns all profiles for a base scenario.
func (*Config) GetProviderByName ¶
func (*Config) GetProviderByUUID ¶
GetProviderByUUID returns a provider from database
func (*Config) GetProviderStore ¶
func (c *Config) GetProviderStore() *db.ProviderStore
GetProviderStore returns the provider store instance
func (*Config) GetRequestConfigs ¶
GetRequestConfigs returns all Rules
func (*Config) GetRequestModel ¶
GetRequestModel returns the request model from the default Rule
func (*Config) GetResponseModel ¶
GetResponseModel returns the response model from the default Rule
func (*Config) GetRuleByRequestModelAndScenario ¶
func (c *Config) GetRuleByRequestModelAndScenario(requestModel string, scenario typ.RuleScenario) *typ.Rule
GetRuleByRequestModelAndScenario returns the Rule for the given request model and scenario
func (*Config) GetRuleByUUID ¶
GetRuleByUUID returns the Rule for the given request uuid
func (*Config) GetScenarioConfig ¶
func (c *Config) GetScenarioConfig(scenario typ.RuleScenario) *typ.ScenarioConfig
GetScenarioConfig returns the configuration for a specific scenario
func (*Config) GetScenarioExtensionBool ¶ added in v0.260409.1540
func (c *Config) GetScenarioExtensionBool(scenario typ.RuleScenario, key string) bool
GetScenarioExtensionBool returns a boolean value from scenario extensions.
func (*Config) GetScenarioExtensionString ¶ added in v0.260409.1540
func (c *Config) GetScenarioExtensionString(scenario typ.RuleScenario, key string) string
GetScenarioExtensionString returns a string value from scenario extensions.
func (*Config) GetScenarioFlag ¶
func (c *Config) GetScenarioFlag(scenario typ.RuleScenario, flagName string) bool
func (*Config) GetScenarioIntFlag ¶ added in v0.260611.1
func (c *Config) GetScenarioIntFlag(scenario typ.RuleScenario, flagName string) int
GetScenarioIntFlag returns an integer flag value for a scenario.
Generic infra for scenario-level integer flags: the HTTP int-flag endpoint routes through here. No keys are currently registered (session_affinity moved to a rule-only flag), so it returns 0; adding a future scenario int flag is just a new case in the switch.
func (*Config) GetScenarioRecordingMode ¶
func (c *Config) GetScenarioRecordingMode(scenario typ.RuleScenario) typ.RecordingMode
GetScenarioRecordingMode returns the effective recording mode for a scenario It checks both legacy Recording (bool) and new RecordV2 (RecordingMode) Priority: RecordV2 > legacy Recording
func (*Config) GetScenarioStringFlag ¶
func (c *Config) GetScenarioStringFlag(scenario typ.RuleScenario, flagName string) string
GetScenarioStringFlag returns a string flag value for a scenario
func (*Config) GetScenarios ¶
func (c *Config) GetScenarios() []typ.ScenarioConfig
GetScenarios returns all scenario configurations
func (*Config) GetServerHost ¶ added in v0.260604.1
GetServerHost returns the configured server host Returns "localhost" if no host is configured
func (*Config) GetServerPort ¶
GetServerPort returns the configured server port
func (*Config) GetSmartGuideRuleForBot ¶
GetSmartGuideRuleForBot returns the _smart_guide rule for a specific bot
func (*Config) GetTemplateManager ¶
func (c *Config) GetTemplateManager() *data.TemplateManager
GetTemplateManager returns the template manager
func (*Config) GetToolConfig ¶
GetToolConfig returns the global config for a specific tool type target is a pointer to the config struct to unmarshal into Returns true if config was found and successfully unmarshaled
func (*Config) GetUUIDByRequestModel ¶
GetUUIDByRequestModel returns the UUID for the given request model name
func (*Config) GetUUIDByRequestModelAndScenario ¶
func (c *Config) GetUUIDByRequestModelAndScenario(requestModel string, scenario typ.RuleScenario) string
GetUUIDByRequestModelAndScenario returns the UUID for the given request model and scenario
func (*Config) GetUserToken ¶
GetUserToken returns the user token
func (*Config) GetVerbose ¶
GetVerbose returns the verbose setting
func (*Config) HasModelToken ¶
HasModelToken checks if a model token is configured
func (*Config) HasToken ¶
HasToken checks if a user token is configured (for backward compatibility)
func (*Config) HasUserToken ¶
HasUserToken checks if a user token is configured
func (*Config) InsertDefaultRule ¶
func (*Config) IsGlobalTokenDisabled ¶ added in v0.260418.2200
IsGlobalTokenDisabled returns whether the global model token is disabled
func (*Config) IsMultiTenantEnabled ¶ added in v0.260418.2200
IsMultiTenantEnabled returns whether multi-tenant mode is enabled
func (*Config) IsRequestModel ¶
IsRequestModel checks if the given model name is a request model in any config
func (*Config) IsRequestModelInScenario ¶
func (c *Config) IsRequestModelInScenario(modelName string, scenario typ.RuleScenario) bool
IsRequestModelInScenario checks if the given model name is a request model in the given scenario
func (*Config) IsScenarioRecordingEnabled ¶
func (c *Config) IsScenarioRecordingEnabled(scenario typ.RuleScenario) bool
IsScenarioRecordingEnabled checks if recording is enabled for a scenario
func (*Config) ListOAuthProviders ¶
ListOAuthProviders returns all OAuth-enabled providers
func (*Config) ListProviders ¶
ListProviders returns all providers
func (*Config) MatchRuleByModelAndScenario ¶
func (c *Config) MatchRuleByModelAndScenario(requestModel string, scenario typ.RuleScenario) *typ.Rule
MatchRuleByModelAndScenario finds a rule by model name with wildcard support Priority: exact match > wildcard match Returns nil if no rule matches
func (*Config) RefreshStatsFromStore ¶
RefreshStatsFromStore hydrates service stats from the SQLite store.
func (*Config) RegisterProviderDeleteHook ¶
func (c *Config) RegisterProviderDeleteHook(hook ProviderDeleteHook)
RegisterProviderDeleteHook adds a hook to be called when a provider is deleted
func (*Config) RegisterProviderUpdateHook ¶
func (c *Config) RegisterProviderUpdateHook(hook ProviderUpdateHook)
RegisterProviderUpdateHook adds a hook to be called when a provider is created or updated.
func (*Config) RemoveRequestConfig ¶
RemoveRequestConfig removes the Rule at the given index
func (*Config) ResolveProfileAlias ¶ added in v0.260625.1
ResolveProfileAlias resolves a URL-friendly profile alias to its canonical profile ID. The alias may be:
- the profile ID itself (e.g. "p1") — returned as-is, and
- a profile's human-readable name (e.g. "mine") — but only when that name is a simple identifier safe to embed in a URL path segment.
Profiles whose names contain spaces or other characters that don't parse cleanly out of a URL are intentionally not routable by name; callers must address those by ID. Returns ("", false) when the alias matches neither a known ID nor a simple, unique profile name.
func (*Config) ResolveProfileNameOrID ¶
func (c *Config) ResolveProfileNameOrID(baseScenario typ.RuleScenario, input string) (string, error)
ResolveProfileNameOrID resolves a profile identifier to a profile ID. If the input matches an existing ID (e.g. "p1"), returns it directly. If the input matches an existing name, returns the corresponding ID.
func (*Config) ResolveProviderModels ¶ added in v0.260716.1
func (c *Config) ResolveProviderModels(forceRefresh, forceUpstream bool, uid string) (ResolvedModels, error)
ResolveProviderModels returns the effective model list for a provider, walking the full fallback chain in ONE place so every caller (HTTP read, HTTP refresh, CLI, OAuth completion) sees identical behavior:
cache (DB) → VModel (virtual) → upstream API → embedded template
When forceRefresh is false, a fresh-enough DB cache short-circuits the chain; when true the cache is bypassed and upstream is re-queried (the manual "refresh models" action). The returned list is canonically sorted.
Template results are never persisted, so an improved embedded list takes effect immediately and a template snapshot never pollutes a real cached list. This method always fetches on a cache miss — callers that must not touch the network (e.g. TUI render) should read the cache/template directly.
func (*Config) SetDefaultMaxTokens ¶
SetDefaultMaxTokens updates the default max_tokens
func (*Config) SetDefaultRequestID ¶
SetDefaultRequestID sets the index of the default Rule
func (*Config) SetGUIDebug ¶
SetGUIDebug updates the GUI debug setting
func (*Config) SetGUIPort ¶
SetGUIPort updates the GUI port setting
func (*Config) SetGUIVerbose ¶
SetGUIVerbose updates the GUI verbose setting
func (*Config) SetModelToken ¶
SetModelToken sets the model token for OpenAI and Anthropic APIs
func (*Config) SetMultiTenantConfig ¶ added in v0.260418.2200
func (c *Config) SetMultiTenantConfig(config MultiTenantConfig) error
SetMultiTenantConfig updates the entire multi-tenant configuration
func (*Config) SetMultiTenantEnabled ¶ added in v0.260418.2200
SetMultiTenantEnabled updates the multi-tenant enabled flag
func (*Config) SetOpenBrowser ¶
SetOpenBrowser updates the open browser setting (runtime only, not persisted)
func (*Config) SetRequestConfigs ¶
SetRequestConfigs updates all Rules
func (*Config) SetScenarioConfig ¶
func (c *Config) SetScenarioConfig(config typ.ScenarioConfig) error
SetScenarioConfig updates or creates a scenario configuration
func (*Config) SetScenarioExtensions ¶ added in v0.260409.1540
func (c *Config) SetScenarioExtensions(scenario typ.RuleScenario, values map[string]interface{}) error
SetScenarioExtensions merges extension values into a scenario config.
func (*Config) SetScenarioFlag ¶
SetScenarioFlag sets a specific flag value for a scenario
func (*Config) SetScenarioIntFlag ¶ added in v0.260611.1
SetScenarioIntFlag sets an integer flag value for a scenario.
Generic infra (see GetScenarioIntFlag). With no keys registered every flag is rejected; adding a future scenario int flag is just a new case in the switch.
func (*Config) SetScenarioStringFlag ¶
func (c *Config) SetScenarioStringFlag(scenario typ.RuleScenario, flagName string, value string) error
SetScenarioStringFlag sets a string flag value for a scenario
func (*Config) SetServerHost ¶ added in v0.260604.1
SetServerHost updates the server host
func (*Config) SetServerPort ¶
SetServerPort updates the server port
func (*Config) SetTemplateManager ¶
func (c *Config) SetTemplateManager(tm *data.TemplateManager)
SetTemplateManager sets the template manager for provider templates
func (*Config) SetToolConfig ¶
SetToolConfig sets the global config for a specific tool type
func (*Config) SetUserToken ¶
SetUserToken sets the user token for UI and control API
func (*Config) SetVerbose ¶
SetVerbose updates the verbose setting
func (*Config) StoreManager ¶
func (c *Config) StoreManager() *db.StoreManager
StoreManager returns the unified store manager (may be nil in tests). This provides access to all database stores through a single interface. External consumers should use this method instead of the individual GetXxxStore() methods.
func (*Config) UpdateClaudeCodeProfileConfig ¶ added in v0.260723.1
func (c *Config) UpdateClaudeCodeProfileConfig(baseScenario typ.RuleScenario, profileID string, profileConfig *typ.ClaudeCodeProfileConfig) error
UpdateClaudeCodeProfileConfig replaces the persistent Claude Code override delta for a profile. Passing nil clears all overrides and restores pure inheritance from the main Claude Code settings and profile routing rules.
func (*Config) UpdateProfile ¶
func (c *Config) UpdateProfile(baseScenario typ.RuleScenario, profileID string, name string, unified *bool) error
UpdateProfile updates the name of an existing profile. The unified parameter is accepted for API compatibility but ignored — mode is fixed at creation time. To switch modes, delete and recreate the profile.
func (*Config) UpdateProvider ¶
UpdateProvider updates an existing provider by UUID
func (*Config) UpdateRequestConfigAt ¶
UpdateRequestConfigAt updates the Rule at the given index
func (*Config) UpdateRequestConfigByRequestModel ¶
UpdateRequestConfigByRequestModel updates a Rule by its request model name
func (*Config) UpdateRequestConfigByUUID ¶
UpdateRequestConfigByUUID updates a Rule by its UUID
type ConfigOption ¶
type ConfigOption func(*configOptions)
ConfigOption is a function that modifies a Config during initialization
func WithConfigDir ¶
func WithConfigDir(dir string) ConfigOption
WithConfigDir returns a ConfigOption that sets a custom config directory
func WithDisableBuiltIn ¶
func WithDisableBuiltIn() ConfigOption
WithDisableBuiltIn returns a ConfigOption that disables the built-in rules creation
func WithDisableMigration ¶
func WithDisableMigration() ConfigOption
WithDisableMigration returns a ConfigOption that disables the migration step Useful when using tingly-box as a library in external projects
type DshPrefs ¶ added in v0.260819.0
type DshPrefs struct {
DefaultInput string `json:"default_input,omitempty"`
Protocol string `json:"protocol,omitempty"`
}
DshPrefs is the typed, user-tunable surface of settings.yaml's tingly-box provider entry. DefaultInput mirrors the provider-level `defaultInput` key ("text" or "text_image" -> [text] / [text, image]); empty omits the key so dsh treats the provider as text-only — the conservative default for models tingly-box cannot verify support vision (same stance as Codex's third-party defaults, see .design/codex-config.md). Protocol mirrors the provider-level `api` key (see dshProtocolValues) — unlike DefaultInput, dsh has no "omit it" state for `api`: it's a required field, so an empty/invalid Protocol always falls back to dshDefaultProtocol rather than being dropped.
func DefaultDshPrefs ¶ added in v0.260819.0
func DefaultDshPrefs() *DshPrefs
DefaultDshPrefs returns the defaults for the CLI path and no-prefs fallback: DefaultInput unset (text-only), Protocol defaulting to dshDefaultProtocol.
func DshPrefsFromConfig ¶ added in v0.260819.0
DshPrefsFromConfig is the inverse of toConfig: it extracts DefaultInput and Protocol from a parsed tingly-box provider stanza.
func ReadDshSettings ¶ added in v0.260819.0
ReadDshSettings reads $DSH_HOME/settings.yaml and returns the typed prefs and whether a tingly-managed provider stanza exists. A missing or unparseable file yields empty prefs, exists=false, so the form falls back to defaults rather than erroring on first-time setup.
type EnterpriseContextJWTConfig ¶
type EnterpriseContextJWTConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
AllowedIssuers []string `json:"allowed_issuers,omitempty" yaml:"allowed_issuers,omitempty"`
AllowedAudiences []string `json:"allowed_audiences,omitempty" yaml:"allowed_audiences,omitempty"`
AlgAllowlist []string `json:"alg_allowlist,omitempty" yaml:"alg_allowlist,omitempty"`
HS256SecretRef string `json:"hs256_secret_ref,omitempty" yaml:"hs256_secret_ref,omitempty"`
RS256PublicKeyRef string `json:"rs256_public_key_ref,omitempty" yaml:"rs256_public_key_ref,omitempty"`
JWKSURL string `json:"jwks_url,omitempty" yaml:"jwks_url,omitempty"`
PublicKeys []EnterpriseContextPublicKey `json:"public_keys,omitempty" yaml:"public_keys,omitempty"`
ClockSkewSeconds int `json:"clock_skew_seconds,omitempty" yaml:"clock_skew_seconds,omitempty"`
RequireJTI bool `json:"require_jti" yaml:"require_jti"`
}
type GUIConfig ¶
type GUIConfig struct {
// Debug enables debug mode for GUI (gin debug logging, detailed logs)
Debug bool `json:"debug"`
// Port specifies the GUI server port. 0 means use ServerPort from global config
Port int `json:"port"`
// Verbose enables verbose logging for GUI
Verbose bool `json:"verbose"`
}
GUIConfig holds GUI-specific settings (slim/gui mode)
type GenericMCPConfig ¶ added in v0.260507.1
type GenericMCPConfig struct {
// UseGenericAnthropicV1NonStream enables generic path for A→A V1 non-streaming
// When false: uses existing dispatch implementation
// When true: uses GenericLoopProcessor
UseGenericAnthropicV1NonStream bool `json:"use_generic_anthropic_v1_non_stream,omitempty" yaml:"use_generic_anthropic_v1_non_stream,omitempty"`
// UseGenericAnthropicV1Stream enables generic path for A→A V1 streaming
// When false: uses existing dispatch implementation
// When true: uses GenericStreamInterceptor
UseGenericAnthropicV1Stream bool `json:"use_generic_anthropic_v1_stream,omitempty" yaml:"use_generic_anthropic_v1_stream,omitempty"`
// UseGenericOpenAIChatNonStream enables generic path for O→O non-streaming
UseGenericOpenAIChatNonStream bool `json:"use_generic_openai_chat_non_stream,omitempty" yaml:"use_generic_openai_chat_non_stream,omitempty"`
// UseGenericOpenAIChatStream enables generic path for O→O streaming
UseGenericOpenAIChatStream bool `json:"use_generic_openai_chat_stream,omitempty" yaml:"use_generic_openai_chat_stream,omitempty"`
// ProviderLimits limits which providers use generic path
// Empty means all providers can use generic path
// Format: comma-separated provider names (e.g., "provider1,provider2")
ProviderLimits string `json:"provider_limits,omitempty" yaml:"provider_limits,omitempty"`
}
GenericMCPConfig holds settings for the new generic MCP architecture
type HTTPTransportConfig ¶
type HTTPTransportConfig struct {
// MaxIdleConns is the maximum number of idle connections across all hosts
// Default (nil): 100 (Go stdlib default)
// Recommended for 200 concurrent users: 200-300
MaxIdleConns *int `json:"max_idle_conns,omitempty" yaml:"max_idle_conns,omitempty"`
// MaxIdleConnsPerHost is the maximum number of idle connections per host
// Default (nil): 2 (Go stdlib default)
// Recommended for 200 concurrent users: 20-50
MaxIdleConnsPerHost *int `json:"max_idle_conns_per_host,omitempty" yaml:"max_idle_conns_per_host,omitempty"`
// MaxConnsPerHost limits the total number of connections per host (active + idle)
// Default (nil): 0 (no limit)
// Set to control maximum concurrent connections to a single upstream host
MaxConnsPerHost *int `json:"max_conns_per_host,omitempty" yaml:"max_conns_per_host,omitempty"`
// DisableKeepAlives disables HTTP/1.1 keep-alive connections
// Default (nil): false
// WARNING: Setting this to true will significantly impact performance
DisableKeepAlives *bool `json:"disable_keep_alives,omitempty" yaml:"disable_keep_alives,omitempty"`
// RespectEnvProxy controls whether providers without explicit proxy configuration
// should use environment/system proxy settings (HTTP_PROXY, HTTPS_PROXY, macOS system proxy, etc.)
// Default (nil): false - providers without proxy_url connect directly
// Set to true: providers without proxy_url will use system/environment proxy
RespectEnvProxy *bool `json:"respect_env_proxy,omitempty" yaml:"respect_env_proxy,omitempty"`
// GlobalProxyURL stores a shared proxy URL offered as a UI convenience default.
// The backend does NOT apply it automatically; users must explicitly opt in per-provider/OAuth.
GlobalProxyURL string `json:"global_proxy_url,omitempty" yaml:"global_proxy_url,omitempty"`
}
HTTPTransportConfig holds HTTP transport connection pool settings These settings control the connection pooling behavior for upstream API requests All fields use pointers so that omitting them means "use Go default" (backward compatible)
type ModelListSource ¶ added in v0.260716.1
type ModelListSource string
ModelListSource identifies where a resolved model list came from. Its string values match provider.ModelCacheSource so the HTTP layer can map directly.
const ( ModelListSourceCache ModelListSource = "db" // served from the DB cache ModelListSourceAPI ModelListSource = "api" // freshly fetched from upstream ModelListSourceVModel ModelListSource = "vmodel" // virtual provider's static list ModelListSourceTemplate ModelListSource = "template" // compile-time embedded fallback )
type MultiTenantConfig ¶ added in v0.260418.2200
type MultiTenantConfig struct {
// Enabled enables multi-tenant mode with JWT API token authentication
// When false, only the global model token is accepted (backward compatible)
Enabled bool `json:"enabled" yaml:"enabled"`
// DisableGlobalToken disables the global model token when true
// When enabled, only JWT API tokens are accepted for authentication
DisableGlobalToken bool `json:"disable_global_token" yaml:"disable_global_token"`
// APITokenSecret is the secret key for signing JWT tokens
// Use env: or file: references for secure secret management
// Default: Uses JWTSecret from main config
APITokenSecret string `json:"api_token_secret,omitempty" yaml:"api_token_secret,omitempty"`
// APITokenAlgorithm specifies the JWT signing algorithm
// Supported: "HS256" (default), "RS256"
APITokenAlgorithm string `json:"api_token_algorithm,omitempty" yaml:"api_token_algorithm,omitempty"`
// APITokenIssuer is the issuer claim for JWT tokens
// Default: "tingly-box"
APITokenIssuer string `json:"api_token_issuer,omitempty" yaml:"api_token_issuer,omitempty"`
}
MultiTenantConfig holds settings for multi-tenant API token authentication
type OpenCodeConfigPayload ¶
type OpenCodeConfigPayload struct {
Provider map[string]OpenCodeProviderConfig `json:"provider"`
}
OpenCodeConfigPayload contains the payload for applying OpenCode config
type OpenCodeProviderConfig ¶
type OpenCodeProviderConfig struct {
Name string `json:"name"`
NPM string `json:"npm"`
Options map[string]interface{} `json:"options"`
Models map[string]interface{} `json:"models"`
}
OpenCodeProviderConfig contains the provider configuration for OpenCode
type ProviderDeleteHook ¶
type ProviderDeleteHook interface {
OnProviderDelete(uuid string)
}
ProviderDeleteHook is called when a provider is deleted
type ProviderUpdateHook ¶
ProviderUpdateHook is called when a provider is created or updated.
type ResolvedModels ¶ added in v0.260716.1
type ResolvedModels struct {
Models []string
Source ModelListSource
LastUpdated string // formatted timestamp of the cached record; empty if unknown
}
ResolvedModels is the effective model list for a provider plus provenance.
type RestoreResult ¶ added in v0.260507.1
type RestoreResult struct {
Success bool `json:"success"`
OriginalPath string `json:"originalPath"`
RestoredFrom string `json:"restoredFrom,omitempty"`
PreRestoreBackup string `json:"preRestoreBackup,omitempty"`
Message string `json:"message"`
}
RestoreResult describes the outcome of restoring a single config file.
func RestoreLatestBackup ¶ added in v0.260507.1
func RestoreLatestBackup(originalPath string) (*RestoreResult, error)
RestoreLatestBackup restores originalPath from its most recent backup. If originalPath currently exists, a "pre-restore" backup of the live file is created first (and is itself subject to rotation) so the restore is reversible.
type Watcher ¶
type Watcher struct {
// contains filtered or unexported fields
}
Watcher monitors configuration changes and triggers reloads
func NewConfigWatcher ¶
NewConfigWatcher creates a new configuration watcher
func (*Watcher) AddCallback ¶
AddCallback adds a callback function to be called when configuration changes
func (*Watcher) AddWatchFile ¶
AddWatchFile adds a file to the watch list If the watcher is already running, the file will be added immediately
func (*Watcher) GetWatchFiles ¶
GetWatchFiles returns a copy of the current watch file list
func (*Watcher) RemoveWatchFile ¶
RemoveWatchFile removes a file from the watch list
func (*Watcher) TriggerReload ¶
TriggerReload manually triggers a configuration reload
Source Files
¶
- apply_config.go
- apply_config_claude.go
- apply_config_codex.go
- apply_config_dsh.go
- apply_config_opencode.go
- builtin_rules.go
- config.go
- enterprise.go
- guardrails.go
- gui.go
- init.go
- migration.go
- model_resolve.go
- profile.go
- provider.go
- rule.go
- rule_storage.go
- scenario.go
- server_settings.go
- smart_guide_rule.go
- token.go
- util.go
- watcher.go