config

package
v2.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Package config defines Compa's configuration and loads and saves it. config.json holds the settings; .security.yml beside it holds the secrets (API keys, tokens and passwords), and COMPA_* environment variables override both.

Index

Constants

View Source
const (
	ReadFileModeBytes = "bytes"
	ReadFileModeLines = "lines"
)
View Source
const (
	ChannelWeb            = "web"
	ChannelWebClient      = "web_client"
	ChannelTelegram       = "telegram"
	ChannelDiscord        = "discord"
	ChannelFeishu         = "feishu"
	ChannelWeixin         = "weixin"
	ChannelWeCom          = "wecom"
	ChannelDingTalk       = "dingtalk"
	ChannelSlack          = "slack"
	ChannelMatrix         = "matrix"
	ChannelDeltaChat      = "deltachat"
	ChannelLINE           = "line"
	ChannelOneBot         = "onebot"
	ChannelQQ             = "qq"
	ChannelIRC            = "irc"
	ChannelVK             = "vk"
	ChannelMaixCam        = "maixcam"
	ChannelWhatsApp       = "whatsapp"
	ChannelWhatsAppNative = "whatsapp_native"
	ChannelTeamsWebHook   = "teams_webhook"
	ChannelMQTT           = "mqtt"
	ChannelSlackWebHook   = "slack_webhook"
)

Channel type constants — single source of truth for all channel type names.

View Source
const (
	// EnvHome overrides the base directory for all Compa data
	// (config, workspace, skills, auth store, …).
	// Default: ~/.compa
	EnvHome = "COMPA_HOME"

	// EnvConfig overrides the full path to the JSON config file.
	// Default: $COMPA_HOME/config.json
	EnvConfig = "COMPA_CONFIG"

	// EnvBuiltinSkills overrides the directory from which built-in
	// skills are loaded.
	// Default: a skills folder beside the executable, if there is one.
	EnvBuiltinSkills = "COMPA_BUILTIN_SKILLS"

	// EnvBinary overrides the path to the compa-kernel executable.
	// Used by the web shell when spawning the gateway subprocess.
	// Default: resolved from the same directory as the current executable.
	EnvBinary = "COMPA_BINARY"

	// EnvGatewayHost overrides the host address for the gateway server.
	// Default: "localhost"
	EnvGatewayHost = "COMPA_GATEWAY_HOST"
)

Runtime environment variable keys for Compa processes. These control the location of files and binaries at runtime and are read directly via os.Getenv / os.LookupEnv. All Compa-specific keys use the COMPA_ prefix. Reference these constants instead of inline string literals to keep all supported knobs visible in one place and to prevent typos.

View Source
const (
	ProviderAdapterOpenAICompatible    = "openai-compatible"
	ProviderAdapterAnthropicCompatible = "anthropic-compatible"
	// ProviderAdapterNative runs the llmgw-core provider the core registry
	// records for the instance's provider kind, such as Google, Azure
	// OpenAI, Bedrock or Ollama.
	ProviderAdapterNative = "native"
	// ProviderAdapterExtension reaches one provider an extension daemon
	// serves. Endpoint is the daemon's URL, Protocol the provider's primary
	// llmgw-core surface (a chat surface when it serves one, else any surface
	// core defines, such as audio_speech), the setting ExtensionSurfacesSetting
	// every surface the daemon lists for it, and ExtensionProviderSetting the
	// daemon's id of the provider.
	ProviderAdapterExtension = "extension"
)

Adapters of the provider instances Compa runs.

View Source
const (
	// ExtensionProviderSetting is the daemon's id of the provider.
	ExtensionProviderSetting = "extension_provider"
	// ExtensionCredentialSetting is what the provider needs: "none",
	// "token" or "oauth".
	ExtensionCredentialSetting = "extension_credential"
	// ExtensionCredentialKeySetting is the auth store key of a signed-in
	// provider's credential. Such a credential refreshes, so it is read per
	// request rather than through auth_connection_ref, which resolves once.
	ExtensionCredentialKeySetting = "extension_credential_key"
	// ExtensionDisplayNameSetting is the daemon's display name of the provider.
	ExtensionDisplayNameSetting = "display_name"
	// ExtensionSurfacesSetting lists the llmgw-core surfaces the daemon
	// serves for the provider, such as ["audio_speech"]. The instance's
	// core provider serves exactly these.
	ExtensionSurfacesSetting = "extension_surfaces"
)

Settings of an extension provider instance.

View Source
const (
	ExtensionSurfaceChatCompletions = "chat_completions"
	ExtensionSurfaceMessages        = "messages"
)

Chat surfaces of an extension instance's protocol, as llmgw-core names them. An extension instance's protocol may be any surface core defines, such as audio_speech for a speech-only daemon provider.

View Source
const (
	// DMPolicyPairing processes direct messages from senders in allow_from and
	// records any other sender as a pairing request for the owner to approve.
	DMPolicyPairing = "pairing"
	// DMPolicyAllowlist processes direct messages from senders in allow_from
	// only.
	DMPolicyAllowlist = "allowlist"
	// DMPolicyOpen processes direct messages from anyone.
	DMPolicyOpen = "open"
	// DMPolicyDisabled ignores direct messages.
	DMPolicyDisabled = "disabled"
)

Direct-message policies for channel_list.<name>.dm_policy.

View Source
const (
	// GroupPolicyAllowlist processes group messages from senders, or in
	// groups, listed in allow_from.
	GroupPolicyAllowlist = "allowlist"
	// GroupPolicyOpen processes group messages from any member.
	GroupPolicyOpen = "open"
	// GroupPolicyDisabled ignores group messages.
	GroupPolicyDisabled = "disabled"
)

Group policies for channel_list.<name>.group_policy.

View Source
const (
	// WhatsAppChatsSelf takes input only from the owner's own "message
	// yourself" chat.
	WhatsAppChatsSelf = "self"
	// WhatsAppChatsAllowed adds the chats whose senders or groups the
	// channel's dm_policy and group_policy admit.
	WhatsAppChatsAllowed = "allowed"
	// WhatsAppChatsAll takes every chat as input and replies in it on the
	// owner's behalf.
	WhatsAppChatsAll = "all"
)

Values of channel_list.<whatsapp native>.settings.chats.

View Source
const (
	// MessageTargetsCurrentChat lets the message tool send only to the chat
	// the turn came from.
	MessageTargetsCurrentChat = "current_chat"
	// MessageTargetsAny lets the message tool send to any chat of any
	// connected channel.
	MessageTargetsAny = "any"
)

Values of tools.message.targets.

View Source
const (
	DefaultLogMaxSizeMB = 10
	DefaultLogMaxFiles  = 5
)

Defaults of the logging settings.

View Source
const DefaultGatewayLogLevel = "warn"
View Source
const DefaultMCPMaxInlineTextChars = 16 * 1024
View Source
const DefaultMaxMediaSize = 20 * 1024 * 1024 // 20 MB
View Source
const SecretPlaceholder = "[NOT_HERE]"

SecretPlaceholder stands, in config.json and any other JSON of the config, for a secret whose value is kept in .security.yml. Sent back in an edit, it keeps that value.

View Source
const (
	SecurityConfigFile = ".security.yml"
)

Variables

View Source
var (
	Version   = "dev" // Default value when not built with ldflags
	GitCommit string  // Git commit SHA (short)
	BuildTime string  // Build timestamp in RFC3339 format
	GoVersion string  // Go version used for building
)

Build-time variables injected via ldflags during build process. These are set by the Makefile or .goreleaser.yaml using the -X flag:

-X github.com/xibodev/compa/v2/pkg/config.Version=<version>
-X github.com/xibodev/compa/v2/pkg/config.GitCommit=<commit>
-X github.com/xibodev/compa/v2/pkg/config.BuildTime=<timestamp>
-X github.com/xibodev/compa/v2/pkg/config.GoVersion=<go-version>
View Source
var DefaultEventLoggingInclude = []string{"agent.*"}

DefaultEventLoggingInclude keeps the pre-existing behavior where agent events are printed, while non-agent runtime events are published for subscribers only.

Functions

func DiagnosticSummary

func DiagnosticSummary(err error) string

func EffectiveGatewayLogLevel

func EffectiveGatewayLogLevel(cfg *Config) string

EffectiveGatewayLogLevel returns the normalized runtime log level from a loaded config. Invalid or empty values fall back to the package default.

func EffectiveMCPTransportType

func EffectiveMCPTransportType(server MCPServerConfig) string

EffectiveMCPTransportType returns the normalized configured transport, or the inferred default when the config leaves Type empty.

func ExpandHome

func ExpandHome(path string) string

ExpandHome replaces a leading "~" with the user's home directory: "~" alone, "~/x" and "~\x" (the Windows form, accepted everywhere). Any other path, including "~user/x", is returned unchanged, as is every path when the home directory is unknown; a bare home directory is never substituted for a path it does not name.

func FormatBuildInfo

func FormatBuildInfo() (string, string)

FormatBuildInfo returns build time and go version info

func FormatVersion

func FormatVersion() string

FormatVersion returns the version string with optional git commit

func GetHome

func GetHome() string

GetHome returns the base directory for Compa's data: COMPA_HOME when set, otherwise ~/.compa. The launcher, gateway, agent and CLI all resolve it here, so they agree on where the data is.

func GetVersion

func GetVersion() string

GetVersion returns the version string

func InitChannelList

func InitChannelList(channels ChannelsConfig) error

InitChannelList validates and initializes all channels in the ChannelsConfig. It performs three steps:

  1. Validates that each channel has a non-empty Type
  2. Validates singleton constraints
  3. Decodes Settings into the correct typed struct based on Type, so that b.extend contains the actual settings (e.g., WebChatSettings)

After calling this method, callers can safely use b.extend via Decode() without re-parsing raw Settings.

func IsSingletonChannel

func IsSingletonChannel(channelType string) bool

IsSingletonChannel returns true if the channel type only allows one instance.

func MakeBackup

func MakeBackup(path string) error

func NormalizeMCPTransportType

func NormalizeMCPTransportType(transport string) string

NormalizeMCPTransportType canonicalizes MCP transport names used in config. "http" is Compa's streamable HTTP request-response mode, and "streamable-http" is accepted as an explicit alias for the same transport.

func RegisterChannelSettings

func RegisterChannelSettings(channelType string, prototype any)

RegisterChannelSettings registers a settings struct prototype for a custom channel type. External packages (out-of-tree channels registered via channels.RegisterFactory) call this from an init() so their channel type passes config validation (isValidChannelType) and its settings block decodes into the right struct (newChannelSettings). The prototype must be a struct value, e.g. RegisterChannelSettings("my_channel", MyChannelSettings{}).

func RegisterSensitiveValuesSource

func RegisterSensitiveValuesSource(values func() []string) (unregister func())

RegisterSensitiveValuesSource adds a source of secrets that live outside the config, such as the credentials in the auth store. FilterSensitiveData consults every source on each call, so a secret stored after the config was loaded is filtered too; a source should therefore be cheap. The returned function unregisters the source.

func ResetToDefaults

func ResetToDefaults(configPath string) error

ResetToDefaults backs up the current config, creates a default config, preserves security credentials from the existing config, and saves it.

func ResolveGatewayLogLevel

func ResolveGatewayLogLevel(path string) string

ResolveGatewayLogLevel reads the configured gateway log level without triggering the full config loader, so startup code can apply logging before config load logs run. The COMPA_LOG_LEVEL environment variable overrides the file value.

func SaveConfig

func SaveConfig(path string, cfg *Config) error

SaveConfig writes cfg to config.json at path and its secrets to .security.yml beside it, in the current format with every setting explicit. A setting the environment overrode when cfg was loaded keeps the value the files held, unless it was changed since. cfg itself is not modified.

Every process that saves the config (launcher, CLI, onboarding, kernel) takes the lock beside config.json, and the two files are replaced together: a save that fails leaves the previous pair (see writeFilePair).

func SupportedProviderInstanceAdapter

func SupportedProviderInstanceAdapter(instance *ProviderInstanceConfig) error

SupportedProviderInstanceAdapter returns an error for an instance whose adapter Compa does not run. Compa reaches every provider through an llmgw-core provider: an OpenAI- or Anthropic-compatible endpoint, the native provider of its kind, or an extension daemon; an extension instance must name the daemon's provider, and its protocol and listed surfaces must be surfaces llmgw-core defines (chat or not, such as audio_speech).

func ValidThinkingLevel

func ValidThinkingLevel(level string) bool

ValidThinkingLevel reports whether level is an extended-thinking level the agent understands, ignoring case and surrounding space. Empty is not a level.

func ValidateSelectionSyntax

func ValidateSelectionSyntax(s string) error

ValidateSelectionSyntax checks that s can name a model: empty, an exact target, or a model route name. It checks syntax only. Whether the target's instance, model or the route exists is checked when a selection is set and when it is resolved, so a dangling selection never makes a config unloadable.

func ValidateSourceRoot

func ValidateSourceRoot(name, path string) error

ValidateSourceRoot checks the shape of one source root: a usable name and an absolute path. It does not touch the filesystem. The error states only what is wrong; the caller says where the entry came from.

func WithFileLock

func WithFileLock(path string, fn func() error) error

WithFileLock runs fn while holding an exclusive OS lock tied to path, so the processes that write path (the launcher, the CLI, onboarding and the kernel) take turns. The lock is on a sidecar file, path+".flock", because path is replaced by rename, which would drop a lock held on it. The OS releases the lock if its holder dies. fn must not take the same lock again.

Types

type AgentConfig

type AgentConfig struct {
	ID        string           `json:"id"`
	Default   bool             `json:"default,omitempty"`
	Name      string           `json:"name,omitempty"`
	Workspace string           `json:"workspace,omitempty"`
	Model     string           `json:"model,omitempty"` // model selection: exact target "instance-id/model-id" or route name; empty uses the default
	Skills    []string         `json:"skills,omitempty"`
	Subagents *SubagentsConfig `json:"subagents,omitempty"`
}

type AgentDefaults

type AgentDefaults struct {
	Workspace                 string             `json:"workspace"                        env:"COMPA_AGENTS_DEFAULTS_WORKSPACE"`
	RestrictToWorkspace       bool               `json:"restrict_to_workspace"            env:"COMPA_AGENTS_DEFAULTS_RESTRICT_TO_WORKSPACE"`
	AllowReadOutsideWorkspace bool               `json:"allow_read_outside_workspace"     env:"COMPA_AGENTS_DEFAULTS_ALLOW_READ_OUTSIDE_WORKSPACE"`
	ModelName                 string             `json:"model_name"                       env:"COMPA_AGENTS_DEFAULTS_MODEL_NAME"`  // default model selection: exact target "instance-id/model-id" or route name; empty means none
	ImageModel                string             `json:"image_model,omitempty"            env:"COMPA_AGENTS_DEFAULTS_IMAGE_MODEL"` // model selection turns carrying images are rerouted to; empty keeps the agent's model
	MaxTokens                 int                `json:"max_tokens"                       env:"COMPA_AGENTS_DEFAULTS_MAX_TOKENS"`
	ContextWindow             int                `json:"context_window,omitempty"         env:"COMPA_AGENTS_DEFAULTS_CONTEXT_WINDOW"`
	Temperature               *float64           `json:"temperature,omitempty"            env:"COMPA_AGENTS_DEFAULTS_TEMPERATURE"`
	MaxToolIterations         int                `json:"max_tool_iterations"              env:"COMPA_AGENTS_DEFAULTS_MAX_TOOL_ITERATIONS"`
	SummarizeMessageThreshold int                `json:"summarize_message_threshold"      env:"COMPA_AGENTS_DEFAULTS_SUMMARIZE_MESSAGE_THRESHOLD"`
	SummarizeTokenPercent     int                `json:"summarize_token_percent"          env:"COMPA_AGENTS_DEFAULTS_SUMMARIZE_TOKEN_PERCENT"`
	MaxMediaSize              int                `json:"max_media_size,omitempty"         env:"COMPA_AGENTS_DEFAULTS_MAX_MEDIA_SIZE"`
	Routing                   *RoutingConfig     `json:"routing,omitempty"`
	SteeringMode              string             `json:"steering_mode,omitempty"          env:"COMPA_AGENTS_DEFAULTS_STEERING_MODE"`      // "one-at-a-time" (default) or "all"
	MaxParallelTurns          int                `json:"max_parallel_turns,omitempty"     env:"COMPA_AGENTS_DEFAULTS_MAX_PARALLEL_TURNS"` // Max turns of different sessions at once (0 = default 4, 1 = sequential)
	SubTurn                   SubTurnConfig      `json:"subturn"`
	ToolFeedback              ToolFeedbackConfig `json:"tool_feedback,omitempty"`
	SplitOnMarker             bool               `json:"split_on_marker"                  env:"COMPA_AGENTS_DEFAULTS_SPLIT_ON_MARKER"` // split messages on <|[SPLIT]|> marker
	ContextManager            string             `json:"context_manager,omitempty"        env:"COMPA_AGENTS_DEFAULTS_CONTEXT_MANAGER"`
	ContextManagerConfig      json.RawMessage    `json:"context_manager_config,omitempty" env:"COMPA_AGENTS_DEFAULTS_CONTEXT_MANAGER_CONFIG"`
	TurnProfile               TurnProfileConfig  `json:"turn_profile,omitempty"`
	MaxLLMRetries             int                `json:"max_llm_retries,omitempty"        env:"COMPA_AGENTS_DEFAULTS_MAX_LLM_RETRIES"`
	LLMRetryBackoffSecs       int                `json:"llm_retry_backoff_secs,omitempty" env:"COMPA_AGENTS_DEFAULTS_LLM_RETRY_BACKOFF_SECS"`
}

func (*AgentDefaults) GetMaxMediaSize

func (d *AgentDefaults) GetMaxMediaSize() int

func (*AgentDefaults) GetModelName

func (d *AgentDefaults) GetModelName() string

GetModelName returns the default model selection: an exact target "instance-id/model-id", a model route name, or "" when there is none.

func (*AgentDefaults) GetToolFeedbackMaxArgsLength

func (d *AgentDefaults) GetToolFeedbackMaxArgsLength() int

GetToolFeedbackMaxArgsLength returns the max visible text length for tool argument previews.

func (*AgentDefaults) IsToolFeedbackEnabled

func (d *AgentDefaults) IsToolFeedbackEnabled() bool

IsToolFeedbackEnabled returns true when tool feedback messages should be sent to the chat.

func (*AgentDefaults) IsToolFeedbackSeparateMessagesEnabled

func (d *AgentDefaults) IsToolFeedbackSeparateMessagesEnabled() bool

IsToolFeedbackSeparateMessagesEnabled returns true when each tool feedback update should be sent as its own chat message instead of editing a single in-place progress message.

func (*AgentDefaults) ResolveTurnProfile

func (d *AgentDefaults) ResolveTurnProfile() (EffectiveTurnProfile, bool, error)

type AgentsConfig

type AgentsConfig struct {
	Defaults AgentDefaults   `json:"defaults"`
	List     []AgentConfig   `json:"list,omitempty"`
	Dispatch *DispatchConfig `json:"dispatch,omitempty"`
}

type BaiduSearchConfig

type BaiduSearchConfig struct {
	Enabled    bool         `json:"enabled"          yaml:"-"                 env:"COMPA_TOOLS_WEB_BAIDU_ENABLED"`
	APIKey     SecureString `json:"api_key,omitzero" yaml:"api_key,omitempty" env:"COMPA_TOOLS_WEB_BAIDU_API_KEY"`
	BaseURL    string       `json:"base_url"         yaml:"-"                 env:"COMPA_TOOLS_WEB_BAIDU_BASE_URL"`
	MaxResults int          `json:"max_results"      yaml:"-"                 env:"COMPA_TOOLS_WEB_BAIDU_MAX_RESULTS"`
}

type BraveConfig

type BraveConfig struct {
	Enabled    bool          `json:"enabled"           yaml:"-"                  env:"COMPA_TOOLS_WEB_BRAVE_ENABLED"`
	APIKeys    SecureStrings `json:"api_keys,omitzero" yaml:"api_keys,omitempty" env:"COMPA_TOOLS_WEB_BRAVE_API_KEYS"`
	MaxResults int           `json:"max_results"       yaml:"-"                  env:"COMPA_TOOLS_WEB_BRAVE_MAX_RESULTS"`
}

func (*BraveConfig) APIKey

func (c *BraveConfig) APIKey() string

APIKey returns the Brave API key

func (*BraveConfig) SetAPIKey

func (c *BraveConfig) SetAPIKey(key string)

SetAPIKey sets the Brave API key

func (*BraveConfig) SetAPIKeys

func (c *BraveConfig) SetAPIKeys(keys []string)

type BuildInfo

type BuildInfo struct {
	Version   string `json:"version"`
	GitCommit string `json:"git_commit"`
	BuildTime string `json:"build_time"`
	GoVersion string `json:"go_version"`
}

BuildInfo contains build-time version information

type BuiltinHookConfig

type BuiltinHookConfig struct {
	Enabled  bool            `json:"enabled"`
	Priority int             `json:"priority,omitempty"`
	Config   json.RawMessage `json:"config,omitempty"`
}

type Channel

type Channel struct {
	Enabled   bool                `json:"enabled"                 yaml:"-"`
	Type      string              `json:"type"                    yaml:"-"`
	AllowFrom FlexibleStringSlice `json:"allow_from,omitempty"    yaml:"-"`
	// DMPolicy decides which direct messages are processed: "pairing",
	// "allowlist", "open" or "disabled". See EffectiveDMPolicy.
	DMPolicy string `json:"dm_policy,omitempty" yaml:"-"`
	// GroupPolicy decides which group messages are processed: "allowlist",
	// "open" or "disabled". See EffectiveGroupPolicy.
	GroupPolicy        string             `json:"group_policy,omitempty"  yaml:"-"`
	ReasoningChannelID string             `json:"reasoning_channel_id"    yaml:"-"`
	GroupTrigger       GroupTriggerConfig `json:"group_trigger,omitempty" yaml:"-"`
	Typing             TypingConfig       `json:"typing,omitempty"        yaml:"-"`
	Placeholder        PlaceholderConfig  `json:"placeholder,omitempty"   yaml:"-"`
	Settings           RawNode            `json:"settings,omitzero"       yaml:"settings,omitempty"`
	// contains filtered or unexported fields
}

Channel defines the common fields shared by all channel types. Channel-specific settings go into Settings (nested format only). The settings struct should use SecureString/SecureStrings for sensitive fields.

Decode stores the settings pointer internally; subsequent modifications to the decoded struct are automatically reflected in MarshalJSON/MarshalYAML.

MarshalJSON outputs nested format (common fields at top level, settings as sub-key). MarshalYAML outputs only secure fields (for .security.yml).

Standard Go JSON/YAML unmarshaling handles nested format correctly:

  • JSON: {"enabled": true, "type": "telegram", "settings": {"base_url": "..."}}
  • YAML: settings: {token: xxx} (for .security.yml)

func (*Channel) AllowsEveryone

func (b *Channel) AllowsEveryone() bool

AllowsEveryone reports whether allow_from contains "*".

func (Channel) CollectSensitiveValues

func (b Channel) CollectSensitiveValues() []string

CollectSensitiveValues returns all sensitive string values from this Channel's decoded settings (extend). Used by the security filter system.

func (*Channel) Decode

func (b *Channel) Decode(target any) error

Decode decodes the Settings node into the given target struct and stores the pointer internally. Subsequent modifications to the target are automatically reflected in MarshalJSON/MarshalYAML (no explicit Encode needed).

func (*Channel) EffectiveDMPolicy

func (b *Channel) EffectiveDMPolicy() string

EffectiveDMPolicy returns the channel's direct-message policy. A channel without one derives it from allow_from: "*" opens it, entries make it an allowlist, and none pairs.

func (*Channel) EffectiveGroupPolicy

func (b *Channel) EffectiveGroupPolicy() string

EffectiveGroupPolicy returns the channel's group policy. A channel without one derives it from allow_from: "*" opens it, otherwise allow_from decides.

func (*Channel) GetDecoded

func (b *Channel) GetDecoded() (any, error)

GetDecoded returns the previously decoded settings struct. If Decode hasn't been called yet, it lazily decodes using the channel Type prototype. Returns an error if decoding fails; the decoded value (possibly nil) is still returned so callers can distinguish between "not decoded" and "decode failed".

func (*Channel) HasAllowEntries

func (b *Channel) HasAllowEntries() bool

HasAllowEntries reports whether allow_from names at least one sender or group, not counting "*".

func (Channel) MarshalJSON

func (b Channel) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for Channel. Outputs nested format: common fields at top level, channel-specific in "settings". Secure fields (SecureString/SecureStrings) are removed from settings output.

func (Channel) MarshalYAML

func (b Channel) MarshalYAML() (any, error)

MarshalYAML implements yaml.ValueMarshaler for Channel. Outputs only secure fields in the Settings YAML (for .security.yml). If Decode was called, it serializes from the stored extend (reflecting any modifications); otherwise falls back to decoding Settings via the channel Type to extract secure fields.

func (*Channel) Name

func (b *Channel) Name() string

Name returns the channel name.

func (*Channel) SetName

func (b *Channel) SetName(name string)

SetName sets the channel name.

func (*Channel) SetSecretField

func (b *Channel) SetSecretField(fieldName string, value SecureString)

SetSecretField sets a secure field value by field name in the Settings JSON. NOTE: This only operates on raw Settings. If Decode() has been called, prefer modifying the typed struct directly — MarshalJSON serializes from extend.

func (*Channel) SettingsIsEmpty

func (b *Channel) SettingsIsEmpty() bool

SettingsIsEmpty returns true if Settings has not been populated.

func (*Channel) UnmarshalYAML

func (b *Channel) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler for Channel. Merges the node's settings (settings: {...}) into the existing Channel.

type ChannelsConfig

type ChannelsConfig map[string]*Channel

ChannelsConfig maps channel name to its Channel configuration. Each Channel stores the full channel config in Settings and handles JSON/YAML serialization (removing/keeping secure fields automatically).

func (ChannelsConfig) Get

func (c ChannelsConfig) Get(name string) *Channel

Get returns the Channel for the given channel name (map key), or nil if not found.

func (ChannelsConfig) GetByType

func (c ChannelsConfig) GetByType(t string) *Channel

GetByType returns the Channel for the given channel type, or nil if not found.

func (ChannelsConfig) SetEnabled

func (c ChannelsConfig) SetEnabled(name string, enabled bool) bool

SetEnabled sets the Enabled field on the Channel with the given name. Returns false if no channel with that name exists.

func (*ChannelsConfig) UnmarshalJSON

func (c *ChannelsConfig) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for ChannelsConfig. Sets the channel name from the map key after unmarshaling.

func (*ChannelsConfig) UnmarshalYAML

func (c *ChannelsConfig) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler for ChannelsConfig. This ensures that when loading security.yml, existing Channel instances are properly merged rather than replaced with new ones.

type CommandsConfig

type CommandsConfig struct {
	// OwnerOnly runs commands sent from chat apps only when the sender is the
	// owner: a sender matching an explicit allow_from entry. The web UI and
	// the terminal are always the owner.
	OwnerOnly bool `json:"owner_only" env:"COMPA_COMMANDS_OWNER_ONLY"`
}

CommandsConfig configures the chat commands (/reload, /switch, ...).

type Config

type Config struct {
	Isolation IsolationConfig `json:"isolation,omitempty" yaml:"-"`
	Agents    AgentsConfig    `json:"agents"              yaml:"-"`
	Session   SessionConfig   `json:"session,omitempty"   yaml:"-"`
	Evolution EvolutionConfig `json:"evolution,omitempty" yaml:"-"`
	Channels  ChannelsConfig  `json:"channel_list"        yaml:"channel_list"`
	// ProviderInstances are the provider connections models run on; each
	// owns its endpoint, credential reference, runtime settings and model
	// catalog. ModelRoutes are named failover routes over their exact
	// targets, and every model selection in the config names a target or a
	// route. ActiveModels is the shortlist of targets offered for chat.
	ProviderInstances []*ProviderInstanceConfig `json:"provider_instances,omitempty" yaml:"-"`
	ModelRoutes       []*ModelRouteConfig       `json:"model_routes,omitempty"       yaml:"-"`
	ActiveModels      []string                  `json:"active_models,omitempty"      yaml:"-"`
	Gateway           GatewayConfig             `json:"gateway"             yaml:"-"`
	Events            EventsConfig              `json:"events,omitempty"    yaml:"-"`
	Hooks             HooksConfig               `json:"hooks,omitempty"     yaml:"-"`
	Tools             ToolsConfig               `json:"tools"               yaml:",inline"`
	Heartbeat         HeartbeatConfig           `json:"heartbeat"           yaml:"-"`
	Devices           DevicesConfig             `json:"devices"             yaml:"-"`
	Voice             VoiceConfig               `json:"voice"               yaml:"-"`
	// Commands configures who may run the chat commands.
	Commands CommandsConfig `json:"commands" yaml:"-"`
	// Logging configures Compa's log files.
	Logging LoggingConfig `json:"logging" yaml:"-"`
	// Modules configures the detached-module host, including the named
	// source roots a module may be granted read-only.
	Modules ModulesConfig `json:"modules,omitzero" yaml:"-"`
	// BuildInfo contains build-time version information
	BuildInfo BuildInfo `json:"build_info,omitempty" yaml:"-"`

	// Extension is the extension daemon Compa reaches providers through, if
	// any. Its shared secret lives in the auth store.
	Extension *ExtensionDaemonConfig `json:"extension,omitempty" yaml:"-"`
	// contains filtered or unexported fields
}

Config is Compa's configuration, as stored in config.json and .security.yml.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns the default configuration for Compa. It configures no provider instance and so selects no model; connecting a provider adds its instance and catalog.

func LoadConfig

func LoadConfig(path string) (*Config, error)

LoadConfig reads config.json at path, merges .security.yml beside it, applies the COMPA_* environment overrides and validates the result. A missing config.json, or one too short to hold a setting, yields the defaults, completed the same way. LoadConfig never writes either file.

func (*Config) FilterSensitiveData

func (c *Config) FilterSensitiveData(content string) string

FilterSensitiveData filters sensitive values from content before sending to LLM. This prevents the LLM from seeing its own credentials: the config's own secrets and every value a source registered with RegisterSensitiveValuesSource returns, consulted on each call. Short content (below FilterMinLength) is returned unchanged for performance.

func (*Config) InheritEnvOverrides

func (c *Config) InheritEnvOverrides(loaded *Config)

InheritEnvOverrides makes SaveConfig treat c's settings as overridden by the environment wherever loaded's were. A config rebuilt from a loaded one, for example decoded from its JSON, carries the environment's values but not the record of them; without this, saving it would write those values to the files.

func (*Config) MarshalJSON

func (c *Config) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for Config to omit the session section when it is empty.

func (*Config) SecurityCopyFrom

func (c *Config) SecurityCopyFrom(path string) error

SecurityCopyFrom fills c's secrets from the .security.yml beside path, as a config decoded from JSON, which never holds them, needs.

func (*Config) SensitiveDataReplacer

func (sec *Config) SensitiveDataReplacer() *strings.Replacer

SensitiveDataReplacer returns the replacer FilterSensitiveData applies. It replaces the config's own secrets and the registered sources' current values; the replacer is rebuilt only when those values change.

func (*Config) ValidateModelSelections

func (c *Config) ValidateModelSelections() error

ValidateModelSelections checks the syntax of every model selection and of the voice targets, which are exact targets. It does not check that they exist.

func (*Config) ValidateModules

func (c *Config) ValidateModules() error

ValidateModules checks the module host settings. Source roots are checked for shape only; see ModulesConfig.SourceRoots.

func (*Config) ValidateProviderInstances

func (c *Config) ValidateProviderInstances() error

ValidateProviderInstances checks every provider instance, including that Compa runs its adapter, and every model route's targets.

func (*Config) ValidateSettings

func (c *Config) ValidateSettings() error

ValidateSettings checks the enumerated settings outside the channels.

func (*Config) ValidateTurnProfile

func (c *Config) ValidateTurnProfile() error

func (*Config) WorkspacePath

func (c *Config) WorkspacePath() string

type CronToolsConfig

type CronToolsConfig struct {
	ToolConfig `envPrefix:"COMPA_TOOLS_CRON_"`
	// 0 means no timeout.
	ExecTimeoutMinutes    int      `json:"exec_timeout_minutes"    env:"COMPA_TOOLS_CRON_EXEC_TIMEOUT_MINUTES"`
	AllowCommand          bool     `json:"allow_command"           env:"COMPA_TOOLS_CRON_ALLOW_COMMAND"`
	CommandAllowedRemotes []string `json:"command_allowed_remotes" env:"COMPA_TOOLS_CRON_COMMAND_ALLOWED_REMOTES"`
}

type DeltaChatSettings

type DeltaChatSettings struct {
	Email          string       `json:"email"                     yaml:"-"                  env:"COMPA_CHANNELS_DELTACHAT_EMAIL"`
	Password       SecureString `json:"password,omitzero"         yaml:"password,omitempty" env:"COMPA_CHANNELS_DELTACHAT_PASSWORD"`
	DisplayName    string       `json:"display_name,omitempty"    yaml:"-"                  env:"COMPA_CHANNELS_DELTACHAT_DISPLAY_NAME"`
	AvatarImage    string       `json:"avatar_image,omitempty"    yaml:"-"                  env:"COMPA_CHANNELS_DELTACHAT_AVATAR_IMAGE"`
	DataDir        string       `json:"data_dir,omitempty"        yaml:"-"                  env:"COMPA_CHANNELS_DELTACHAT_DATA_DIR"`
	RPCServerPath  string       `json:"rpc_server_path,omitempty" yaml:"-"                  env:"COMPA_CHANNELS_DELTACHAT_RPC_SERVER_PATH"`
	InviteLink     string       `json:"invite_link,omitempty"     yaml:"-"                  env:"COMPA_CHANNELS_DELTACHAT_INVITE_LINK"`
	AllowCrosspost bool         `json:"allow_crosspost,omitempty" yaml:"-"                  env:"COMPA_CHANNELS_DELTACHAT_ALLOW_CROSSPOST"`
	IMAPServer     string       `json:"imap_server,omitempty"     yaml:"-"`
	IMAPPort       int          `json:"imap_port,omitempty"       yaml:"-"`
	SMTPServer     string       `json:"smtp_server,omitempty"     yaml:"-"`
	SMTPPort       int          `json:"smtp_port,omitempty"       yaml:"-"`
}

DeltaChatSettings configures the Delta Chat channel. Delta Chat is an email-based, end-to-end encrypted messenger; Compa talks to a local `deltachat-rpc-server` process over JSON-RPC (stdio).

Email is the only required setting. A full address selects an already configured account in DataDir; a first-run marker such as "@nine.testrun.org" creates a chatmail account and tells the user which full email to save. Mailbox credentials stay in the Delta Chat account store. DisplayName and AvatarImage are optional profile settings applied on startup. Password, with the optional IMAP/SMTP settings, is for an email account Compa configures itself rather than one already in the account store.

type DevicesConfig

type DevicesConfig struct {
	Enabled    bool `json:"enabled"     env:"COMPA_DEVICES_ENABLED"`
	MonitorUSB bool `json:"monitor_usb" env:"COMPA_DEVICES_MONITOR_USB"`
}

type DingTalkSettings

type DingTalkSettings struct {
	ClientID     string       `json:"client_id"              yaml:"-"                       env:"COMPA_CHANNELS_DINGTALK_CLIENT_ID"`
	ClientSecret SecureString `json:"client_secret,omitzero" yaml:"client_secret,omitempty" env:"COMPA_CHANNELS_DINGTALK_CLIENT_SECRET"`
}

type DiscordSettings

type DiscordSettings struct {
	Token SecureString `json:"token,omitzero" yaml:"token,omitempty" env:"COMPA_CHANNELS_DISCORD_TOKEN"`
	Proxy string       `json:"proxy"          yaml:"-"               env:"COMPA_CHANNELS_DISCORD_PROXY"`
}

type DispatchConfig

type DispatchConfig struct {
	Rules []DispatchRule `json:"rules,omitempty"`
}

type DispatchRule

type DispatchRule struct {
	Name              string           `json:"name,omitempty"`
	Agent             string           `json:"agent"`
	When              DispatchSelector `json:"when"`
	SessionDimensions []string         `json:"session_dimensions,omitempty"`
}

type DispatchSelector

type DispatchSelector struct {
	Channel   string `json:"channel,omitempty"`
	Account   string `json:"account,omitempty"`
	Space     string `json:"space,omitempty"`
	Chat      string `json:"chat,omitempty"`
	Topic     string `json:"topic,omitempty"`
	Sender    string `json:"sender,omitempty"`
	Mentioned *bool  `json:"mentioned,omitempty"`
}

type DuckDuckGoConfig

type DuckDuckGoConfig struct {
	Enabled    bool `json:"enabled"     env:"COMPA_TOOLS_WEB_DUCKDUCKGO_ENABLED"`
	MaxResults int  `json:"max_results" env:"COMPA_TOOLS_WEB_DUCKDUCKGO_MAX_RESULTS"`
}

type EffectiveTurnProfile

type EffectiveTurnProfile struct {
	Enabled          bool
	HistoryMode      TurnProfileMode
	SystemPromptMode TurnProfileMode
	SkillsMode       TurnProfileMode
	ToolsMode        TurnProfileMode
	AllowedSkills    []string
	AllowedTools     []string
}

type EventLoggingConfig

type EventLoggingConfig struct {
	// Enabled controls whether runtime events are printed by the built-in logger.
	Enabled bool `json:"enabled" env:"ENABLED"`
	// Include contains exact event kinds or glob patterns such as "agent.*" or "*".
	Include []string `json:"include,omitempty" env:"INCLUDE"`
	// Exclude contains exact event kinds or glob patterns to suppress after Include matches.
	Exclude []string `json:"exclude,omitempty" env:"EXCLUDE"`
	// MinSeverity filters out events below the configured severity: debug, info, warn, or error.
	MinSeverity string `json:"min_severity,omitempty" env:"MIN_SEVERITY"`
	// IncludePayload adds the raw payload to logs. Leave disabled unless detailed diagnostics are needed.
	IncludePayload bool `json:"include_payload,omitempty" env:"INCLUDE_PAYLOAD"`
}

EventLoggingConfig controls centralized runtime event logging.

func EffectiveEventLoggingConfig

func EffectiveEventLoggingConfig(cfg *Config) EventLoggingConfig

EffectiveEventLoggingConfig returns a logging config with stable defaults.

type EventsConfig

type EventsConfig struct {
	Logging EventLoggingConfig `json:"logging,omitempty" envPrefix:"COMPA_EVENTS_LOGGING_"`
}

EventsConfig groups runtime event configuration.

type EvolutionConfig

type EvolutionConfig struct {
	Enabled         bool     `json:"enabled,omitempty"`
	Mode            string   `json:"mode,omitempty"`
	StateDir        string   `json:"state_dir,omitempty"`
	MinTaskCount    int      `json:"min_task_count,omitempty"`
	MinSuccessRatio float64  `json:"min_success_ratio,omitempty"`
	ColdPathTrigger string   `json:"cold_path_trigger,omitempty"`
	ColdPathTimes   []string `json:"cold_path_times,omitempty"`
}

func (EvolutionConfig) AutoAppliesDrafts

func (c EvolutionConfig) AutoAppliesDrafts() bool

func (EvolutionConfig) ColdPathTriggerMode

func (c EvolutionConfig) ColdPathTriggerMode() string

func (EvolutionConfig) EffectiveColdPathTimes

func (c EvolutionConfig) EffectiveColdPathTimes() []string

func (EvolutionConfig) EffectiveMinSuccessRatio

func (c EvolutionConfig) EffectiveMinSuccessRatio() float64

func (EvolutionConfig) EffectiveMinTaskCount

func (c EvolutionConfig) EffectiveMinTaskCount() int

func (EvolutionConfig) EffectiveMode

func (c EvolutionConfig) EffectiveMode() string

func (EvolutionConfig) MarshalJSON

func (c EvolutionConfig) MarshalJSON() ([]byte, error)

func (EvolutionConfig) RunsColdPathAfterTurn

func (c EvolutionConfig) RunsColdPathAfterTurn() bool

func (EvolutionConfig) RunsColdPathAutomatically

func (c EvolutionConfig) RunsColdPathAutomatically() bool

func (EvolutionConfig) RunsColdPathScheduled

func (c EvolutionConfig) RunsColdPathScheduled() bool

type ExactModelTarget

type ExactModelTarget struct {
	InstanceID string
	ModelID    string
}

ExactModelTarget identifies one model owned by one configured provider instance. ModelID may contain additional slashes.

func ParseExactModelTarget

func ParseExactModelTarget(raw string) (ExactModelTarget, error)

func (ExactModelTarget) String

func (t ExactModelTarget) String() string

type ExecConfig

type ExecConfig struct {
	ToolConfig          `         envPrefix:"COMPA_TOOLS_EXEC_"`
	EnableDenyPatterns  bool     `                                 json:"enable_deny_patterns"  env:"COMPA_TOOLS_EXEC_ENABLE_DENY_PATTERNS"`
	AllowRemote         bool     `                                 json:"allow_remote"          env:"COMPA_TOOLS_EXEC_ALLOW_REMOTE"`
	CustomDenyPatterns  []string `                                 json:"custom_deny_patterns"  env:"COMPA_TOOLS_EXEC_CUSTOM_DENY_PATTERNS"`
	CustomAllowPatterns []string `                                 json:"custom_allow_patterns" env:"COMPA_TOOLS_EXEC_CUSTOM_ALLOW_PATTERNS"`
	TimeoutSeconds      int      `                                 json:"timeout_seconds"       env:"COMPA_TOOLS_EXEC_TIMEOUT_SECONDS"` // 0 means use default (60s)
}

type ExposePath

type ExposePath struct {
	Source string `json:"source"`
	Target string `json:"target,omitempty"`
	Mode   string `json:"mode"`
}

ExposePath describes a host path that should remain visible inside the isolated child-process environment. This is currently implemented on Linux only.

type ExtensionDaemonConfig

type ExtensionDaemonConfig struct {
	// URL is the daemon's origin, such as "http://127.0.0.1:18888".
	URL string `json:"url"`
}

ExtensionDaemonConfig locates the extension daemon.

type FeishuSettings

type FeishuSettings struct {
	AppID               string              `json:"app_id"                      yaml:"-"                            env:"COMPA_CHANNELS_FEISHU_APP_ID"`
	AppSecret           SecureString        `json:"app_secret,omitzero"         yaml:"app_secret,omitempty"         env:"COMPA_CHANNELS_FEISHU_APP_SECRET"`
	EncryptKey          SecureString        `json:"encrypt_key,omitzero"        yaml:"encrypt_key,omitempty"        env:"COMPA_CHANNELS_FEISHU_ENCRYPT_KEY"`
	VerificationToken   SecureString        `json:"verification_token,omitzero" yaml:"verification_token,omitempty" env:"COMPA_CHANNELS_FEISHU_VERIFICATION_TOKEN"`
	RandomReactionEmoji FlexibleStringSlice `json:"random_reaction_emoji"       yaml:"-"                            env:"COMPA_CHANNELS_FEISHU_RANDOM_REACTION_EMOJI"`
	IsLark              bool                `json:"is_lark"                     yaml:"-"                            env:"COMPA_CHANNELS_FEISHU_IS_LARK"`
}

type FlexibleStringSlice

type FlexibleStringSlice []string

FlexibleStringSlice is a []string that also accepts JSON numbers, so allow_from can contain both "123" and 123. It also supports parsing comma-separated strings from environment variables, including both English (,) and Chinese (,) commas.

func (*FlexibleStringSlice) UnmarshalJSON

func (f *FlexibleStringSlice) UnmarshalJSON(data []byte) error

func (*FlexibleStringSlice) UnmarshalText

func (f *FlexibleStringSlice) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler to support env variable parsing. It handles comma-separated values with both English (,) and Chinese (,) commas.

type GLMSearchConfig

type GLMSearchConfig struct {
	Enabled bool         `json:"enabled"          yaml:"-"                 env:"COMPA_TOOLS_WEB_GLM_ENABLED"`
	APIKey  SecureString `json:"api_key,omitzero" yaml:"api_key,omitempty" env:"COMPA_TOOLS_WEB_GLM_API_KEY"`
	BaseURL string       `json:"base_url"         yaml:"-"                 env:"COMPA_TOOLS_WEB_GLM_BASE_URL"`
	// SearchEngine specifies the search backend: "search_std" (default),
	// "search_pro", "search_pro_sogou", or "search_pro_quark".
	SearchEngine string `json:"search_engine" yaml:"-" env:"COMPA_TOOLS_WEB_GLM_SEARCH_ENGINE"`
	MaxResults   int    `json:"max_results"   yaml:"-" env:"COMPA_TOOLS_WEB_GLM_MAX_RESULTS"`
}

type GatewayConfig

type GatewayConfig struct {
	Host      string `json:"host"                env:"COMPA_GATEWAY_HOST"`
	Port      int    `json:"port"                env:"COMPA_GATEWAY_PORT"`
	HotReload bool   `json:"hot_reload"          env:"COMPA_GATEWAY_HOT_RELOAD"`
	LogLevel  string `json:"log_level,omitempty" env:"COMPA_LOG_LEVEL"`
}

type GeminiSearchConfig

type GeminiSearchConfig struct {
	Enabled    bool         `json:"enabled"          yaml:"-"                 env:"COMPA_TOOLS_WEB_GEMINI_ENABLED"`
	APIKey     SecureString `json:"api_key,omitzero" yaml:"api_key,omitempty" env:"COMPA_TOOLS_WEB_GEMINI_API_KEY"`
	Model      string       `json:"model"            yaml:"-"                 env:"COMPA_TOOLS_WEB_GEMINI_MODEL"`
	MaxResults int          `json:"max_results"      yaml:"-"                 env:"COMPA_TOOLS_WEB_GEMINI_MAX_RESULTS"`
}

type GroupTriggerConfig

type GroupTriggerConfig struct {
	// MentionOnly answers in groups only when the bot is mentioned. A channel
	// entry that leaves it out gets true (ChannelsConfig.UnmarshalJSON).
	MentionOnly bool     `json:"mention_only"`
	Prefixes    []string `json:"prefixes,omitempty"`
}

GroupTriggerConfig controls when the bot responds in group chats.

type HeartbeatConfig

type HeartbeatConfig struct {
	Enabled  bool `json:"enabled"  env:"COMPA_HEARTBEAT_ENABLED"`
	Interval int  `json:"interval" env:"COMPA_HEARTBEAT_INTERVAL"` // minutes, min 5
}

type HookDefaultsConfig

type HookDefaultsConfig struct {
	ObserverTimeoutMS    int `json:"observer_timeout_ms,omitempty"`
	InterceptorTimeoutMS int `json:"interceptor_timeout_ms,omitempty"`
	ApprovalTimeoutMS    int `json:"approval_timeout_ms,omitempty"`
}

type HooksConfig

type HooksConfig struct {
	Enabled   bool                         `json:"enabled"`
	Defaults  HookDefaultsConfig           `json:"defaults,omitempty"`
	Builtins  map[string]BuiltinHookConfig `json:"builtins,omitempty"`
	Processes map[string]ProcessHookConfig `json:"processes,omitempty"`
}

type IRCSettings

type IRCSettings struct {
	Server           string              `json:"server"                     yaml:"-"                           env:"COMPA_CHANNELS_IRC_SERVER"`
	TLS              bool                `json:"tls"                        yaml:"-"                           env:"COMPA_CHANNELS_IRC_TLS"`
	Nick             string              `json:"nick"                       yaml:"-"                           env:"COMPA_CHANNELS_IRC_NICK"`
	User             string              `json:"user,omitempty"             yaml:"-"                           env:"COMPA_CHANNELS_IRC_USER"`
	RealName         string              `json:"real_name,omitempty"        yaml:"-"`
	Password         SecureString        `json:"password,omitzero"          yaml:"password,omitempty"          env:"COMPA_CHANNELS_IRC_PASSWORD"`
	NickServPassword SecureString        `json:"nickserv_password,omitzero" yaml:"nickserv_password,omitempty" env:"COMPA_CHANNELS_IRC_NICKSERV_PASSWORD"`
	SASLUser         string              `json:"sasl_user"                  yaml:"-"                           env:"COMPA_CHANNELS_IRC_SASL_USER"`
	SASLPassword     SecureString        `json:"sasl_password,omitzero"     yaml:"sasl_password,omitempty"     env:"COMPA_CHANNELS_IRC_SASL_PASSWORD"`
	Channels         FlexibleStringSlice `json:"channels"                   yaml:"-"                           env:"COMPA_CHANNELS_IRC_CHANNELS"`
	RequestCaps      FlexibleStringSlice `json:"request_caps,omitempty"     yaml:"-"`
}

type IsolationConfig

type IsolationConfig struct {
	Enabled     bool         `json:"enabled,omitempty"`
	ExposePaths []ExposePath `json:"expose_paths,omitempty"`
}

IsolationConfig controls subprocess isolation for commands started by Compa. It is applied by the isolation package rather than by sandboxing the main process.

type KagiConfig

type KagiConfig struct {
	Enabled    bool          `json:"enabled"           yaml:"-"                  env:"COMPA_TOOLS_WEB_KAGI_ENABLED"`
	APIKeys    SecureStrings `json:"api_keys,omitzero" yaml:"api_keys,omitempty" env:"COMPA_TOOLS_WEB_KAGI_API_KEYS"`
	BaseURL    string        `json:"base_url"          yaml:"-"                  env:"COMPA_TOOLS_WEB_KAGI_BASE_URL"`
	MaxResults int           `json:"max_results"       yaml:"-"                  env:"COMPA_TOOLS_WEB_KAGI_MAX_RESULTS"`
}

func (*KagiConfig) APIKey

func (c *KagiConfig) APIKey() string

APIKey returns the Kagi API key

func (*KagiConfig) SetAPIKey

func (c *KagiConfig) SetAPIKey(key string)

SetAPIKey sets the Kagi API key

func (*KagiConfig) SetAPIKeys

func (c *KagiConfig) SetAPIKeys(keys []string)

SetAPIKeys sets the Kagi API keys

type LINESettings

type LINESettings struct {
	ChannelSecret      SecureString `json:"channel_secret,omitzero"       yaml:"channel_secret,omitempty"       env:"COMPA_CHANNELS_LINE_CHANNEL_SECRET"`
	ChannelAccessToken SecureString `json:"channel_access_token,omitzero" yaml:"channel_access_token,omitempty" env:"COMPA_CHANNELS_LINE_CHANNEL_ACCESS_TOKEN"`
	WebhookPath        string       `json:"webhook_path"                  yaml:"-"                              env:"COMPA_CHANNELS_LINE_WEBHOOK_PATH"`
}

LINESettings configures the LINE channel. Its webhook is served by the gateway's own server, at WebhookPath.

type LoggingConfig

type LoggingConfig struct {
	// RedactSecrets replaces the secrets Compa stores, and tokens inside
	// URLs, with [FILTERED] in log entries.
	RedactSecrets bool `json:"redact_secrets" env:"COMPA_LOGGING_REDACT_SECRETS"`
	// MaxSizeMB rotates a log file when it reaches this size.
	MaxSizeMB int `json:"max_size_mb" env:"COMPA_LOGGING_MAX_SIZE_MB"`
	// MaxFiles is how many rotated files are kept beside the current one.
	MaxFiles int `json:"max_files" env:"COMPA_LOGGING_MAX_FILES"`
}

LoggingConfig configures Compa's log files.

func (LoggingConfig) EffectiveMaxFiles

func (c LoggingConfig) EffectiveMaxFiles() int

EffectiveMaxFiles returns MaxFiles, or its default when unset.

func (LoggingConfig) EffectiveMaxSizeMB

func (c LoggingConfig) EffectiveMaxSizeMB() int

EffectiveMaxSizeMB returns MaxSizeMB, or its default when unset.

type MCPConfig

type MCPConfig struct {
	ToolConfig `                    envPrefix:"COMPA_TOOLS_MCP_"`
	Discovery  ToolDiscoveryConfig `                                json:"discovery"`
	// MaxInlineTextChars controls how much MCP text stays inline before it is saved as an artifact.
	MaxInlineTextChars int `json:"max_inline_text_chars,omitempty" env:"COMPA_TOOLS_MCP_MAX_INLINE_TEXT_CHARS"`
	// CallTimeoutSeconds bounds one tool call to a server without its own
	// call_timeout_seconds; 0 means 300 (mcp.DefaultCallTimeout).
	CallTimeoutSeconds int `json:"call_timeout_seconds,omitempty" env:"COMPA_TOOLS_MCP_CALL_TIMEOUT_SECONDS"`
	// Servers is a map of server name to server configuration
	Servers map[string]MCPServerConfig `json:"servers,omitempty"`
}

MCPConfig defines configuration for all MCP servers

func (*MCPConfig) GetMaxInlineTextChars

func (c *MCPConfig) GetMaxInlineTextChars() int

type MCPServerConfig

type MCPServerConfig struct {
	// Enabled indicates whether this MCP server is active
	Enabled bool `json:"enabled"`
	// Deferred controls whether this server's tools are registered as hidden (deferred/discovery mode).
	// When nil, the global Discovery.Enabled setting applies.
	// When explicitly set to true or false, it overrides the global setting for this server only.
	Deferred *bool `json:"deferred,omitempty"`
	// Command is the executable to run (e.g., "npx", "python", "/path/to/server")
	Command string `json:"command"`
	// Args are the arguments to pass to the command
	Args []string `json:"args,omitempty"`
	// Env are environment variables to set for the server process (stdio only)
	Env map[string]string `json:"env,omitempty"`
	// EnvFile is the path to a file containing environment variables (stdio only)
	EnvFile string `json:"env_file,omitempty"`
	// Type is "stdio", "sse", "http", or "streamable-http".
	// "http" and "streamable-http" both select streamable HTTP request-response
	// mode, while "sse" keeps the standalone SSE listener enabled for
	// server-initiated notifications. Defaults: stdio if command is set, sse if
	// url is set.
	Type string `json:"type,omitempty"`
	// URL is used for SSE/HTTP transport
	URL string `json:"url,omitempty"`
	// Headers are HTTP headers to send with requests (sse/http only)
	Headers map[string]string `json:"headers,omitempty"`
	// Trusted lets Compa act on what the server declares about its tools
	// (annotations such as readOnlyHint): approval rules may match them, and a
	// read-only or idempotent call is retried once after a lost session.
	// Annotations from servers that are not trusted are ignored.
	Trusted bool `json:"trusted,omitempty"`
	// Cwd is the working folder of a stdio server; empty means the agent
	// workspace.
	Cwd string `json:"cwd,omitempty"`
	// CallTimeoutSeconds bounds one tool call to this server; 0 means the
	// MCP default (MCPConfig.CallTimeoutSeconds).
	CallTimeoutSeconds int `json:"call_timeout_seconds,omitempty"`
}

MCPServerConfig defines configuration for a single MCP server

func (MCPServerConfig) MarshalJSON

func (c MCPServerConfig) MarshalJSON() ([]byte, error)

MarshalJSON writes the server with its env and header values masked: they often hold tokens, which are kept in .security.yml.

type MQTTSettings

type MQTTSettings struct {
	Broker      string       `json:"broker"                 yaml:"-"                  env:"COMPA_CHANNELS_MQTT_BROKER"`
	AgentID     string       `json:"agent_id"               yaml:"-"                  env:"COMPA_CHANNELS_MQTT_AGENT_ID"`
	TopicPrefix string       `json:"topic_prefix,omitempty" yaml:"-"                  env:"COMPA_CHANNELS_MQTT_TOPIC_PREFIX"`
	Username    SecureString `json:"username,omitzero"      yaml:"username,omitempty" env:"COMPA_CHANNELS_MQTT_USERNAME"`
	Password    SecureString `json:"password,omitzero"      yaml:"password,omitempty" env:"COMPA_CHANNELS_MQTT_PASSWORD"`
	ClientID    string       `json:"client_id,omitempty"    yaml:"-"                  env:"COMPA_CHANNELS_MQTT_CLIENT_ID"`
	KeepAlive   int          `json:"keep_alive,omitempty"   yaml:"-"                  env:"COMPA_CHANNELS_MQTT_KEEP_ALIVE"`
	QoS         int          `json:"qos,omitempty"          yaml:"-"                  env:"COMPA_CHANNELS_MQTT_QOS"`
	// TLSInsecureSkipVerify turns off verification of the broker's TLS
	// certificate.
	TLSInsecureSkipVerify bool `json:"tls_insecure_skip_verify" yaml:"-" env:"COMPA_CHANNELS_MQTT_TLS_INSECURE_SKIP_VERIFY"`
}

type MaixCamSettings

type MaixCamSettings struct {
	Host  string       `json:"host"           yaml:"-"               env:"COMPA_CHANNELS_MAIXCAM_HOST"`
	Port  int          `json:"port"           yaml:"-"               env:"COMPA_CHANNELS_MAIXCAM_PORT"`
	Token SecureString `json:"token,omitzero" yaml:"token,omitempty" env:"COMPA_CHANNELS_MAIXCAM_TOKEN"`
}

type MatrixSettings

type MatrixSettings struct {
	Homeserver         string       `json:"homeserver"                     yaml:"-"                      env:"COMPA_CHANNELS_MATRIX_HOMESERVER"`
	UserID             string       `json:"user_id"                        yaml:"-"                      env:"COMPA_CHANNELS_MATRIX_USER_ID"`
	AccessToken        SecureString `json:"access_token,omitzero"          yaml:"access_token,omitempty" env:"COMPA_CHANNELS_MATRIX_ACCESS_TOKEN"`
	DeviceID           string       `json:"device_id,omitempty"            yaml:"-"`
	JoinOnInvite       bool         `json:"join_on_invite"                 yaml:"-"`
	MessageFormat      string       `json:"message_format,omitempty"       yaml:"-"`
	CryptoDatabasePath string       `json:"crypto_database_path,omitempty" yaml:"-"`
	// CryptoPassphrase protects the end-to-end encryption keys.
	CryptoPassphrase SecureString `json:"crypto_passphrase,omitzero" yaml:"crypto_passphrase,omitempty"`
}

type MediaCleanupConfig

type MediaCleanupConfig struct {
	ToolConfig `    envPrefix:"COMPA_MEDIA_CLEANUP_"`
	MaxAge     int `                                    json:"max_age_minutes"  env:"COMPA_MEDIA_CLEANUP_MAX_AGE"`
	Interval   int `                                    json:"interval_minutes" env:"COMPA_MEDIA_CLEANUP_INTERVAL"`
}

type MessageToolsConfig

type MessageToolsConfig struct {
	ToolConfig `yaml:"-" envPrefix:"COMPA_TOOLS_MESSAGE_"`

	MediaEnabled bool `json:"media_enabled" yaml:"-" env:"COMPA_TOOLS_MESSAGE_MEDIA_ENABLED"`
	// Targets is where the message tool may send: "current_chat" or "any".
	Targets string `json:"targets" yaml:"-" env:"COMPA_TOOLS_MESSAGE_TARGETS"`
}

func (MessageToolsConfig) EffectiveTargets

func (c MessageToolsConfig) EffectiveTargets() string

EffectiveTargets returns the message tool's target policy.

type ModelRouteConfig

type ModelRouteConfig struct {
	Name    string   `json:"name"`
	Targets []string `json:"targets"`
}

ModelRouteConfig is an ordered failover route of exact instance-owned targets. Ordering is significant and duplicates are invalid.

type ModulesConfig

type ModulesConfig struct {
	// SourceRoots are the named locations the host may lend a module to read:
	// root name -> absolute path of an existing directory or file.
	//
	// A module asks for a root by NAME in the filesystem_read list of its
	// descriptor, and the host grants it read-only only when that name is
	// configured here (or supplied for one invocation with
	// `module-invoke --source-root name=path`). Compa itself defines no names
	// and no default paths. Roots the host supplies on its own -- the
	// workspace, a module's bundle and its writable state -- are never taken
	// from here.
	//
	// Loading checks the SHAPE of each entry only. Whether a path exists is
	// checked each time a module is granted it, so a detached drive never
	// makes the whole config unloadable.
	SourceRoots map[string]string `json:"source_roots,omitempty"`
}

ModulesConfig configures the host for detached modules.

type OneBotSettings

type OneBotSettings struct {
	WSUrl             string       `json:"ws_url"                yaml:"-"                      env:"COMPA_CHANNELS_ONEBOT_WS_URL"`
	AccessToken       SecureString `json:"access_token,omitzero" yaml:"access_token,omitempty" env:"COMPA_CHANNELS_ONEBOT_ACCESS_TOKEN"`
	ReconnectInterval int          `json:"reconnect_interval"    yaml:"-"                      env:"COMPA_CHANNELS_ONEBOT_RECONNECT_INTERVAL"`
}

type PerplexityConfig

type PerplexityConfig struct {
	Enabled    bool          `json:"enabled"           yaml:"-"                  env:"COMPA_TOOLS_WEB_PERPLEXITY_ENABLED"`
	APIKeys    SecureStrings `json:"api_keys,omitzero" yaml:"api_keys,omitempty" env:"COMPA_TOOLS_WEB_PERPLEXITY_API_KEYS"`
	MaxResults int           `json:"max_results"       yaml:"-"                  env:"COMPA_TOOLS_WEB_PERPLEXITY_MAX_RESULTS"`
}

func (*PerplexityConfig) APIKey

func (c *PerplexityConfig) APIKey() string

APIKey returns the Perplexity API key

func (*PerplexityConfig) SetAPIKey

func (c *PerplexityConfig) SetAPIKey(key string)

SetAPIKey sets the Perplexity API key

type PlaceholderConfig

type PlaceholderConfig struct {
	Enabled bool                `json:"enabled"`
	Text    FlexibleStringSlice `json:"text,omitempty"`
}

PlaceholderConfig controls placeholder message behavior (Phase 10).

func (*PlaceholderConfig) GetRandomText

func (p *PlaceholderConfig) GetRandomText() string

GetRandomText returns a random placeholder text, or default if none set.

type ProcessHookConfig

type ProcessHookConfig struct {
	Enabled   bool              `json:"enabled"`
	Priority  int               `json:"priority,omitempty"`
	Transport string            `json:"transport,omitempty"`
	Command   []string          `json:"command,omitempty"`
	Dir       string            `json:"dir,omitempty"`
	Env       map[string]string `json:"env,omitempty"`
	Observe   []string          `json:"observe,omitempty"`
	Intercept []string          `json:"intercept,omitempty"`
}

func (ProcessHookConfig) MarshalJSON

func (c ProcessHookConfig) MarshalJSON() ([]byte, error)

MarshalJSON writes the hook with its env values masked; they are kept in .security.yml.

type ProviderInstanceConfig

type ProviderInstanceConfig struct {
	ID                string            `json:"id"`
	ProviderKind      string            `json:"provider_kind"`
	Adapter           string            `json:"adapter"`
	Protocol          string            `json:"protocol"`
	Endpoint          string            `json:"endpoint,omitempty"`
	AuthConnectionRef string            `json:"auth_connection_ref,omitempty"`
	Headers           map[string]string `json:"headers,omitempty"`
	// Settings configure the adapter: display_name, project and location for
	// Vertex AI and, for an extension instance, the extension_* settings.
	Settings map[string]any `json:"settings,omitempty"`
	// Runtime holds the request settings every model of the instance runs
	// with; nil uses the provider defaults.
	Runtime *ProviderInstanceRuntime `json:"runtime,omitempty"`
	State   ProviderInstanceState    `json:"state"`
}

ProviderInstanceConfig owns one provider adapter connection independently of any model selected from its catalog.

func (*ProviderInstanceConfig) ExtensionProvider

func (c *ProviderInstanceConfig) ExtensionProvider() string

ExtensionProvider returns the daemon's id of an extension instance's provider, or "" for any other instance.

func (*ProviderInstanceConfig) ExtensionSurfaces

func (c *ProviderInstanceConfig) ExtensionSurfaces() []string

ExtensionSurfaces returns the surfaces the daemon lists for an extension instance's provider (the ExtensionSurfacesSetting), or just its protocol when the setting is absent. Other instances have none.

func (ProviderInstanceConfig) MarshalJSON

func (c ProviderInstanceConfig) MarshalJSON() ([]byte, error)

MarshalJSON writes the instance with its header values masked; they often hold credentials, which are kept in .security.yml.

func (*ProviderInstanceConfig) Validate

func (c *ProviderInstanceConfig) Validate() error

type ProviderInstanceRuntime

type ProviderInstanceRuntime struct {
	// Proxy is the http, https, socks5 or socks5h proxy URL requests go
	// through; empty uses none.
	Proxy string `json:"proxy,omitempty"`
	// RequestTimeout bounds a request, in seconds; 0 uses the provider
	// default.
	RequestTimeout int `json:"request_timeout,omitempty"`
	// RPM caps requests per minute; 0 is unlimited.
	RPM int `json:"rpm,omitempty"`
	// Streaming turns provider streaming on or off; nil leaves it on, so
	// answers show as they arrive.
	Streaming *bool `json:"streaming,omitempty"`
	// ThinkingLevel is the extended-thinking level: off, low, medium, high,
	// xhigh or adaptive; empty leaves it to the agent.
	ThinkingLevel string `json:"thinking_level,omitempty"`
	// MaxTokensField names the request's max-tokens field, such as
	// "max_completion_tokens"; empty uses the provider's choice.
	MaxTokensField string `json:"max_tokens_field,omitempty"`
	// ToolSchemaTransform adapts tool schemas for providers that reject
	// complex JSON Schema: "off" (or empty) or "simple".
	ToolSchemaTransform string `json:"tool_schema_transform,omitempty"`
	// ExtraBody holds fields merged into every request body.
	ExtraBody map[string]any `json:"extra_body,omitempty"`
}

ProviderInstanceRuntime holds the typed request settings of a provider instance, applied to every model call on it.

func (*ProviderInstanceRuntime) Validate

func (r *ProviderInstanceRuntime) Validate() error

Validate checks the runtime settings' values.

type ProviderInstanceState

type ProviderInstanceState string
const (
	ProviderInstanceStateEnabled  ProviderInstanceState = "enabled"
	ProviderInstanceStateDisabled ProviderInstanceState = "disabled"
)

type QQSettings

type QQSettings struct {
	AppID                string       `json:"app_id"                   yaml:"-"                    env:"COMPA_CHANNELS_QQ_APP_ID"`
	AppSecret            SecureString `json:"app_secret,omitzero"      yaml:"app_secret,omitempty" env:"COMPA_CHANNELS_QQ_APP_SECRET"`
	MaxMessageLength     int          `json:"max_message_length"       yaml:"-"                    env:"COMPA_CHANNELS_QQ_MAX_MESSAGE_LENGTH"`
	MaxBase64FileSizeMiB int64        `json:"max_base64_file_size_mib" yaml:"-"                    env:"COMPA_CHANNELS_QQ_MAX_BASE64_FILE_SIZE_MIB"`
	SendMarkdown         bool         `json:"send_markdown"            yaml:"-"                    env:"COMPA_CHANNELS_QQ_SEND_MARKDOWN"`
}

type RawNode

type RawNode json.RawMessage

RawNode stores raw configuration data as JSON bytes, supporting both JSON and YAML. Internally uses json.RawMessage, so Decode always uses json.Unmarshal which correctly respects json struct tags.

func (*RawNode) Decode

func (r *RawNode) Decode(target any) error

Decode unmarshals the stored data into the given target struct using json.Unmarshal.

func (*RawNode) IsEmpty

func (r *RawNode) IsEmpty() bool

IsEmpty returns true if the node has not been populated.

func (RawNode) MarshalJSON

func (r RawNode) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler: outputs stored JSON bytes.

func (RawNode) MarshalYAML

func (r RawNode) MarshalYAML() (any, error)

MarshalYAML implements yaml.ValueMarshaler: converts stored JSON back to a YAML-compatible value.

func (*RawNode) UnmarshalJSON

func (r *RawNode) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler: stores raw JSON bytes. NOTE: yaml.Unmarshal may call this when unmarshaling into RawNode fields. We detect if the input looks like YAML (not JSON) and handle it.

func (*RawNode) UnmarshalYAML

func (r *RawNode) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler: converts YAML node to JSON bytes. Merges the incoming YAML values with existing data, with YAML taking precedence.

type ReadFileToolConfig

type ReadFileToolConfig struct {
	Enabled         bool   `json:"enabled"`
	Mode            string `json:"mode"`
	MaxReadFileSize int    `json:"max_read_file_size"`
}

func (ReadFileToolConfig) EffectiveMode

func (c ReadFileToolConfig) EffectiveMode() string

type RoutingConfig

type RoutingConfig struct {
	Enabled    bool    `json:"enabled"`
	LightModel string  `json:"light_model"` // model selection (exact target or model route name) for simple tasks
	Threshold  float64 `json:"threshold"`   // complexity score in [0,1]; score >= threshold → primary model
}

RoutingConfig controls the intelligent model routing feature. When enabled, each incoming message is scored against structural features (message length, code blocks, tool call history, conversation depth, attachments). Messages scoring below Threshold are sent to LightModel; all others use the agent's primary model. This reduces cost and latency for simple tasks without requiring any keyword matching — all scoring is language-agnostic.

type SearXNGConfig

type SearXNGConfig struct {
	Enabled    bool   `json:"enabled"     env:"COMPA_TOOLS_WEB_SEARXNG_ENABLED"`
	BaseURL    string `json:"base_url"    env:"COMPA_TOOLS_WEB_SEARXNG_BASE_URL"`
	MaxResults int    `json:"max_results" env:"COMPA_TOOLS_WEB_SEARXNG_MAX_RESULTS"`
}

type SearchCacheConfig

type SearchCacheConfig struct {
	MaxSize    int `json:"max_size"    env:"COMPA_SKILLS_SEARCH_CACHE_MAX_SIZE"`
	TTLSeconds int `json:"ttl_seconds" env:"COMPA_SKILLS_SEARCH_CACHE_TTL_SECONDS"`
}

type SecureString

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

SecureString is a secret setting. JSON shows a placeholder instead of a value that is set; the value is kept in .security.yml, as written or as a file:// reference to a file beside it.

func NewSecureString

func NewSecureString(value string) *SecureString

func (SecureString) IsZero

func (s SecureString) IsZero() bool

IsZero reports whether the value is empty.

func (SecureString) MarshalJSON

func (s SecureString) MarshalJSON() ([]byte, error)

func (SecureString) MarshalYAML

func (s SecureString) MarshalYAML() (any, error)

MarshalYAML writes the value for .security.yml: a file:// reference as the reference, any other value as it is.

func (*SecureString) Set

func (s *SecureString) Set(value string) *SecureString

func (*SecureString) String

func (s *SecureString) String() string

func (*SecureString) UnmarshalJSON

func (s *SecureString) UnmarshalJSON(value []byte) error

UnmarshalJSON reads a plain value or a file:// reference. The placeholder reads as unset: the value is in .security.yml.

func (*SecureString) UnmarshalText

func (s *SecureString) UnmarshalText(text []byte) error

func (*SecureString) UnmarshalYAML

func (s *SecureString) UnmarshalYAML(value *yaml.Node) error

type SecureStrings

type SecureStrings []*SecureString

SecureStrings is a slice of SecureString

func SimpleSecureStrings

func SimpleSecureStrings(val ...string) SecureStrings

func (SecureStrings) IsZero

func (s SecureStrings) IsZero() bool

IsZero reports whether the list is empty.

func (SecureStrings) MarshalJSON

func (s SecureStrings) MarshalJSON() ([]byte, error)

func (*SecureStrings) UnmarshalJSON

func (s *SecureStrings) UnmarshalJSON(value []byte) error

UnmarshalJSON reads a list of values. The placeholder, for the whole list or an entry, reads as unset: the values are in .security.yml.

func (*SecureStrings) Values

func (s *SecureStrings) Values() []string

Values returns the decrypted/resolved values

type SensitiveDataCache

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

SensitiveDataCache holds the config's own secrets, collected once, and the replacer last built from them and the registered sources' values.

type SessionConfig

type SessionConfig struct {
	Dimensions    []string            `json:"dimensions,omitempty"`
	IdentityLinks map[string][]string `json:"identity_links,omitempty"`
	DmScope       string              `json:"dm_scope,omitempty"`
}

func (*SessionConfig) ApplyDmScope

func (s *SessionConfig) ApplyDmScope()

ApplyDmScope translates the user-facing dm_scope value into the internal dimensions array that the routing layer consumes. It is a no-op when DmScope is empty or when Dimensions is already set (explicit Dimensions take precedence over the derived value).

func (*SessionConfig) DeriveDmScope

func (s *SessionConfig) DeriveDmScope()

DeriveDmScope sets DmScope based on Dimensions when DmScope is empty. This handles configs, including the defaults, that set Dimensions without a corresponding DmScope value, ensuring the API response always includes a dm_scope that matches the actual runtime dimensions.

type SkillRegistryConfig

type SkillRegistryConfig struct {
	Name      string         `json:"name,omitempty"      yaml:"-"                    env:"-"`
	Enabled   bool           `json:"enabled"             yaml:"-"                    env:"-"`
	BaseURL   string         `json:"base_url"            yaml:"-"                    env:"-"`
	AuthToken SecureString   `json:"auth_token,omitzero" yaml:"auth_token,omitempty" env:"-"`
	Param     map[string]any `json:"-"                   yaml:"-"                    env:"-"`
}

func (*SkillRegistryConfig) DecodeParam

func (c *SkillRegistryConfig) DecodeParam(target any) error

func (SkillRegistryConfig) MarshalJSON

func (c SkillRegistryConfig) MarshalJSON() ([]byte, error)

func (SkillRegistryConfig) MarshalYAML

func (c SkillRegistryConfig) MarshalYAML() (any, error)

func (*SkillRegistryConfig) UnmarshalJSON

func (c *SkillRegistryConfig) UnmarshalJSON(data []byte) error

func (*SkillRegistryConfig) UnmarshalYAML

func (c *SkillRegistryConfig) UnmarshalYAML(value *yaml.Node) error

type SkillsRegistriesConfig

type SkillsRegistriesConfig []*SkillRegistryConfig

func (*SkillsRegistriesConfig) Get

func (SkillsRegistriesConfig) MarshalJSON

func (v SkillsRegistriesConfig) MarshalJSON() ([]byte, error)

func (SkillsRegistriesConfig) MarshalYAML

func (v SkillsRegistriesConfig) MarshalYAML() (any, error)

func (*SkillsRegistriesConfig) Set

func (*SkillsRegistriesConfig) UnmarshalJSON

func (v *SkillsRegistriesConfig) UnmarshalJSON(data []byte) error

func (*SkillsRegistriesConfig) UnmarshalYAML

func (v *SkillsRegistriesConfig) UnmarshalYAML(value *yaml.Node) error

type SkillsToolsConfig

type SkillsToolsConfig struct {
	ToolConfig            `                       yaml:"-"                    envPrefix:"COMPA_TOOLS_SKILLS_"`
	Registries            SkillsRegistriesConfig `yaml:"registries,omitempty"                                    json:"registries"`
	MaxConcurrentSearches int                    `yaml:"-"                    json:"max_concurrent_searches" env:"COMPA_TOOLS_SKILLS_MAX_CONCURRENT_SEARCHES"`
	SearchCache           SearchCacheConfig      `yaml:"-"                    json:"search_cache"`
}

type SlackSettings

type SlackSettings struct {
	BotToken SecureString `json:"bot_token,omitzero" yaml:"bot_token,omitempty" env:"COMPA_CHANNELS_SLACK_BOT_TOKEN"`
	AppToken SecureString `json:"app_token,omitzero" yaml:"app_token,omitempty" env:"COMPA_CHANNELS_SLACK_APP_TOKEN"`
}

type SlackWebhookSettings

type SlackWebhookSettings struct {
	Webhooks map[string]SlackWebhookTarget `json:"webhooks" yaml:"webhooks,omitempty"`
}

SlackWebhookSettings configures the output-only Slack webhook channel.

type SlackWebhookTarget

type SlackWebhookTarget struct {
	WebhookURL SecureString `json:"webhook_url,omitzero" yaml:"webhook_url,omitempty"`
	Username   string       `json:"username,omitempty"   yaml:"-"`
	IconEmoji  string       `json:"icon_emoji,omitempty" yaml:"-"`
}

SlackWebhookTarget represents a single Slack Incoming Webhook destination.

type SogouConfig

type SogouConfig struct {
	Enabled    bool `json:"enabled"     env:"COMPA_TOOLS_WEB_SOGOU_ENABLED"`
	MaxResults int  `json:"max_results" env:"COMPA_TOOLS_WEB_SOGOU_MAX_RESULTS"`
}

type StreamingConfig

type StreamingConfig struct {
	Enabled         bool `json:"enabled,omitempty"`
	ThrottleSeconds int  `json:"throttle_seconds,omitempty"`
	MinGrowthChars  int  `json:"min_growth_chars,omitempty"`
}

func (StreamingConfig) IsZero

func (c StreamingConfig) IsZero() bool

func (StreamingConfig) WithDefaults

func (c StreamingConfig) WithDefaults(throttleSeconds, minGrowthChars int) StreamingConfig

type SubTurnConfig

type SubTurnConfig struct {
	MaxDepth              int `json:"max_depth"               env:"COMPA_AGENTS_DEFAULTS_SUBTURN_MAX_DEPTH"`
	MaxConcurrent         int `json:"max_concurrent"          env:"COMPA_AGENTS_DEFAULTS_SUBTURN_MAX_CONCURRENT"`
	DefaultTimeoutMinutes int `json:"default_timeout_minutes" env:"COMPA_AGENTS_DEFAULTS_SUBTURN_DEFAULT_TIMEOUT_MINUTES"`
	ConcurrencyTimeoutSec int `json:"concurrency_timeout_sec" env:"COMPA_AGENTS_DEFAULTS_SUBTURN_CONCURRENCY_TIMEOUT_SEC"`
}

SubTurnConfig configures the SubTurn execution system. Its env tags are the full COMPA_AGENTS_DEFAULTS_SUBTURN_* names, so the field that holds it carries no envPrefix, which would double them.

type SubagentsConfig

type SubagentsConfig struct {
	AllowAgents []string `json:"allow_agents,omitempty"`
}

type TavilyConfig

type TavilyConfig struct {
	Enabled    bool          `json:"enabled"           yaml:"-"                  env:"COMPA_TOOLS_WEB_TAVILY_ENABLED"`
	APIKeys    SecureStrings `json:"api_keys,omitzero" yaml:"api_keys,omitempty" env:"COMPA_TOOLS_WEB_TAVILY_API_KEYS"`
	BaseURL    string        `json:"base_url"          yaml:"-"                  env:"COMPA_TOOLS_WEB_TAVILY_BASE_URL"`
	MaxResults int           `json:"max_results"       yaml:"-"                  env:"COMPA_TOOLS_WEB_TAVILY_MAX_RESULTS"`
}

func (*TavilyConfig) APIKey

func (c *TavilyConfig) APIKey() string

APIKey returns the Tavily API key

func (*TavilyConfig) SetAPIKey

func (c *TavilyConfig) SetAPIKey(key string)

SetAPIKey sets the Tavily API key

func (*TavilyConfig) SetAPIKeys

func (c *TavilyConfig) SetAPIKeys(keys []string)

SetAPIKeys sets the Tavily API keys

type TeamsWebhookSettings

type TeamsWebhookSettings struct {
	Webhooks map[string]TeamsWebhookTarget `json:"webhooks" yaml:"webhooks,omitempty"`
}

TeamsWebhookSettings configures the output-only Microsoft Teams webhook channel. Multiple webhook targets can be configured and selected via ChatID at send time.

type TeamsWebhookTarget

type TeamsWebhookTarget struct {
	WebhookURL SecureString `json:"webhook_url,omitzero" yaml:"webhook_url,omitempty"`
	Title      string       `json:"title,omitempty"      yaml:"-"`
}

TeamsWebhookTarget represents a single Teams webhook destination.

type TelegramSettings

type TelegramSettings struct {
	Token             SecureString    `json:"token,omitzero"       yaml:"token,omitempty" env:"COMPA_CHANNELS_TELEGRAM_TOKEN"`
	BaseURL           string          `json:"base_url"             yaml:"-"               env:"COMPA_CHANNELS_TELEGRAM_BASE_URL"`
	Proxy             string          `json:"proxy"                yaml:"-"               env:"COMPA_CHANNELS_TELEGRAM_PROXY"`
	Streaming         StreamingConfig `json:"streaming,omitzero"   yaml:"-"`
	UseMarkdownV2     bool            `json:"use_markdown_v2"      yaml:"-"               env:"COMPA_CHANNELS_TELEGRAM_USE_MARKDOWN_V2"`
	MediaGroupDelayMS int             `json:"media_group_delay_ms" yaml:"-"               env:"COMPA_CHANNELS_TELEGRAM_MEDIA_GROUP_DELAY_MS"`
}

type ToolConfig

type ToolConfig struct {
	Enabled bool `json:"enabled" yaml:"-" env:"ENABLED"`
}

type ToolDiscoveryConfig

type ToolDiscoveryConfig struct {
	Enabled          bool `json:"enabled"            env:"COMPA_TOOLS_DISCOVERY_ENABLED"`
	TTL              int  `json:"ttl"                env:"COMPA_TOOLS_DISCOVERY_TTL"`
	MaxSearchResults int  `json:"max_search_results" env:"COMPA_MAX_SEARCH_RESULTS"`
	UseBM25          bool `json:"use_bm25"           env:"COMPA_TOOLS_DISCOVERY_USE_BM25"`
	UseRegex         bool `json:"use_regex"          env:"COMPA_TOOLS_DISCOVERY_USE_REGEX"`
}

type ToolFeedbackConfig

type ToolFeedbackConfig struct {
	Enabled          bool `json:"enabled"           env:"COMPA_AGENTS_DEFAULTS_TOOL_FEEDBACK_ENABLED"`
	MaxArgsLength    int  `json:"max_args_length"   env:"COMPA_AGENTS_DEFAULTS_TOOL_FEEDBACK_MAX_ARGS_LENGTH"`
	SeparateMessages bool `json:"separate_messages" env:"COMPA_AGENTS_DEFAULTS_TOOL_FEEDBACK_SEPARATE_MESSAGES"`
}

type ToolsConfig

type ToolsConfig struct {
	AllowReadPaths  []string `json:"allow_read_paths"  yaml:"-" env:"COMPA_TOOLS_ALLOW_READ_PATHS"`
	AllowWritePaths []string `json:"allow_write_paths" yaml:"-" env:"COMPA_TOOLS_ALLOW_WRITE_PATHS"`
	// FilterSensitiveData controls whether to filter sensitive values (API keys,
	// tokens, secrets) from tool results before sending to the LLM.
	// Default: true (enabled)
	FilterSensitiveData bool `json:"filter_sensitive_data" yaml:"-" env:"COMPA_TOOLS_FILTER_SENSITIVE_DATA"`
	// FilterMinLength is the minimum content length required for filtering.
	// Content shorter than this will be returned unchanged for performance.
	// Default: 8
	FilterMinLength int                `json:"filter_min_length" yaml:"-"                env:"COMPA_TOOLS_FILTER_MIN_LENGTH"`
	Approval        approval.Policy    `json:"approval"          yaml:"-"`
	Web             WebToolsConfig     `json:"web"               yaml:"web,omitempty"`
	Cron            CronToolsConfig    `json:"cron"              yaml:"-"`
	Exec            ExecConfig         `json:"exec"              yaml:"-"`
	Skills          SkillsToolsConfig  `json:"skills"            yaml:"skills,omitempty"`
	MediaCleanup    MediaCleanupConfig `json:"media_cleanup"     yaml:"-"`
	MCP             MCPConfig          `json:"mcp"               yaml:"-"`
	AppendFile      ToolConfig         `json:"append_file"       yaml:"-"                                                       envPrefix:"COMPA_TOOLS_APPEND_FILE_"`
	EditFile        ToolConfig         `json:"edit_file"         yaml:"-"                                                       envPrefix:"COMPA_TOOLS_EDIT_FILE_"`
	FindSkills      ToolConfig         `json:"find_skills"       yaml:"-"                                                       envPrefix:"COMPA_TOOLS_FIND_SKILLS_"`
	I2C             ToolConfig         `json:"i2c"               yaml:"-"                                                       envPrefix:"COMPA_TOOLS_I2C_"`
	InstallSkill    ToolConfig         `` /* 126-byte string literal not displayed */
	ListDir         ToolConfig         `json:"list_dir"          yaml:"-"                                                       envPrefix:"COMPA_TOOLS_LIST_DIR_"`
	LoadImage       ToolConfig         `json:"load_image"        yaml:"-"                                                       envPrefix:"COMPA_TOOLS_LOAD_IMAGE_"`
	Message         MessageToolsConfig `json:"message"           yaml:"-"`
	ReadFile        ReadFileToolConfig `json:"read_file"         yaml:"-"                                                       envPrefix:"COMPA_TOOLS_READ_FILE_"`
	Serial          ToolConfig         `json:"serial"            yaml:"-"                                                       envPrefix:"COMPA_TOOLS_SERIAL_"`
	SendFile        ToolConfig         `json:"send_file"         yaml:"-"                                                       envPrefix:"COMPA_TOOLS_SEND_FILE_"`
	SendTTS         ToolConfig         `json:"send_tts"          yaml:"-"                                                       envPrefix:"COMPA_TOOLS_SEND_TTS_"`
	Spawn           ToolConfig         `json:"spawn"             yaml:"-"                                                       envPrefix:"COMPA_TOOLS_SPAWN_"`
	SpawnStatus     ToolConfig         `json:"spawn_status"      yaml:"-"                                                       envPrefix:"COMPA_TOOLS_SPAWN_STATUS_"`
	SPI             ToolConfig         `json:"spi"               yaml:"-"                                                       envPrefix:"COMPA_TOOLS_SPI_"`
	Subagent        ToolConfig         `json:"subagent"          yaml:"-"                                                       envPrefix:"COMPA_TOOLS_SUBAGENT_"`
	WebFetch        ToolConfig         `json:"web_fetch"         yaml:"-"                                                       envPrefix:"COMPA_TOOLS_WEB_FETCH_"`
	WriteFile       ToolConfig         `json:"write_file"        yaml:"-"                                                       envPrefix:"COMPA_TOOLS_WRITE_FILE_"`
}

func (*ToolsConfig) GetFilterMinLength

func (c *ToolsConfig) GetFilterMinLength() int

GetFilterMinLength returns the minimum content length for filtering (default: 8)

func (*ToolsConfig) IsFilterSensitiveDataEnabled

func (c *ToolsConfig) IsFilterSensitiveDataEnabled() bool

IsFilterSensitiveDataEnabled returns true if sensitive data filtering is enabled

func (*ToolsConfig) IsToolEnabled

func (t *ToolsConfig) IsToolEnabled(name string) bool

type TurnProfileBlock

type TurnProfileBlock struct {
	Mode  TurnProfileMode `json:"mode,omitempty"`
	Allow []string        `json:"allow,omitempty"`
}

type TurnProfileConfig

type TurnProfileConfig struct {
	Enabled      bool             `json:"enabled"`
	History      TurnProfileBlock `json:"history,omitempty"`
	SystemPrompt TurnProfileBlock `json:"system_prompt,omitempty"`
	Skills       TurnProfileBlock `json:"skills,omitempty"`
	Tools        TurnProfileBlock `json:"tools,omitempty"`
}

type TurnProfileMode

type TurnProfileMode string
const (
	TurnProfileModeDefault TurnProfileMode = "default"
	TurnProfileModeOff     TurnProfileMode = "off"
	TurnProfileModeCustom  TurnProfileMode = "custom"
)

func (TurnProfileMode) Effective

func (m TurnProfileMode) Effective() TurnProfileMode

type TypingConfig

type TypingConfig struct {
	Enabled bool `json:"enabled,omitempty"`
}

TypingConfig controls typing indicator behavior (Phase 10).

type VKSettings

type VKSettings struct {
	Token   SecureString `json:"token,omitzero" yaml:"token,omitempty" env:"COMPA_CHANNELS_VK_TOKEN"`
	GroupID int          `json:"group_id"       yaml:"-"               env:"COMPA_CHANNELS_VK_GROUP_ID"`
}

func (*VKSettings) SetToken

func (c *VKSettings) SetToken(token string)

type VoiceConfig

type VoiceConfig struct {
	Enabled bool `json:"enabled"`
	// Mode is "cascade" (push-to-talk) or "live" (hands-free).
	Mode string `json:"mode,omitempty"`
	// STTTarget is the exact target "instance-id/model-id" that transcribes
	// speech.
	STTTarget string `json:"stt_target,omitempty"`
	// STTViaChat opts STTTarget in as a chat model that transcribes the audio
	// it is sent (llmgw-core's chat transcription adapter) instead of a model
	// serving audio_transcriptions. It is never inferred, and holds only for
	// a model whose catalog declares audio input.
	STTViaChat bool `json:"stt_via_chat,omitempty"`
	// TTSTarget is the exact target "instance-id/model-id" that synthesizes
	// speech.
	TTSTarget string `json:"tts_target,omitempty"`
	// TTSVoice is the synthesis voice; empty uses the provider's default.
	TTSVoice          string `json:"tts_voice,omitempty"`
	EchoTranscription bool   `json:"echo_transcription" env:"COMPA_VOICE_ECHO_TRANSCRIPTION"`
}

VoiceConfig configures voice conversation. Speech-to-text and text-to-speech each run on an exact provider instance target; voice runs with either or both: speech-to-text alone dictates, text-to-speech alone speaks the replies.

type WeComGroupConfig

type WeComGroupConfig struct {
	AllowFrom FlexibleStringSlice `json:"allow_from,omitempty"`
}

type WeComSettings

type WeComSettings struct {
	BotID               string          `json:"bot_id"                  yaml:"-"                env:"COMPA_CHANNELS_WECOM_BOT_ID"`
	Secret              SecureString    `json:"secret,omitzero"         yaml:"secret,omitempty" env:"COMPA_CHANNELS_WECOM_SECRET"`
	WebSocketURL        string          `json:"websocket_url,omitempty" yaml:"-"                env:"COMPA_CHANNELS_WECOM_WEBSOCKET_URL"`
	SendThinkingMessage bool            `json:"send_thinking_message"   yaml:"-"                env:"COMPA_CHANNELS_WECOM_SEND_THINKING_MESSAGE"`
	Streaming           StreamingConfig `json:"streaming,omitzero"      yaml:"-"`
}

func (*WeComSettings) SetSecret

func (c *WeComSettings) SetSecret(secret string)

type WebChatClientSettings

type WebChatClientSettings struct {
	URL          string       `json:"url"                     yaml:"-"               env:"COMPA_CHANNELS_WEB_CLIENT_URL"`
	Token        SecureString `json:"token,omitzero"          yaml:"token,omitempty" env:"COMPA_CHANNELS_WEB_CLIENT_TOKEN"`
	SessionID    string       `json:"session_id,omitempty"    yaml:"-"`
	PingInterval int          `json:"ping_interval,omitempty" yaml:"-"`
	ReadTimeout  int          `json:"read_timeout,omitempty"  yaml:"-"`
}

type WebChatSettings

type WebChatSettings struct {
	Token           SecureString    `json:"token,omitzero"              yaml:"token,omitempty" env:"COMPA_CHANNELS_WEB_TOKEN"`
	AllowTokenQuery bool            `json:"allow_token_query,omitempty" yaml:"-"`
	AllowOrigins    []string        `json:"allow_origins,omitempty"     yaml:"-"`
	Streaming       StreamingConfig `json:"streaming,omitzero"          yaml:"-"`
	PingInterval    int             `json:"ping_interval,omitempty"     yaml:"-"`
	ReadTimeout     int             `json:"read_timeout,omitempty"      yaml:"-"`
	WriteTimeout    int             `json:"write_timeout,omitempty"     yaml:"-"`
	MaxConnections  int             `json:"max_connections,omitempty"   yaml:"-"`
}

func (*WebChatSettings) SetToken

func (c *WebChatSettings) SetToken(token string)

SetToken sets the web chat token and marks it as dirty for security saving

type WebToolsConfig

type WebToolsConfig struct {
	ToolConfig  `                   yaml:"-"                      envPrefix:"COMPA_TOOLS_WEB_"`
	Brave       BraveConfig        `yaml:"brave,omitempty"                                        json:"brave"`
	Tavily      TavilyConfig       `yaml:"tavily,omitempty"                                       json:"tavily"`
	Kagi        KagiConfig         `yaml:"kagi,omitempty"                                         json:"kagi"`
	Sogou       SogouConfig        `yaml:"-"                                                      json:"sogou"`
	DuckDuckGo  DuckDuckGoConfig   `yaml:"-"                                                      json:"duckduckgo"`
	Gemini      GeminiSearchConfig `yaml:"gemini,omitempty"                                       json:"gemini"`
	Perplexity  PerplexityConfig   `yaml:"perplexity,omitempty"                                   json:"perplexity"`
	SearXNG     SearXNGConfig      `yaml:"-"                                                      json:"searxng"`
	GLMSearch   GLMSearchConfig    `yaml:"glm_search,omitempty"                                   json:"glm_search"`
	BaiduSearch BaiduSearchConfig  `yaml:"baidu_search,omitempty"                                 json:"baidu_search"`
	Provider    string             `yaml:"-"                                                      json:"provider,omitempty" env:"COMPA_TOOLS_WEB_PROVIDER"`
	// PreferNative controls whether to use provider-native web search when
	// the active LLM supports it (e.g. OpenAI web_search_preview). When true,
	// the client-side web_search tool is hidden to avoid duplicate search surfaces,
	// and the provider's built-in search is used instead. Falls back to client-side
	// search when the provider does not support native search.
	PreferNative bool `yaml:"-" json:"prefer_native" env:"COMPA_TOOLS_WEB_PREFER_NATIVE"`
	// Proxy is an optional proxy URL for web tools (http/https/socks5/socks5h).
	// For authenticated proxies, prefer HTTP_PROXY/HTTPS_PROXY env vars instead of embedding credentials in config.
	Proxy                string              `yaml:"-" json:"proxy,omitempty"                  env:"COMPA_TOOLS_WEB_PROXY"`
	FetchLimitBytes      int64               `yaml:"-" json:"fetch_limit_bytes,omitempty"      env:"COMPA_TOOLS_WEB_FETCH_LIMIT_BYTES"`
	Format               string              `yaml:"-" json:"format,omitempty"                 env:"COMPA_TOOLS_WEB_FORMAT"`
	PrivateHostWhitelist FlexibleStringSlice `yaml:"-" json:"private_host_whitelist,omitempty" env:"COMPA_TOOLS_WEB_PRIVATE_HOST_WHITELIST"`
}

type WeixinSettings

type WeixinSettings struct {
	Token      SecureString `json:"token,omitzero"       yaml:"token,omitempty" env:"COMPA_CHANNELS_WEIXIN_TOKEN"`
	AccountID  string       `json:"account_id,omitempty" yaml:"-"               env:"COMPA_CHANNELS_WEIXIN_ACCOUNT_ID"`
	BaseURL    string       `json:"base_url"             yaml:"-"               env:"COMPA_CHANNELS_WEIXIN_BASE_URL"`
	CDNBaseURL string       `json:"cdn_base_url"         yaml:"-"               env:"COMPA_CHANNELS_WEIXIN_CDN_BASE_URL"`
	Proxy      string       `json:"proxy"                yaml:"-"               env:"COMPA_CHANNELS_WEIXIN_PROXY"`
}

func (*WeixinSettings) SetToken

func (c *WeixinSettings) SetToken(token string)

SetToken sets the Weixin token and marks it as dirty for security saving

type WhatsAppSettings

type WhatsAppSettings struct {
	BridgeURL        string `json:"bridge_url"         yaml:"-" env:"COMPA_CHANNELS_WHATSAPP_BRIDGE_URL"`
	UseNative        bool   `json:"use_native"         yaml:"-" env:"COMPA_CHANNELS_WHATSAPP_USE_NATIVE"`
	SessionStorePath string `json:"session_store_path" yaml:"-" env:"COMPA_CHANNELS_WHATSAPP_SESSION_STORE_PATH"`
	// Chats selects which chats the native client takes as input: "self",
	// "allowed" or "all" (see the WhatsAppChats* constants).
	Chats string `json:"chats,omitempty" yaml:"-" env:"COMPA_CHANNELS_WHATSAPP_CHATS"`
}

func (WhatsAppSettings) EffectiveChats

func (s WhatsAppSettings) EffectiveChats() string

EffectiveChats returns which chats the native WhatsApp client takes as input.

Jump to

Keyboard shortcuts

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