config

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func LoadClaudeMD

func LoadClaudeMD(projectRoot string, filesystem *FS) (string, error)

LoadClaudeMD loads ./CLAUDE.md and expands @include directives.

Claude Code supports including additional files by placing "@path/to/file" lines inside CLAUDE.md. This loader replaces those lines with the referenced file content (recursively).

Missing CLAUDE.md returns ("", nil).

func ValidateSettings

func ValidateSettings(s *Settings) error

ValidateSettings checks the merged Settings structure for logical consistency. Aggregates all failures using errors.Join so callers can surface every issue at once.

Types

type BashOutputConfig

type BashOutputConfig struct {
	SyncThresholdBytes  *int `json:"syncThresholdBytes,omitempty"`  // Spool sync output to disk after exceeding this many bytes.
	AsyncThresholdBytes *int `json:"asyncThresholdBytes,omitempty"` // Spool async output to disk after exceeding this many bytes.
}

BashOutputConfig configures when bash output is spooled to disk.

type FS

type FS struct {
	// contains filtered or unexported fields
}

FS 提供统一的文件系统访问接口,支持 OS 文件系统和嵌入 FS。 OS 优先:只有当 OS 操作失败时才会回退到嵌入 FS。

func NewFS

func NewFS(projectRoot string, embedFS fs.FS) *FS

NewFS 创建新的文件系统抽象层实例。

func (*FS) Open

func (f *FS) Open(path string) (fs.File, error)

Open 打开指定路径文件,OS 优先,失败时回退到嵌入 FS。

func (*FS) ReadDir

func (f *FS) ReadDir(path string) ([]fs.DirEntry, error)

ReadDir 读取目录内容,OS 优先,失败时回退到嵌入 FS。

func (*FS) ReadFile

func (f *FS) ReadFile(path string) ([]byte, error)

ReadFile 读取文件内容,OS 优先,失败时回退到嵌入 FS。

func (*FS) Stat

func (f *FS) Stat(path string) (fs.FileInfo, error)

Stat 返回文件信息,OS 优先,失败时回退到嵌入 FS。

func (*FS) WalkDir

func (f *FS) WalkDir(root string, fn fs.WalkDirFunc) error

WalkDir 遍历目录树,OS 优先,失败时回退到嵌入 FS。

type HookDefinition

type HookDefinition struct {
	Type          string `json:"type"`                    // "command" (default), "prompt", or "agent"
	Command       string `json:"command,omitempty"`       // Shell command (type=command)
	Prompt        string `json:"prompt,omitempty"`        // LLM prompt (type=prompt)
	Model         string `json:"model,omitempty"`         // Model override (type=prompt/agent)
	Timeout       int    `json:"timeout,omitempty"`       // Per-hook timeout in seconds (0 = use default)
	Async         bool   `json:"async,omitempty"`         // Fire-and-forget execution
	Once          bool   `json:"once,omitempty"`          // Execute only once per session
	StatusMessage string `json:"statusMessage,omitempty"` // Status message shown during execution
}

HookDefinition describes a single hook action bound to a matcher entry. Supports command (shell), prompt (LLM), and agent hook types per the Claude Code spec.

type HookMatcherEntry

type HookMatcherEntry struct {
	Matcher string           `json:"matcher"`
	Hooks   []HookDefinition `json:"hooks"`
}

HookMatcherEntry pairs a matcher pattern with one or more hook definitions.

type HooksConfig

type HooksConfig struct {
	PreToolUse         []HookMatcherEntry `json:"PreToolUse,omitempty"`
	PostToolUse        []HookMatcherEntry `json:"PostToolUse,omitempty"`
	PostToolUseFailure []HookMatcherEntry `json:"PostToolUseFailure,omitempty"`
	PermissionRequest  []HookMatcherEntry `json:"PermissionRequest,omitempty"`
	SessionStart       []HookMatcherEntry `json:"SessionStart,omitempty"`
	SessionEnd         []HookMatcherEntry `json:"SessionEnd,omitempty"`
	SubagentStart      []HookMatcherEntry `json:"SubagentStart,omitempty"`
	SubagentStop       []HookMatcherEntry `json:"SubagentStop,omitempty"`
	Stop               []HookMatcherEntry `json:"Stop,omitempty"`
	Notification       []HookMatcherEntry `json:"Notification,omitempty"`
	UserPromptSubmit   []HookMatcherEntry `json:"UserPromptSubmit,omitempty"`
	PreCompact         []HookMatcherEntry `json:"PreCompact,omitempty"`
}

HooksConfig maps event types to matcher entries. For tool-related events the matcher is applied to the tool name; for session events it matches source/reason; for notification it matches type; for subagent events it matches agent type.

Supports both Claude Code official format (array of HookMatcherEntry) and SDK simplified format (map[string]string) via custom UnmarshalJSON.

func (*HooksConfig) UnmarshalJSON

func (h *HooksConfig) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom unmarshaling for HooksConfig to support both: 1. Claude Code official format (array): {"PostToolUse": [{"matcher": "pattern", "hooks": [...]}]} 2. SDK simplified format (map): {"PostToolUse": {"tool-name": "command"}}

func (*HooksConfig) Validate

func (h *HooksConfig) Validate() error

Validate ensures hook maps contain non-empty commands.

type MCPConfig

type MCPConfig struct {
	Servers map[string]MCPServerConfig `json:"servers,omitempty"`
}

MCPConfig nests Model Context Protocol server definitions.

type MCPServerConfig

type MCPServerConfig struct {
	Type               string            `json:"type"`              // stdio/http/sse
	Command            string            `json:"command,omitempty"` // for stdio
	Args               []string          `json:"args,omitempty"`
	URL                string            `json:"url,omitempty"` // for http/sse
	Env                map[string]string `json:"env,omitempty"`
	Headers            map[string]string `json:"headers,omitempty"`
	TimeoutSeconds     int               `json:"timeoutSeconds,omitempty"`     // optional connect/list timeout
	EnabledTools       []string          `json:"enabledTools,omitempty"`       // optional remote tool allowlist
	DisabledTools      []string          `json:"disabledTools,omitempty"`      // optional remote tool denylist
	ToolTimeoutSeconds int               `json:"toolTimeoutSeconds,omitempty"` // optional timeout for each MCP tool call
}

MCPServerConfig describes how to reach an MCP server.

type MCPServerRule

type MCPServerRule struct {
	ServerName string `json:"serverName,omitempty"` // Name of the MCP server as declared in .mcp.json.
	URL        string `json:"url,omitempty"`        // Optional URL/endpoint to further pin the server.
}

MCPServerRule constrains which MCP servers can be enabled.

func (MCPServerRule) Validate

func (r MCPServerRule) Validate() error

Validate enforces presence of a server name.

type PermissionsConfig

type PermissionsConfig struct {
	Allow                        []string `json:"allow,omitempty"`                        // Rules that auto-allow tool use.
	Ask                          []string `json:"ask,omitempty"`                          // Rules that require confirmation.
	Deny                         []string `json:"deny,omitempty"`                         // Rules that block tool use.
	AdditionalDirectories        []string `json:"additionalDirectories,omitempty"`        // Extra working directories Claude may access.
	DefaultMode                  string   `json:"defaultMode,omitempty"`                  // Default permission mode when opening Claude Code.
	DisableBypassPermissionsMode string   `json:"disableBypassPermissionsMode,omitempty"` // Set to "disable" to forbid bypassPermissions mode.
}

PermissionsConfig defines per-tool permission rules.

func (*PermissionsConfig) Validate

func (p *PermissionsConfig) Validate() error

Validate ensures permission modes and toggles are within allowed values.

type Rule

type Rule struct {
	Name     string // 文件名(不含扩展名)
	Content  string // 规则内容
	Priority int    // 优先级(从文件名前缀解析,如 01-xxx.md -> 1)
}

Rule represents a single project rule loaded from .claude/rules.

type RulesLoader

type RulesLoader struct {
	// contains filtered or unexported fields
}

RulesLoader loads markdown rules under .claude/rules and watches for changes.

func NewRulesLoader

func NewRulesLoader(projectRoot string) *RulesLoader

func NewRulesLoaderWithConfigRoot added in v0.1.1

func NewRulesLoaderWithConfigRoot(projectRoot, configRoot string) *RulesLoader

func (*RulesLoader) Close

func (l *RulesLoader) Close() error

func (*RulesLoader) GetContent

func (l *RulesLoader) GetContent() string

GetContent merges all loaded rule contents separated by double newlines.

func (*RulesLoader) LoadRules

func (l *RulesLoader) LoadRules() ([]Rule, error)

func (*RulesLoader) WatchChanges

func (l *RulesLoader) WatchChanges(callback func([]Rule)) error

WatchChanges starts watching the rules directory and reloads on changes. If the rules directory doesn't exist, this is a no-op.

type SandboxConfig

type SandboxConfig struct {
	Enabled                   *bool                 `json:"enabled,omitempty"`                   // Enable filesystem/network sandboxing for bash.
	AutoAllowBashIfSandboxed  *bool                 `json:"autoAllowBashIfSandboxed,omitempty"`  // Auto-approve bash commands when sandboxed.
	ExcludedCommands          []string              `json:"excludedCommands,omitempty"`          // Commands that must run outside the sandbox.
	AllowUnsandboxedCommands  *bool                 `json:"allowUnsandboxedCommands,omitempty"`  // Whether dangerouslyDisableSandbox escape hatch is allowed.
	EnableWeakerNestedSandbox *bool                 `json:"enableWeakerNestedSandbox,omitempty"` // Allow weaker sandbox for unprivileged Docker.
	Network                   *SandboxNetworkConfig `json:"network,omitempty"`                   // Network-level sandbox knobs.
}

SandboxConfig controls bash sandboxing.

func (*SandboxConfig) Validate

func (s *SandboxConfig) Validate() error

Validate checks sandbox and network constraints.

type SandboxNetworkConfig

type SandboxNetworkConfig struct {
	AllowUnixSockets  []string `json:"allowUnixSockets,omitempty"`  // Unix sockets exposed inside sandbox (SSH agent, docker socket).
	AllowLocalBinding *bool    `json:"allowLocalBinding,omitempty"` // Allow binding to localhost ports (macOS).
	HTTPProxyPort     *int     `json:"httpProxyPort,omitempty"`     // Port for custom HTTP proxy if bringing your own.
	SocksProxyPort    *int     `json:"socksProxyPort,omitempty"`    // Port for custom SOCKS5 proxy if bringing your own.
}

SandboxNetworkConfig tunes sandbox network access.

type Settings

type Settings struct {
	APIKeyHelper         string             `json:"apiKeyHelper,omitempty"`         // /bin/sh script that returns an API key for outbound model calls.
	CleanupPeriodDays    *int               `json:"cleanupPeriodDays,omitempty"`    // Days to retain chat history locally (default 30). Set to 0 to disable.
	CompanyAnnouncements []string           `json:"companyAnnouncements,omitempty"` // Startup announcements rotated randomly.
	Env                  map[string]string  `json:"env,omitempty"`                  // Environment variables applied to every session.
	IncludeCoAuthoredBy  *bool              `json:"includeCoAuthoredBy,omitempty"`  // Whether to append "co-authored-by Claude" to commits/PRs.
	Permissions          *PermissionsConfig `json:"permissions,omitempty"`          // Tool permission rules and defaults.
	DisallowedTools      []string           `json:"disallowedTools,omitempty"`      // Tool blacklist; disallowed tools are not registered.
	Hooks                *HooksConfig       `json:"hooks,omitempty"`                // Hook commands to run around tool execution.
	DisableAllHooks      *bool              `json:"disableAllHooks,omitempty"`      // Force-disable all hooks.
	Model                string             `json:"model,omitempty"`                // Override default model id.
	StatusLine           *StatusLineConfig  `json:"statusLine,omitempty"`           // Custom status line settings.
	OutputStyle          string             `json:"outputStyle,omitempty"`          // Optional named output style.
	MCP                  *MCPConfig         `json:"mcp,omitempty"`                  // MCP server definitions keyed by name.
	LegacyMCPServers     []string           `json:"mcpServers,omitempty"`           // Deprecated list format; kept for migration errors.
	ForceLoginMethod     string             `json:"forceLoginMethod,omitempty"`     // Restrict login to "claudeai" or "console".
	ForceLoginOrgUUID    string             `json:"forceLoginOrgUUID,omitempty"`    // Org UUID to auto-select during login when set.
	Sandbox              *SandboxConfig     `json:"sandbox,omitempty"`              // Bash sandbox configuration.
	BashOutput           *BashOutputConfig  `json:"bashOutput,omitempty"`           // Thresholds for spooling bash output to disk.
	ToolOutput           *ToolOutputConfig  `json:"toolOutput,omitempty"`           // Thresholds for persisting large tool outputs to disk.
	AllowedMcpServers    []MCPServerRule    `json:"allowedMcpServers,omitempty"`    // Managed allowlist of user-configurable MCP servers.
	DeniedMcpServers     []MCPServerRule    `json:"deniedMcpServers,omitempty"`     // Managed denylist of user-configurable MCP servers.
	AWSAuthRefresh       string             `json:"awsAuthRefresh,omitempty"`       // Script to refresh AWS SSO credentials.
	AWSCredentialExport  string             `json:"awsCredentialExport,omitempty"`  // Script that prints JSON AWS credentials.
	RespectGitignore     *bool              `json:"respectGitignore,omitempty"`     // Whether Glob/Grep tools should respect .gitignore patterns.
}

Settings models the full contents of .claude/settings.json. All optional booleans use *bool so nil means "unset" and caller defaults apply.

func GetDefaultSettings

func GetDefaultSettings() Settings

GetDefaultSettings returns Anthropic's documented defaults.

func MergeSettings

func MergeSettings(lower, higher *Settings) *Settings

MergeSettings deep-merges two Settings structs (lower <- higher) and returns a new instance. - Scalars: higher non-zero values override lower. - *bool / *int pointers: higher non-nil overrides lower. - Maps: merged per key with higher entries overriding. - []string: concatenated with de-duplication, preserving order. - Nested structs: merged recursively.

func (*Settings) Validate

func (s *Settings) Validate() error

Validate delegates to the new aggregated validator.

type SettingsLoader

type SettingsLoader struct {
	ProjectRoot      string
	ConfigRoot       string
	SettingsFiles    []string
	RuntimeOverrides *Settings
	FS               *FS
}

SettingsLoader composes settings using the simplified precedence model. Higher-priority layers override lower ones while preserving unspecified fields. Order (low -> high): defaults < project < local < runtime overrides.

func (*SettingsLoader) Load

func (l *SettingsLoader) Load() (*Settings, error)

Load resolves and merges settings across all layers.

type StatusLineConfig

type StatusLineConfig struct {
	Type            string `json:"type"`                      // "command" executes a script; "template" renders a string.
	Command         string `json:"command,omitempty"`         // Executable to run when Type=command.
	Template        string `json:"template,omitempty"`        // Text template when Type=template.
	IntervalSeconds int    `json:"intervalSeconds,omitempty"` // Optional refresh interval in seconds.
	TimeoutSeconds  int    `json:"timeoutSeconds,omitempty"`  // Optional timeout for the command run.
}

StatusLineConfig controls contextual status line rendering.

func (*StatusLineConfig) Validate

func (s *StatusLineConfig) Validate() error

Validate ensures status line config is coherent.

type ToolOutputConfig

type ToolOutputConfig struct {
	DefaultThresholdBytes int            `json:"defaultThresholdBytes,omitempty"` // Persist output to disk after exceeding this many bytes (0 = SDK default).
	PerToolThresholdBytes map[string]int `json:"perToolThresholdBytes,omitempty"` // Optional per-tool thresholds keyed by canonical tool name.
}

ToolOutputConfig configures when tool output is persisted to disk.

Jump to

Keyboard shortcuts

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