config

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package config loads deepseekcode configuration from TOML with precedence: CLI flags > project ./.deepseek/config.toml > user ~/.deepseek/config.toml > built-in defaults.

Env vars referenced as ${VAR} inside string values are expanded at load time. API key resolution falls back to DEEPSEEK_API_KEY when [api].key is empty.

Index

Constants

View Source
const ModelFlash = "deepseek-v4-flash"

ModelFlash is the v0.1 default main-loop model.

View Source
const ModelPro = "deepseek-v4-pro"

ModelPro is the escalation/validator model.

View Source
const RequirementsPath = ".deepseek/requirements.toml"

RequirementsPath is the project-relative location of the admin policy floor.

Variables

View Source
var ErrNoAPIKey = errors.New("no api key found for provider")

ErrNoAPIKey is returned by ResolveSecret / ResolveSecretWithSource when no API key can be found (no explicit key, the env var is unset, and the secrets file does not contain an entry for the provider). It is distinct from I/O errors such as bad file permissions or a TOML parse failure.

View Source
var ErrSecretsPermsTooOpen = errors.New("secrets file is not 0600; refusing to load (chmod 600 the file)")

Functions

func CheckSecretsFilePermissions

func CheckSecretsFilePermissions() error

func IsLegacyDeepSeekAlias added in v0.3.4

func IsLegacyDeepSeekAlias(model string) bool

IsLegacyDeepSeekAlias reports whether model is a legacy alias scheduled for retirement on 2026-07-24.

func IsOfficialDeepSeekV4Model added in v0.3.4

func IsOfficialDeepSeekV4Model(model string) bool

IsOfficialDeepSeekV4Model reports whether model is one of the two official DeepSeek V4 models (flash or pro).

func ProjectStateDir

func ProjectStateDir() string

ProjectStateDir returns the local ./.deepseek dir (snapshots, last_session).

func ResolveSecret

func ResolveSecret(p ProviderConfigTOML) (apiKey string, err error)

func SaveThemePreference added in v0.3.2

func SaveThemePreference(name string) error

SaveThemePreference writes the given theme name to [ui].theme in the state overlay file, preserving any other keys already present. Creates the file and parent directory if needed. Returns an error if no home directory is available or the write fails.

func SecretsPath

func SecretsPath() string

func StatePath added in v0.3.2

func StatePath() string

StatePath returns the path to the machine-managed state overlay file (~/.deepseek/state.toml), or "" if no home directory is available.

func UserConfigDir

func UserConfigDir() string

UserConfigDir returns ~/.deepseek (or "" if no home).

Types

type APIConfig

type APIConfig struct {
	Key                 string `toml:"key"`
	BaseURL             string `toml:"base_url"`
	UserID              string `toml:"user_id"`
	FirstTokenTimeoutMs int    `toml:"first_token_timeout_ms"`
	ChunkStallTimeoutMs int    `toml:"chunk_stall_timeout_ms"`
}

type ActiveConfig

type ActiveConfig struct {
	Provider string `toml:"provider"`
}

type CacheConfig added in v0.4.1

type CacheConfig struct {
	// AlignUnit is the measured DeepSeek cache block size in tokens.
	// When non-zero, the prefix assembler pads messages so they end on
	// an AlignUnit boundary, maximising cache hit rate. 128 is
	// empirically measured (bench/cmd/cacheprobe; docs/pricing.md) but
	// the hit-rate benefit is not yet validated by the head-to-head
	// benchmark — default off until proven. Set to 128 to opt in.
	AlignUnit int `toml:"align_unit"`
	// FIMFastPath enables a gated, conservative Fill-In-the-Middle
	// cheap-edit path for small single-hunk edits. Default false (off).
	FIMFastPath bool `toml:"fim_fastpath"`
}

CacheConfig controls prompt-cache alignment and compaction behaviour. All fields default to the zero value (off), so omitting the [cache] section preserves today's behaviour exactly.

type ClarifyConfig added in v0.4.0

type ClarifyConfig struct {
	// AutoClarify asks one clarifying question on an under-specified prompt
	// before spending a (possibly pro/max) model turn. Default false (opt-in).
	AutoClarify bool `toml:"auto_clarify"`
}

ClarifyConfig exposes the intent-clarify gate (internal/routing.NeedsClarification).

type Config

type Config struct {
	API         APIConfig                     `toml:"api"`
	Defaults    DefaultsConfig                `toml:"defaults"`
	Tools       ToolsConfig                   `toml:"tools"`
	Duet        DuetConfig                    `toml:"duet"`
	Permissions PermissionsConfig             `toml:"permissions"`
	Sessions    SessionsConfig                `toml:"sessions"`
	Hooks       []HookItemConfig              `toml:"hooks"`
	MCPServers  map[string]MCPServerConfig    `toml:"mcp_servers"`
	Web         WebConfig                     `toml:"web"`
	Sandbox     SandboxConfig                 `toml:"sandbox"`
	Network     NetworkConfig                 `toml:"network"`
	Active      ActiveConfig                  `toml:"active"`
	Providers   map[string]ProviderConfigTOML `toml:"providers"`
	UI          UIConfig                      `toml:"ui"`
	Routing     RoutingConfig                 `toml:"routing"`
	Clarify     ClarifyConfig                 `toml:"clarify"`
	Cache       CacheConfig                   `toml:"cache"`

	LegacyAPIUsed         bool `toml:"-"`
	DefaultsModelExplicit bool `toml:"-"`
	// contains filtered or unexported fields
}

Config is the full configuration tree. Keep it flat per concern.

func Default

func Default() Config

Default returns a Config populated with v0.1 defaults. Callers then layer user/project config + CLI flags on top.

func Load

func Load() (Config, error)

Load reads user + project config and overlays them onto defaults. Missing files are not errors; malformed files are.

func (Config) ActiveMCPServers added in v0.4.0

func (c Config) ActiveMCPServers() map[string]MCPServerConfig

ActiveMCPServers returns the subset of MCPServers that are not Disabled, so the runtime bridge and doctor connect only enabled servers. The result is a new map.

func (Config) Validate

func (c Config) Validate() error

Validate checks invariants. Call after Load + any CLI overrides.

type DefaultsConfig

type DefaultsConfig struct {
	Model           string `toml:"model"`
	Thinking        bool   `toml:"thinking"`
	ReasoningEffort string `toml:"reasoning_effort"`
	Theme           string `toml:"theme"`
	VimKeybindings  bool   `toml:"vim_keybindings"`
	// AutoReasoning enables per-turn thinking selection based on the
	// user's last message. When true, SelectThinking decides whether
	// to enable/disable thinking each turn using keyword heuristics.
	// Default: false (opt-in).
	AutoReasoning bool `toml:"auto_reasoning"`
}

type DuetConfig

type DuetConfig struct {
	Enabled            bool     `toml:"enabled"`
	RetryOnFailure     bool     `toml:"retry_on_failure"`
	ValidatorTimeoutMs int      `toml:"validator_timeout_ms"`
	ExtraDestructive   []string `toml:"extra_destructive_patterns"`
}

type HookItemConfig

type HookItemConfig struct {
	Event   string `toml:"event"`   // PreToolUse, PostToolUse, PostToolUseFailure, SessionStart, SessionEnd
	Type    string `toml:"type"`    // "subprocess" | "builtin"
	Command string `toml:"command"` // when type == subprocess
	Name    string `toml:"name"`    // when type == builtin
	Timeout int    `toml:"timeout_seconds"`
}

type MCPServerConfig

type MCPServerConfig struct {
	Transport      string            `toml:"transport"` // "stdio" (default) | "sse" | "http" | "streamable-http"
	URL            string            `toml:"url"`       // required when transport="sse"
	Command        string            `toml:"command"`   // required when transport="stdio"
	Args           []string          `toml:"args"`
	Env            map[string]string `toml:"env"`
	TimeoutSeconds int               `toml:"timeout_seconds"`
	EnabledTools   []string          `toml:"enabled_tools"`      // allowlist: only these tools exposed
	DisabledTools  []string          `toml:"disabled_tools"`     // blocklist: these tools hidden
	Disabled       bool              `toml:"disabled,omitempty"` // configured but not connected
}

type NetworkConfig added in v0.4.0

type NetworkConfig struct {
	// ProxyMode selects the proxy strategy: "auto" (platform default),
	// "env" (HTTPS_PROXY / NO_PROXY env vars), "custom" (explicit URL below),
	// "off" (bypass all proxies). Empty → "auto".
	ProxyMode string `toml:"proxy_mode"`
	// ProxyScheme is the scheme for the custom proxy: "http", "https",
	// "socks5", or "socks5h". Only used when ProxyMode == "custom".
	ProxyScheme string `toml:"proxy_scheme"`
	// ProxyURL is the host:port (no scheme) of the custom proxy.
	ProxyURL string `toml:"proxy_url"`
	// NoProxy is the comma-separated no-proxy list used when ProxyMode == "custom".
	NoProxy string `toml:"no_proxy"`
}

NetworkConfig controls outbound proxy settings for the gateway HTTP client.

type PermissionsConfig

type PermissionsConfig struct {
	AllowBash          []string    `toml:"allow_bash"`
	SecretPathPatterns []string    `toml:"secret_path_patterns"`
	Rules              RulesConfig `toml:"rules"`
	// Default is the autonomy/permission level selected during onboarding.
	// Accepted values: "ask", "auto", "full". Empty means "ask" (safest).
	Default string `toml:"default"`
}

type ProviderConfigTOML

type ProviderConfigTOML struct {
	Type                string `toml:"type"`
	BaseURL             string `toml:"base_url"`
	APIKey              string `toml:"api_key"`
	EnvVar              string `toml:"env_var"`
	SecretsFileKey      string `toml:"secrets_file_key"`
	FirstTokenTimeoutMs int    `toml:"first_token_timeout_ms"`
	ChunkStallTimeoutMs int    `toml:"chunk_stall_timeout_ms"`
	DefaultModel        string `toml:"default_model"`
}

type Requirements

type Requirements struct {
	// MaxMode is the most permissive permission mode the session may run in.
	// One of "plan", "read-only", "ask-all", "default", "yolo" (the same names
	// as the --yolo/--read-only/--ask-all flags and permission rulesets). Empty
	// means no ceiling on the mode.
	//
	// Danger ordering (least → most permissive): plan = read-only < ask-all <
	// default < yolo. The floor refuses any launch strictly more permissive than
	// MaxMode. So max_mode="default" forbids only yolo; max_mode="read-only"
	// forbids default/ask-all/yolo. Note max_mode="ask-all" ALSO forbids the
	// normal default tiered policy — ask-all gates every call through a human, so
	// it ranks as LESS permissive than default. The common admin floors are
	// "default" (ban yolo) and "read-only" (ban all writes).
	MaxMode string `toml:"max_mode"`

	// RequireSandbox refuses the launch when the OS sandbox is disabled.
	RequireSandbox bool `toml:"require_sandbox"`
}

Requirements is an optional, admin-controlled policy floor committed to a repo at .deepseek/requirements.toml. Unlike config.toml (user preferences, often per-machine and gitignored), it constrains the launch from ABOVE the CLI flags: a launch more permissive than the floor is REFUSED outright, never silently clamped, so a repo can forbid `dsc --yolo` regardless of the user's flags or personal config.

Absent file → no floor (the mechanism is opt-in). A malformed file is an error: an admin who wrote a floor should learn it is broken rather than have it silently ignored and fail open.

func LoadRequirements

func LoadRequirements(cwd string) (*Requirements, error)

LoadRequirements reads .deepseek/requirements.toml under cwd. It returns (nil, nil) when the file is absent (the floor is opt-in) and an error when it exists but cannot be read or parsed.

func (Requirements) IsZero

func (r Requirements) IsZero() bool

IsZero reports whether the floor imposes no constraints (so callers can treat an all-default file the same as an absent one).

type RoutingConfig added in v0.4.0

type RoutingConfig struct {
	// AutoRoute enables Flash-first routing: mechanical turns stay on the
	// cheap model + Non-think; reasoning/ambiguity/repeated-repair turns
	// escalate to EscalationModel at high/max effort. Default false (opt-in).
	AutoRoute bool `toml:"auto_route"`
	// EscalationModel is the pro-tier model AutoRoute escalates to. When
	// AutoRoute is true and this is empty, the wiring layer defaults it to
	// deepseek-v4-pro so escalation is actually reachable.
	EscalationModel string `toml:"escalation_model"`
}

RoutingConfig exposes the per-turn cost-aware router (internal/routing). All fields default to the zero value (off), so omitting the [routing] section preserves today's behavior exactly.

type RuleItemConfig

type RuleItemConfig struct {
	Tool string `toml:"tool"`
	Args string `toml:"args"`
}

type RulesConfig

type RulesConfig struct {
	Allow []RuleItemConfig `toml:"allow"`
	Deny  []RuleItemConfig `toml:"deny"`
	Ask   []RuleItemConfig `toml:"ask"`
}

type SandboxConfig

type SandboxConfig struct {
	Enabled         bool     `toml:"enabled"`
	AllowReadPaths  []string `toml:"allow_read_paths"`
	AllowWritePaths []string `toml:"allow_write_paths"`
	AllowNetwork    bool     `toml:"allow_network"`
}

SandboxConfig controls optional OS-native sandboxing for shell tools.

type SecretSource

type SecretSource string
const (
	SecretSourceExplicit SecretSource = "explicit"
	SecretSourceEnv      SecretSource = "env"
	SecretSourceFile     SecretSource = "file"
)

func ResolveSecretWithSource

func ResolveSecretWithSource(p ProviderConfigTOML) (apiKey string, source SecretSource, err error)

type SessionsConfig

type SessionsConfig struct {
	TTLDays       int `toml:"ttl_days"`
	SnapshotKeep  int `toml:"snapshot_keep"`
	AutoResumeAge int `toml:"auto_resume_age_hours"`
}

type State added in v0.3.2

type State struct {
	UI struct {
		Theme string `toml:"theme"`
	} `toml:"ui"`
}

State is the machine-managed state overlay. Only [ui].theme is managed today; unknown keys are preserved on write so future fields survive.

func LoadState added in v0.3.2

func LoadState() (State, error)

LoadState reads the state overlay file. A missing file returns a zero State with nil error (no overlay). A malformed file returns the decode error — callers should treat this as "no overlay" and continue.

type ToolsConfig

type ToolsConfig struct {
	MaxReadBytes  int64 `toml:"max_read_bytes"`  // default 5_242_880 (5 MiB)
	MaxWriteBytes int64 `toml:"max_write_bytes"` // default 5_242_880 (5 MiB)
}

type UIConfig added in v0.3.0

type UIConfig struct {
	// TransparentBackground, when true, degrades the bg-tier panels (tool
	// results, diffs, reasoning) to left-bars / separators with no opaque
	// fills — a fully flat / fg-only look. The full-screen canvas is not
	// painted in either case (it bled through glamour/viewport ANSI resets;
	// see docs/adr/0002), so this is a "no backgrounds at all" toggle.
	// Default false (panels render their fills).
	TransparentBackground bool `toml:"transparent_background"`
	// Language overrides the UI message language for API errors. "" or "auto"
	// inspects LC_ALL/LC_MESSAGES/LANG; "en" forces English; "zh" forces Chinese.
	Language string `toml:"language"`
	// Accent is the colour accent token (e.g. "indigo", "terracotta") used by
	// the desktop SPA's ThemeProvider. Persisted so the Appearance section
	// round-trips correctly. Empty means "use the theme default".
	Accent string `toml:"accent"`
	// Density is the layout density token ("comfortable" | "compact") used by
	// the desktop SPA. Persisted so the Appearance section round-trips.
	// Empty means "use the theme default".
	Density string `toml:"density"`
}

UIConfig holds presentational TUI options. Purely cosmetic — nothing here touches the wire / prompt-cache path.

type ValidationError

type ValidationError struct {
	Path    string // e.g. "mcp_servers[myserver].command"
	Message string
}

ValidationError describes a single config validation problem.

func ValidateStrict

func ValidateStrict(c *Config) []ValidationError

ValidateStrict checks the full config tree for structural errors that Validate (the lightweight startup check) does not catch. Returns an empty slice when the config is sound.

func (ValidationError) Error

func (e ValidationError) Error() string

type WebConfig

type WebConfig struct {
	Enabled        bool   `toml:"enabled"`
	SearchProvider string `toml:"search_provider"`
	SearXNGBaseURL string `toml:"searxng_base_url"`
	AllowPrivate   bool   `toml:"allow_private"`
}

WebConfig configures web fetch and search tools.

Jump to

Keyboard shortcuts

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