config

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ValidLogLevels         = map[string]bool{"debug": true, "info": true, "warn": true, "error": true}
	ValidLogFormats        = map[string]bool{"json": true, "console": true}
	ValidSignerProviders   = map[string]bool{"local": true, "rpc": true, "enclave": true, "aws-kms": true, "gcp-kms": true, "azure-kv": true, "pkcs11": true}
	ValidWalletProviders   = map[string]bool{"local": true, "rpc": true, "composite": true}
	ValidZKPSchemes        = map[string]bool{"plonk": true, "groth16": true}
	ValidContainerRuntimes = map[string]bool{"auto": true, "docker": true, "gvisor": true, "native": true}
	ValidMCPTransports     = map[string]bool{"": true, "stdio": true, "http": true, "sse": true}
)

Validation maps for configuration values.

View Source
var ProviderTypeToEmbeddingType = map[types.ProviderType]string{
	types.ProviderOpenAI:    "openai",
	types.ProviderGemini:    "google",
	types.ProviderGoogle:    "google",
	types.ProviderAnthropic: "",
	types.ProviderOllama:    "local",
}

ProviderTypeToEmbeddingType maps a provider config type to the corresponding embedding backend type.

ValidContextProfiles lists accepted profile names for validation.

Functions

func ApplyContextProfile added in v0.7.0

func ApplyContextProfile(cfg *Config, explicitKeys map[string]bool)

ApplyContextProfile sets context subsystem defaults based on the named profile. Fields explicitly set by the user (tracked in explicitKeys) are never overwritten. If cfg.ContextProfile is empty, this is a no-op.

func ContextRelatedKeys added in v0.7.0

func ContextRelatedKeys() []string

ContextRelatedKeys returns a copy of the config keys tracked for explicit override detection.

func ExpandEnvVars added in v0.4.0

func ExpandEnvVars(s string) string

ExpandEnvVars replaces ${VAR} patterns in s with environment variable values. Variables that are not set in the environment are left as-is.

func IsValidPreset added in v0.6.0

func IsValidPreset(name string) bool

IsValidPreset checks if the given name is a valid preset.

func NormalizePaths added in v0.6.0

func NormalizePaths(cfg *Config)

NormalizePaths resolves relative data paths to be under DataRoot and expands ~ in all path fields. Call after Load/Unmarshal.

func PostLoad added in v0.6.0

func PostLoad(cfg *Config) error

PostLoad applies post-load processing: legacy migration, env substitution, path normalization, path validation, and full config validation. All operations are idempotent — safe to call multiple times on the same config.

func PresetExplicitKeys added in v0.7.0

func PresetExplicitKeys(name string) map[string]bool

PresetExplicitKeys returns the set of config keys that a preset explicitly sets. This allows callers to record preset-set fields as explicit, preventing auto-enable from overriding preset intentions.

func Validate

func Validate(cfg *Config) error

Validate checks if the configuration is valid

func ValidateDataPaths added in v0.6.0

func ValidateDataPaths(cfg *Config) error

ValidateDataPaths checks that all configurable data paths reside under DataRoot. Must be called after NormalizePaths (paths are already cleaned absolute paths).

Types

type A2AConfig

type A2AConfig struct {
	// Enable A2A protocol support.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// BaseURL is the external URL where this agent is reachable.
	BaseURL string `mapstructure:"baseUrl" json:"baseUrl"`

	// AgentName is the name advertised in the Agent Card.
	AgentName string `mapstructure:"agentName" json:"agentName"`

	// AgentDescription is the description in the Agent Card.
	AgentDescription string `mapstructure:"agentDescription" json:"agentDescription"`

	// RemoteAgents is a list of external A2A agents to integrate as sub-agents.
	RemoteAgents []RemoteAgentConfig `mapstructure:"remoteAgents" json:"remoteAgents"`
}

A2AConfig defines Agent-to-Agent protocol settings.

type AgentConfig

type AgentConfig struct {
	// Default model provider (anthropic, openai, google)
	Provider string `mapstructure:"provider" json:"provider"`

	// Model ID to use
	Model string `mapstructure:"model" json:"model"`

	// Maximum tokens for context window
	MaxTokens int `mapstructure:"maxTokens" json:"maxTokens"`

	// Temperature for generation
	Temperature float64 `mapstructure:"temperature" json:"temperature"`

	// PromptsDir is the directory containing section .md files (AGENTS.md, SAFETY.md, etc.)
	// If empty, built-in default sections are used.
	PromptsDir string `mapstructure:"promptsDir" json:"promptsDir"`

	// Fallback provider ID
	FallbackProvider string `mapstructure:"fallbackProvider" json:"fallbackProvider"`

	// Fallback model ID
	FallbackModel string `mapstructure:"fallbackModel" json:"fallbackModel"`

	// MultiAgent enables hierarchical sub-agent orchestration.
	// When false (default), a single monolithic agent handles all tasks.
	MultiAgent bool `mapstructure:"multiAgent" json:"multiAgent"`

	// RequestTimeout is the maximum duration for a single agent request (default: 5m).
	RequestTimeout time.Duration `mapstructure:"requestTimeout" json:"requestTimeout"`

	// ToolTimeout is the maximum duration for a single tool call execution (default: 2m).
	ToolTimeout time.Duration `mapstructure:"toolTimeout" json:"toolTimeout"`

	// MaxTurns limits the number of tool-calling iterations per agent run (default: 25).
	// Zero means use the default.
	MaxTurns int `mapstructure:"maxTurns" json:"maxTurns"`

	// ErrorCorrectionEnabled enables learning-based error correction (default: true).
	// When nil, defaults to true if the knowledge system is enabled.
	ErrorCorrectionEnabled *bool `mapstructure:"errorCorrectionEnabled" json:"errorCorrectionEnabled"`

	// MaxDelegationRounds limits orchestrator→sub-agent delegation rounds per turn (default: 10).
	// Zero means use the default.
	MaxDelegationRounds int `mapstructure:"maxDelegationRounds" json:"maxDelegationRounds"`

	// AutoExtendTimeout enables automatic deadline extension when agent activity is detected.
	// When true, the timeout is extended on each agent event (tool call, text chunk) up to MaxRequestTimeout.
	AutoExtendTimeout bool `mapstructure:"autoExtendTimeout" json:"autoExtendTimeout"`

	// MaxRequestTimeout is the absolute maximum duration for a request when auto-extend is enabled.
	// Defaults to 3x RequestTimeout (e.g. 15m if RequestTimeout is 5m).
	MaxRequestTimeout time.Duration `mapstructure:"maxRequestTimeout" json:"maxRequestTimeout"`

	// Orchestration configures the structured multi-agent control plane.
	// When Mode is "structured", a CoordinatingExecutor wraps the agent executor
	// to apply DelegationGuard, BudgetPolicy, and RecoveryPolicy.
	Orchestration OrchestrationConfig `mapstructure:"orchestration" json:"orchestration"`

	// IdleTimeout is the duration of inactivity (no streaming chunks, tool calls, or model responses)
	// before a request is timed out. When set, RequestTimeout becomes the hard ceiling.
	// Set to -1 to disable idle timeout and use fixed RequestTimeout instead.
	// Default: 0 (disabled for backward compatibility; new installs should set 2m).
	IdleTimeout time.Duration `mapstructure:"idleTimeout" json:"idleTimeout"`

	// AgentsDir is the directory containing user-defined AGENT.md files.
	// Structure: <dir>/<name>/AGENT.md
	// If empty, only built-in agents are used.
	AgentsDir string `mapstructure:"agentsDir" json:"agentsDir"`
}

AgentConfig defines LLM agent settings

type AgentMemoryConfig added in v0.4.0

type AgentMemoryConfig struct {
	// Enable agent memory system
	Enabled bool `mapstructure:"enabled" json:"enabled"`
}

AgentMemoryConfig defines agent-scoped persistent memory settings.

type AlertDeliveryConfig added in v0.7.0

type AlertDeliveryConfig struct {
	// Type is the delivery channel type ("webhook").
	Type string `mapstructure:"type" json:"type"`
	// WebhookURL is the target URL for webhook delivery.
	WebhookURL string `mapstructure:"webhookURL" json:"webhookURL,omitempty"`
	// MinSeverity filters alerts below this level ("warning", "critical").
	MinSeverity string `mapstructure:"minSeverity" json:"minSeverity,omitempty"`
}

AlertDeliveryConfig configures a single alert delivery channel.

type AlertingConfig added in v0.7.0

type AlertingConfig struct {
	// Master switch (default: false)
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// PolicyBlockRate is the threshold for policy block events per 5min window (default: 10)
	PolicyBlockRate int `mapstructure:"policyBlockRateThreshold" json:"policyBlockRateThreshold"`

	// RecoveryRetries is the threshold for recovery retry events per session (default: 5)
	RecoveryRetries int `mapstructure:"recoveryRetryThreshold" json:"recoveryRetryThreshold"`

	// Delivery configures external alert delivery channels (webhook, etc.).
	Delivery []AlertDeliveryConfig `mapstructure:"delivery" json:"delivery,omitempty"`
}

AlertingConfig defines operational alerting thresholds and delivery settings.

type ApprovalPolicy

type ApprovalPolicy string

ApprovalPolicy determines which tools require approval before execution.

const (
	// ApprovalPolicyDangerous requires approval for Dangerous-level tools (default).
	ApprovalPolicyDangerous ApprovalPolicy = "dangerous"
	// ApprovalPolicyAll requires approval for all tools.
	ApprovalPolicyAll ApprovalPolicy = "all"
	// ApprovalPolicyConfigured requires approval only for explicitly listed SensitiveTools.
	ApprovalPolicyConfigured ApprovalPolicy = "configured"
	// ApprovalPolicyNone disables approval entirely.
	ApprovalPolicyNone ApprovalPolicy = "none"
)

func (ApprovalPolicy) Valid

func (p ApprovalPolicy) Valid() bool

Valid reports whether p is a known approval policy.

func (ApprovalPolicy) Values

func (p ApprovalPolicy) Values() []ApprovalPolicy

Values returns all known approval policies.

type AuditConfig added in v0.5.0

type AuditConfig struct {
	// Enabled activates audit logging.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// RetentionDays controls how long audit records are kept (default: 90).
	RetentionDays int `mapstructure:"retentionDays" json:"retentionDays"`
}

AuditConfig defines audit log settings.

type AuthConfig

type AuthConfig struct {
	// OIDC Providers
	Providers map[string]OIDCProviderConfig `mapstructure:"providers" json:"providers"`
}

AuthConfig defines authentication settings

type AutoAdjustConfig added in v0.7.0

type AutoAdjustConfig struct {
	Enabled       bool    `mapstructure:"enabled" json:"enabled"`             // Master switch (default: false)
	Mode          string  `mapstructure:"mode" json:"mode"`                   // "shadow" or "active" (default: "shadow")
	BoostDelta    float64 `mapstructure:"boostDelta" json:"boostDelta"`       // Per-injection boost (default: 0.05)
	DecayDelta    float64 `mapstructure:"decayDelta" json:"decayDelta"`       // Per-interval decay (default: 0.01)
	DecayInterval int     `mapstructure:"decayInterval" json:"decayInterval"` // Turns between global decay (default: 100)
	MinScore      float64 `mapstructure:"minScore" json:"minScore"`           // Floor (default: 0.1)
	MaxScore      float64 `mapstructure:"maxScore" json:"maxScore"`           // Cap (default: 5.0)
	WarmupTurns   int     `mapstructure:"warmupTurns" json:"warmupTurns"`     // Turns before activation (default: 50)
}

AutoAdjustConfig controls relevance score auto-adjustment. Primarily affects LIKE fallback search path and coordinator merge priority.

type AutoEnabledSet added in v0.7.0

type AutoEnabledSet struct {
	Knowledge bool `json:"knowledge,omitempty"`
	Memory    bool `json:"memory,omitempty"`
	Retrieval bool `json:"retrieval,omitempty"`
	Embedding bool `json:"embedding,omitempty"`
}

AutoEnabledSet records which context subsystems were auto-enabled.

func ResolveContextAutoEnable added in v0.7.0

func ResolveContextAutoEnable(cfg *Config, explicitKeys map[string]bool) AutoEnabledSet

ResolveContextAutoEnable sets Enabled for context subsystems that are not explicitly configured by the user when their config-level dependencies are detectable. This is a shared resolver: both config.Load() and bootstrap call it so that app runtime and CLI diagnostics see the same resolved values.

explicitKeys: keys the user explicitly set. nil means "nothing explicit" (legacy profiles, new profiles) → auto-enable all detectable features.

type AzureKVConfig

type AzureKVConfig struct {
	// VaultURL is the Azure Key Vault URL (e.g. "https://myvault.vault.azure.net").
	VaultURL string `mapstructure:"vaultUrl" json:"vaultUrl"`

	// KeyVersion is the specific key version to use (empty = latest).
	KeyVersion string `mapstructure:"keyVersion" json:"keyVersion,omitempty"`
}

AzureKVConfig defines Azure Key Vault specific settings.

type BackgroundConfig

type BackgroundConfig struct {
	// Enable the background task system.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Time in milliseconds before an agent turn is auto-yielded to background.
	YieldMs int `mapstructure:"yieldMs" json:"yieldMs"`

	// Maximum number of concurrently running background tasks.
	MaxConcurrentTasks int `mapstructure:"maxConcurrentTasks" json:"maxConcurrentTasks"`

	// TaskTimeout is the maximum duration for a single background task (default: 30m).
	TaskTimeout time.Duration `mapstructure:"taskTimeout" json:"taskTimeout"`

	// Default delivery channels when channel is not specified (e.g. ["telegram"]).
	DefaultDeliverTo []string `mapstructure:"defaultDeliverTo" json:"defaultDeliverTo"`
}

BackgroundConfig defines background task execution settings.

type BrowserToolConfig

type BrowserToolConfig struct {
	// Enable browser tools (requires Chromium)
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Run headless
	Headless bool `mapstructure:"headless" json:"headless"`

	// Path to browser binary (empty = auto-detect via launcher.LookPath)
	BrowserBin string `mapstructure:"browserBin" json:"browserBin"`

	// Session timeout
	SessionTimeout time.Duration `mapstructure:"sessionTimeout" json:"sessionTimeout"`
}

BrowserToolConfig defines browser automation settings

type BudgetCfg added in v0.7.0

type BudgetCfg struct {
	// ToolCallLimit mirrors the inner executor's max turns (default: 50).
	ToolCallLimit int `mapstructure:"toolCallLimit" json:"toolCallLimit"`

	// DelegationLimit is the max delegations before alerting (default: 15).
	DelegationLimit int `mapstructure:"delegationLimit" json:"delegationLimit"`

	// AlertThreshold is the percentage at which budget alerts fire (default: 0.8).
	AlertThreshold float64 `mapstructure:"alertThreshold" json:"alertThreshold"`
}

BudgetCfg configures observational budget tracking.

type BudgetConfig added in v0.5.0

type BudgetConfig struct {
	// DefaultMax is the default maximum budget per task in USDC (e.g. "10.00").
	DefaultMax string `mapstructure:"defaultMax" json:"defaultMax"`

	// AlertThresholds are percentage thresholds that trigger budget alerts (e.g. [0.5, 0.8, 0.95]).
	AlertThresholds []float64 `mapstructure:"alertThresholds" json:"alertThresholds"`

	// HardLimit enforces budget as a hard cap (rejects overspend). Default: true.
	HardLimit *bool `mapstructure:"hardLimit" json:"hardLimit"`
}

BudgetConfig defines per-task spending limits.

type ChannelsConfig

type ChannelsConfig struct {
	Telegram TelegramConfig `mapstructure:"telegram" json:"telegram"`
	Discord  DiscordConfig  `mapstructure:"discord" json:"discord"`
	Slack    SlackConfig    `mapstructure:"slack" json:"slack"`
}

ChannelsConfig holds all channel configurations

type CheckpointConfig added in v0.7.0

type CheckpointConfig struct {
	// AutoOnStepComplete creates a checkpoint when a RunLedger step passes validation.
	AutoOnStepComplete bool `mapstructure:"autoOnStepComplete" json:"autoOnStepComplete"`

	// AutoOnPolicy creates a checkpoint when a policy decision is applied.
	AutoOnPolicy bool `mapstructure:"autoOnPolicy" json:"autoOnPolicy"`

	// MaxPerSession limits the number of checkpoints per session (0 = unlimited).
	MaxPerSession int `mapstructure:"maxPerSession" json:"maxPerSession"`

	// RetentionDays is how long checkpoints are kept before pruning (0 = unlimited).
	RetentionDays int `mapstructure:"retentionDays" json:"retentionDays"`
}

CheckpointConfig defines checkpoint behavior.

type CircuitBreakerCfg added in v0.7.0

type CircuitBreakerCfg struct {
	// FailureThreshold is consecutive failures before circuit opens (default: 3).
	FailureThreshold int `mapstructure:"failureThreshold" json:"failureThreshold"`

	// ResetTimeout is how long before half-open probe (default: 30s).
	ResetTimeout time.Duration `mapstructure:"resetTimeout" json:"resetTimeout"`
}

CircuitBreakerCfg configures per-agent circuit breaking.

type Config

type Config struct {
	// DataRoot is the root directory for all lango data files (default: ~/.lango/).
	// All configurable data paths (database, graph, skills, etc.) must reside under this directory.
	// This can be overridden (e.g., for Docker: /data/lango/) but all sub-paths must stay under it.
	DataRoot string `mapstructure:"dataRoot" json:"dataRoot,omitempty"`

	// Server configuration
	Server ServerConfig `mapstructure:"server" json:"server"`

	// Agent configuration
	Agent AgentConfig `mapstructure:"agent" json:"agent"`

	// Channel configurations
	Channels ChannelsConfig `mapstructure:"channels" json:"channels"`

	// Logging configuration
	Logging LoggingConfig `mapstructure:"logging" json:"logging"`

	// Session configuration
	Session SessionConfig `mapstructure:"session" json:"session"`

	// Tools configuration
	Tools ToolsConfig `mapstructure:"tools" json:"tools"`

	// Hooks configuration (tool execution hooks)
	Hooks HooksConfig `mapstructure:"hooks" json:"hooks"`

	// Auth configuration
	Auth AuthConfig `mapstructure:"auth" json:"auth"`

	// Security configuration
	Security SecurityConfig `mapstructure:"security" json:"security"`

	// Knowledge configuration
	Knowledge KnowledgeConfig `mapstructure:"knowledge" json:"knowledge"`

	// Observational Memory configuration
	ObservationalMemory ObservationalMemoryConfig `mapstructure:"observationalMemory" json:"observationalMemory"`

	// Embedding / RAG configuration
	Embedding EmbeddingConfig `mapstructure:"embedding" json:"embedding"`

	// Graph store configuration
	Graph GraphConfig `mapstructure:"graph" json:"graph"`

	// A2A protocol configuration
	A2A A2AConfig `mapstructure:"a2a" json:"a2a"`

	// Payment configuration (blockchain micropayments)
	Payment PaymentConfig `mapstructure:"payment" json:"payment"`

	// Cron scheduling configuration
	Cron CronConfig `mapstructure:"cron" json:"cron"`

	// Background task execution configuration
	Background BackgroundConfig `mapstructure:"background" json:"background"`

	// Workflow engine configuration
	Workflow WorkflowConfig `mapstructure:"workflow" json:"workflow"`

	// Skill configuration (file-based skills)
	Skill SkillConfig `mapstructure:"skill" json:"skill"`

	// Librarian configuration (proactive knowledge agent)
	Librarian LibrarianConfig `mapstructure:"librarian" json:"librarian"`

	// P2P network configuration
	P2P P2PConfig `mapstructure:"p2p" json:"p2p"`

	// Agent Memory configuration (per-agent persistent memory)
	AgentMemory AgentMemoryConfig `mapstructure:"agentMemory" json:"agentMemory"`

	// MCP server integration configuration
	MCP MCPConfig `mapstructure:"mcp" json:"mcp"`

	// Economy layer configuration (budget, risk, escrow, pricing, negotiation)
	Economy EconomyConfig `mapstructure:"economy" json:"economy"`

	// Smart Account configuration (ERC-7579 modular accounts)
	SmartAccount SmartAccountConfig `mapstructure:"smartAccount" json:"smartAccount"`

	// Retrieval coordinator configuration (agentic retrieval)
	Retrieval RetrievalConfig `mapstructure:"retrieval" json:"retrieval"`

	// Gatekeeper configuration (response sanitization)
	Gatekeeper GatekeeperConfig `mapstructure:"gatekeeper" json:"gatekeeper"`

	// Observability configuration (token tracking, health, audit, metrics)
	Observability ObservabilityConfig `mapstructure:"observability" json:"observability"`

	// Alerting configuration (operational alert thresholds and delivery)
	Alerting AlertingConfig `mapstructure:"alerting" json:"alerting"`

	// RunLedger configuration (Task OS — durable execution engine)
	RunLedger RunLedgerConfig `mapstructure:"runLedger" json:"runLedger"`

	// Provenance configuration (session checkpoints, attribution, session tree)
	Provenance ProvenanceConfig `mapstructure:"provenance" json:"provenance"`

	// Sandbox configuration (OS-level tool execution isolation)
	Sandbox SandboxConfig `mapstructure:"sandbox" json:"sandbox"`

	// Ontology subsystem configuration (typed objects and predicates)
	Ontology OntologyConfig `mapstructure:"ontology" json:"ontology,omitempty"`

	// ContextProfile selects a named preset that bundles context subsystem settings.
	// Valid values: "off", "lite", "balanced", "full", or empty (no profile).
	ContextProfile ContextProfileName `mapstructure:"contextProfile" json:"contextProfile,omitempty"`

	// Context budget configuration (advanced). contextProfile stays top-level;
	// these settings control token budget allocation across prompt sections.
	Context ContextConfig `mapstructure:"context" json:"context"`

	// Providers configuration
	Providers map[string]ProviderConfig `mapstructure:"providers" json:"providers"`
}

Config is the root configuration structure for lango

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config with sensible defaults

func PresetConfig added in v0.6.0

func PresetConfig(name string) *Config

PresetConfig returns a Config for the given preset name. Unknown names return DefaultConfig().

func (*Config) Clone added in v0.7.0

func (c *Config) Clone() *Config

Clone returns a deep copy of the Config via JSON roundtrip.

func (*Config) MigrateEmbeddingProvider

func (c *Config) MigrateEmbeddingProvider()

MigrateEmbeddingProvider migrates legacy configs that use separate ProviderID and Provider fields into the unified Provider field, and consolidates the deprecated Local.Model into the canonical Model field.

func (*Config) ProbeEmbeddingProvider added in v0.7.0

func (c *Config) ProbeEmbeddingProvider() string

ProbeEmbeddingProvider scans the configured providers map for an embedding-capable provider and returns its key. Returns "" if no suitable provider is found.

Policy (conservative, cost-aware):

  • Local-first: Ollama always preferred if configured
  • Single-remote-only: if exactly one remote embedding-capable provider → use it
  • Multiple-remote → no auto-select (require explicit embedding.provider)

func (*Config) ResolveEmbeddingProvider

func (c *Config) ResolveEmbeddingProvider() (backendType, apiKey string)

ResolveEmbeddingProvider returns the embedding backend type and API key for the configured embedding provider. The Provider field can be "local" (Ollama) or a key in the providers map. Legacy configs with ProviderID are handled via MigrateEmbeddingProvider.

type ContainerSandboxConfig

type ContainerSandboxConfig struct {
	// Enabled activates container-based sandbox instead of subprocess isolation.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// RequireContainer enforces fail-closed behavior: when true and no container
	// runtime (Docker/gVisor) is available, tool execution is refused instead of
	// silently falling back to NativeRuntime. Defaults to true for security.
	RequireContainer bool `mapstructure:"requireContainer" json:"requireContainer"`

	// Runtime selects the container runtime: "auto", "docker", "gvisor", or "native" (default: "auto").
	Runtime string `mapstructure:"runtime" json:"runtime"`

	// Image is the Docker image for the sandbox container (default: "lango-sandbox:latest").
	Image string `mapstructure:"image" json:"image"`

	// NetworkMode is the Docker network mode for sandbox containers (default: "none").
	NetworkMode string `mapstructure:"networkMode" json:"networkMode"`

	// ReadOnlyRootfs mounts the container root filesystem as read-only (default: true).
	ReadOnlyRootfs *bool `mapstructure:"readOnlyRootfs" json:"readOnlyRootfs"`

	// CPUQuotaUS is the Docker CPU quota in microseconds (0 = unlimited).
	CPUQuotaUS int64 `mapstructure:"cpuQuotaUs" json:"cpuQuotaUs"`

	// PoolSize is the number of pre-warmed containers in the pool (0 = disabled).
	PoolSize int `mapstructure:"poolSize" json:"poolSize"`

	// PoolIdleTimeout is the idle timeout before pool containers are recycled (default: 5m).
	PoolIdleTimeout time.Duration `mapstructure:"poolIdleTimeout" json:"poolIdleTimeout"`
}

ContainerSandboxConfig configures container-based tool execution isolation.

type ContextAllocationConfig added in v0.7.0

type ContextAllocationConfig struct {
	Knowledge  float64 `mapstructure:"knowledge" json:"knowledge"`
	RAG        float64 `mapstructure:"rag" json:"rag"`
	Memory     float64 `mapstructure:"memory" json:"memory"`
	RunSummary float64 `mapstructure:"runSummary" json:"runSummary"`
	Headroom   float64 `mapstructure:"headroom" json:"headroom"`
}

ContextAllocationConfig defines per-section token allocation ratios.

type ContextConfig added in v0.7.0

type ContextConfig struct {
	// ModelWindow overrides the auto-detected model context window size (tokens).
	// 0 = auto-detect from model registry.
	ModelWindow int `mapstructure:"modelWindow" json:"modelWindow"`

	// ResponseReserve overrides the response token reserve.
	// 0 = use agent.maxTokens. Clamped to [1024, 25% of modelWindow].
	ResponseReserve int `mapstructure:"responseReserve" json:"responseReserve"`

	// Allocation controls the ratio of available tokens allocated to each section.
	// All values must sum to 1.0.
	Allocation ContextAllocationConfig `mapstructure:"allocation" json:"allocation"`
}

ContextConfig controls token budget allocation across prompt sections. These are advanced settings; most users should use contextProfile instead.

type ContextProfileName added in v0.7.0

type ContextProfileName string

ContextProfileName identifies a named context configuration preset.

const (
	// ContextProfileOff disables all context subsystems.
	ContextProfileOff ContextProfileName = "off"
	// ContextProfileLite enables knowledge and observational memory only.
	ContextProfileLite ContextProfileName = "lite"
	// ContextProfileBalanced enables knowledge, memory, and librarian.
	ContextProfileBalanced ContextProfileName = "balanced"
	// ContextProfileFull enables all context subsystems including graph.
	ContextProfileFull ContextProfileName = "full"
)

type CronConfig

type CronConfig struct {
	// Enable the cron scheduling system.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Default timezone for cron schedules (e.g. "Asia/Seoul").
	Timezone string `mapstructure:"timezone" json:"timezone"`

	// Maximum number of concurrently executing jobs.
	MaxConcurrentJobs int `mapstructure:"maxConcurrentJobs" json:"maxConcurrentJobs"`

	// Default session mode for jobs: "isolated" or "main".
	DefaultSessionMode string `mapstructure:"defaultSessionMode" json:"defaultSessionMode"`

	// How long to retain job execution history (e.g. "30d", "720h").
	HistoryRetention string `mapstructure:"historyRetention" json:"historyRetention"`

	// DefaultJobTimeout is the maximum duration for a single job execution (default: 30m).
	DefaultJobTimeout time.Duration `mapstructure:"defaultJobTimeout" json:"defaultJobTimeout"`

	// Default delivery channels when deliver_to is not specified (e.g. ["telegram"]).
	DefaultDeliverTo []string `mapstructure:"defaultDeliverTo" json:"defaultDeliverTo"`
}

CronConfig defines cron scheduling settings.

type DBEncryptionConfig

type DBEncryptionConfig struct {
	// Enabled activates SQLCipher encryption for the application database.
	Enabled bool `mapstructure:"enabled" json:"enabled"`
	// CipherPageSize is the SQLCipher cipher_page_size PRAGMA (default: 4096).
	CipherPageSize int `mapstructure:"cipherPageSize" json:"cipherPageSize"`
}

DBEncryptionConfig defines SQLCipher transparent database encryption settings.

type DiscordConfig

type DiscordConfig struct {
	// Enable Discord channel
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Bot token from Discord Developer Portal
	BotToken string `mapstructure:"botToken" json:"botToken"`

	// Application ID for slash commands
	ApplicationID string `mapstructure:"applicationId" json:"applicationId"`

	// Allowed guild IDs (empty = allow all)
	AllowedGuilds []string `mapstructure:"allowedGuilds" json:"allowedGuilds"`
}

DiscordConfig defines Discord bot settings

type DynamicPricingConfig added in v0.5.0

type DynamicPricingConfig struct {
	// Enabled activates dynamic pricing.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// TrustDiscount is the max discount for high-trust peers (0-1, default: 0.1).
	TrustDiscount float64 `mapstructure:"trustDiscount" json:"trustDiscount"`

	// VolumeDiscount is the max discount for high-volume peers (0-1, default: 0.05).
	VolumeDiscount float64 `mapstructure:"volumeDiscount" json:"volumeDiscount"`

	// MinPrice is the minimum price floor in USDC (e.g. "0.01").
	MinPrice string `mapstructure:"minPrice" json:"minPrice"`
}

DynamicPricingConfig defines dynamic pricing adjustment settings.

type EconomyConfig added in v0.5.0

type EconomyConfig struct {
	// Enabled activates the economy layer.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Budget controls per-task spending limits.
	Budget BudgetConfig `mapstructure:"budget" json:"budget"`

	// Risk configures trust-based payment strategy routing.
	Risk RiskConfig `mapstructure:"risk" json:"risk"`

	// Negotiate configures the P2P negotiation protocol.
	Negotiate NegotiationConfig `mapstructure:"negotiate" json:"negotiate"`

	// Escrow configures the milestone-based escrow service.
	Escrow EscrowConfig `mapstructure:"escrow" json:"escrow"`

	// Pricing configures dynamic pricing adjustments.
	Pricing DynamicPricingConfig `mapstructure:"pricing" json:"pricing"`
}

EconomyConfig defines P2P economy layer settings (budget, risk, escrow, pricing, negotiation).

type EmbeddingConfig

type EmbeddingConfig struct {
	// Provider selects the embedding provider. Set to "local" for Ollama-based
	// local embeddings, or use a key from the providers map (e.g., "my-openai",
	// "gemini-1") to resolve the backend type and API key automatically.
	Provider string `mapstructure:"provider" json:"provider"`

	// Deprecated: ProviderID is kept only for backwards-compatible config loading.
	// New configs should use Provider for both local and remote providers.
	ProviderID string `mapstructure:"providerID" json:"providerID,omitempty"`

	// Model is the embedding model identifier.
	Model string `mapstructure:"model" json:"model"`

	// Dimensions is the embedding vector dimensionality.
	Dimensions int `mapstructure:"dimensions" json:"dimensions"`

	// Local holds settings for the local (Ollama) provider.
	Local LocalEmbeddingConfig `mapstructure:"local" json:"local"`

	// RAG holds retrieval-augmented generation settings.
	RAG RAGConfig `mapstructure:"rag" json:"rag"`
}

EmbeddingConfig defines embedding and RAG settings.

type EscrowConfig added in v0.5.0

type EscrowConfig struct {
	// Enabled activates the escrow service.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// DefaultTimeout is the escrow expiration timeout (default: 24h).
	DefaultTimeout time.Duration `mapstructure:"defaultTimeout" json:"defaultTimeout"`

	// MaxMilestones is the maximum milestones per escrow (default: 10).
	MaxMilestones int `mapstructure:"maxMilestones" json:"maxMilestones"`

	// AutoRelease releases funds automatically when all milestones are met.
	AutoRelease bool `mapstructure:"autoRelease" json:"autoRelease"`

	// DisputeWindow is the time window for raising disputes after completion (default: 1h).
	DisputeWindow time.Duration `mapstructure:"disputeWindow" json:"disputeWindow"`

	// Settlement configures on-chain settlement for escrow.
	Settlement EscrowSettlementConfig `mapstructure:"settlement" json:"settlement"`

	// OnChain configures the on-chain escrow hub/vault system.
	OnChain EscrowOnChainConfig `mapstructure:"onChain" json:"onChain"`
}

EscrowConfig defines milestone-based escrow settings.

type EscrowOnChainConfig added in v0.5.0

type EscrowOnChainConfig struct {
	// Enabled activates on-chain escrow mode.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Mode selects the on-chain escrow pattern: "hub" or "vault".
	Mode string `mapstructure:"mode" json:"mode"`

	// ContractVersion selects the contract version: "v1" or "v2" (default: auto-detect).
	ContractVersion string `mapstructure:"contractVersion" json:"contractVersion"`

	// HubAddress is the deployed LangoEscrowHub contract address.
	HubAddress string `mapstructure:"hubAddress" json:"hubAddress"`

	// HubV2Address is the deployed LangoEscrowHubV2 proxy address (UUPS).
	HubV2Address string `mapstructure:"hubV2Address" json:"hubV2Address"`

	// VaultFactoryAddress is the deployed LangoVaultFactory contract address.
	VaultFactoryAddress string `mapstructure:"vaultFactoryAddress" json:"vaultFactoryAddress"`

	// VaultImplementation is the LangoVault implementation address for cloning.
	VaultImplementation string `mapstructure:"vaultImplementation" json:"vaultImplementation"`

	// BeaconAddress is the UpgradeableBeacon address for V2 vaults.
	BeaconAddress string `mapstructure:"beaconAddress" json:"beaconAddress"`

	// BeaconFactoryAddress is the LangoBeaconVaultFactory address for V2 vaults.
	BeaconFactoryAddress string `mapstructure:"beaconFactoryAddress" json:"beaconFactoryAddress"`

	// DirectSettlerAddress is the deployed DirectSettler contract address (V2).
	DirectSettlerAddress string `mapstructure:"directSettlerAddress" json:"directSettlerAddress"`

	// MilestoneSettlerAddress is the deployed MilestoneSettler contract address (V2).
	MilestoneSettlerAddress string `mapstructure:"milestoneSettlerAddress" json:"milestoneSettlerAddress"`

	// ArbitratorAddress is the dispute arbitrator address.
	ArbitratorAddress string `mapstructure:"arbitratorAddress" json:"arbitratorAddress"`

	// PollInterval is the event monitor polling interval (default: 15s).
	PollInterval time.Duration `mapstructure:"pollInterval" json:"pollInterval"`

	// ConfirmationDepth is the number of blocks to wait before processing events
	// to protect against L2 reorgs (default: 2 for Base L2).
	ConfirmationDepth uint64 `mapstructure:"confirmationDepth" json:"confirmationDepth"`

	// TokenAddress is the ERC-20 token (USDC) contract address.
	TokenAddress string `mapstructure:"tokenAddress" json:"tokenAddress"`
}

EscrowOnChainConfig configures on-chain escrow contract integration.

func (EscrowOnChainConfig) IsV2 added in v0.6.0

func (c EscrowOnChainConfig) IsV2() bool

IsV2 returns true if the on-chain config uses V2 contracts. Auto-detects based on HubV2Address presence when ContractVersion is empty.

type EscrowSettlementConfig added in v0.5.0

type EscrowSettlementConfig struct {
	// ReceiptTimeout is the maximum wait for on-chain confirmation (default: 2m).
	ReceiptTimeout time.Duration `mapstructure:"receiptTimeout" json:"receiptTimeout"`

	// MaxRetries is the maximum transaction submission attempts (default: 3).
	MaxRetries int `mapstructure:"maxRetries" json:"maxRetries"`
}

EscrowSettlementConfig configures on-chain settlement parameters for escrow.

type ExecToolConfig

type ExecToolConfig struct {
	// Default timeout for commands
	DefaultTimeout time.Duration `mapstructure:"defaultTimeout" json:"defaultTimeout"`

	// Allow background processes
	AllowBackground bool `mapstructure:"allowBackground" json:"allowBackground"`

	// Working directory (empty = current)
	WorkDir string `mapstructure:"workDir" json:"workDir"`

	// AdditionalProtectedPaths specifies extra paths that the exec tool
	// should block access to (in addition to the DataRoot).
	AdditionalProtectedPaths []string `mapstructure:"additionalProtectedPaths" json:"additionalProtectedPaths,omitempty"`
}

ExecToolConfig defines shell execution settings

type FilesystemToolConfig

type FilesystemToolConfig struct {
	// Maximum file size to read
	MaxReadSize int64 `mapstructure:"maxReadSize" json:"maxReadSize"`

	// Allowed paths (empty = allow all)
	AllowedPaths []string `mapstructure:"allowedPaths" json:"allowedPaths"`
}

FilesystemToolConfig defines file access settings

type FirewallRule

type FirewallRule struct {
	// PeerDID is the DID of the peer this rule applies to ("*" for all).
	PeerDID string `mapstructure:"peerDid" json:"peerDid"`

	// Action is "allow" or "deny".
	Action string `mapstructure:"action" json:"action"`

	// Tools lists tool name patterns this rule applies to.
	Tools []string `mapstructure:"tools" json:"tools"`

	// RateLimit is the maximum requests per minute (0 = unlimited).
	RateLimit int `mapstructure:"rateLimit" json:"rateLimit"`
}

FirewallRule defines an ACL rule for the knowledge firewall.

type GatekeeperConfig added in v0.6.0

type GatekeeperConfig struct {
	// Master switch (nil defaults to true — enabled by default)
	Enabled *bool `mapstructure:"enabled" json:"enabled"`

	// Strip <thought>/<thinking> tags from responses
	StripThoughtTags *bool `mapstructure:"stripThoughtTags" json:"stripThoughtTags"`

	// Strip lines starting with [INTERNAL], [DEBUG], [SYSTEM], [OBSERVATION]
	StripInternalMarkers *bool `mapstructure:"stripInternalMarkers" json:"stripInternalMarkers"`

	// Replace large raw JSON code blocks with a placeholder
	StripRawJSON *bool `mapstructure:"stripRawJSON" json:"stripRawJSON"`

	// Character threshold for raw JSON replacement (default: 500)
	RawJSONThreshold int `mapstructure:"rawJsonThreshold" json:"rawJsonThreshold"`

	// Additional regex patterns to strip from responses
	CustomPatterns []string `mapstructure:"customPatterns" json:"customPatterns"`
}

GatekeeperConfig defines response sanitization (output gatekeeper) settings.

type GraphConfig

type GraphConfig struct {
	// Enable the graph store.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Backend type: "bolt" (default, embedded BoltDB) or "rocksdb".
	Backend string `mapstructure:"backend" json:"backend"`

	// DatabasePath is the file path for the graph database.
	// Defaults to a "graph.db" file next to the session database.
	DatabasePath string `mapstructure:"databasePath" json:"databasePath"`

	// MaxTraversalDepth limits graph expansion depth (default: 2).
	MaxTraversalDepth int `mapstructure:"maxTraversalDepth" json:"maxTraversalDepth"`

	// MaxExpansionResults limits how many graph-expanded results to return (default: 10).
	MaxExpansionResults int `mapstructure:"maxExpansionResults" json:"maxExpansionResults"`
}

GraphConfig defines graph store settings for relationship-aware retrieval.

type HealthConfig added in v0.5.0

type HealthConfig struct {
	// Enabled activates health checks (default: true when observability is enabled).
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Interval is the health check interval (default: 30s).
	Interval time.Duration `mapstructure:"interval" json:"interval"`
}

HealthConfig defines health check settings.

type HooksConfig added in v0.4.0

type HooksConfig struct {
	// Enabled activates the hook system (default: true when multi-agent is enabled).
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// SecurityFilter enables the security filter hook that blocks dangerous commands.
	SecurityFilter bool `mapstructure:"securityFilter" json:"securityFilter"`

	// AccessControl enables per-agent tool access control.
	AccessControl bool `mapstructure:"accessControl" json:"accessControl"`

	// EventPublishing enables publishing tool execution events to the event bus.
	EventPublishing bool `mapstructure:"eventPublishing" json:"eventPublishing"`

	// KnowledgeSave enables automatic knowledge saving from tool results.
	KnowledgeSave bool `mapstructure:"knowledgeSave" json:"knowledgeSave"`

	// BlockedCommands is a list of command patterns to block (security filter).
	BlockedCommands []string `mapstructure:"blockedCommands" json:"blockedCommands"`
}

HooksConfig defines tool execution hook settings.

type InterceptorConfig

type InterceptorConfig struct {
	Enabled             bool              `mapstructure:"enabled" json:"enabled"`
	RedactPII           bool              `mapstructure:"redactPii" json:"redactPii"`
	ApprovalPolicy      ApprovalPolicy    `mapstructure:"approvalPolicy" json:"approvalPolicy"` // default: "dangerous"
	HeadlessAutoApprove bool              `mapstructure:"headlessAutoApprove" json:"headlessAutoApprove"`
	NotifyChannel       string            `mapstructure:"notifyChannel" json:"notifyChannel"` // e.g. "discord", "telegram"
	SensitiveTools      []string          `mapstructure:"sensitiveTools" json:"sensitiveTools"`
	ExemptTools         []string          `mapstructure:"exemptTools" json:"exemptTools"` // Tools exempt from approval regardless of policy
	PIIRegexPatterns    []string          `mapstructure:"piiRegexPatterns" json:"piiRegexPatterns"`
	ApprovalTimeoutSec  int               `mapstructure:"approvalTimeoutSec" json:"approvalTimeoutSec"` // default 30
	PIIDisabledPatterns []string          `mapstructure:"piiDisabledPatterns" json:"piiDisabledPatterns"`
	PIICustomPatterns   map[string]string `mapstructure:"piiCustomPatterns" json:"piiCustomPatterns"`
	Presidio            PresidioConfig    `mapstructure:"presidio" json:"presidio"`
}

InterceptorConfig defines AI Privacy Interceptor settings

type KMSConfig

type KMSConfig struct {
	// Region is the cloud region for KMS API calls (e.g. "us-east-1", "us-central1").
	Region string `mapstructure:"region" json:"region"`

	// KeyID is the KMS key identifier (ARN, resource name, or alias).
	KeyID string `mapstructure:"keyId" json:"keyId"`

	// Endpoint is an optional custom endpoint for KMS API calls (useful for testing).
	Endpoint string `mapstructure:"endpoint" json:"endpoint,omitempty"`

	// FallbackToLocal enables automatic fallback to the local CryptoProvider when KMS is unavailable.
	FallbackToLocal bool `mapstructure:"fallbackToLocal" json:"fallbackToLocal"`

	// TimeoutPerOperation is the maximum duration for a single KMS API call (default: 5s).
	TimeoutPerOperation time.Duration `mapstructure:"timeoutPerOperation" json:"timeoutPerOperation"`

	// MaxRetries is the number of retry attempts for transient KMS errors (default: 3).
	MaxRetries int `mapstructure:"maxRetries" json:"maxRetries"`

	// Azure holds Azure Key Vault specific settings.
	Azure AzureKVConfig `mapstructure:"azure" json:"azure"`

	// PKCS11 holds PKCS#11 HSM specific settings.
	PKCS11 PKCS11Config `mapstructure:"pkcs11" json:"pkcs11"`
}

KMSConfig defines Cloud KMS and HSM backend settings.

type KnowledgeConfig

type KnowledgeConfig struct {
	// Enable the knowledge/learning system
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Maximum context items per layer in retrieval
	MaxContextPerLayer int `mapstructure:"maxContextPerLayer" json:"maxContextPerLayer"`

	// AnalysisTurnThreshold is the number of new turns before triggering conversation analysis (default: 10).
	AnalysisTurnThreshold int `mapstructure:"analysisTurnThreshold" json:"analysisTurnThreshold"`

	// AnalysisTokenThreshold is the token count before triggering conversation analysis (default: 2000).
	AnalysisTokenThreshold int `mapstructure:"analysisTokenThreshold" json:"analysisTokenThreshold"`
}

KnowledgeConfig defines self-learning knowledge system settings

type LibrarianConfig

type LibrarianConfig struct {
	// Enable the proactive librarian system.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Minimum observation count to trigger analysis (default: 2).
	ObservationThreshold int `mapstructure:"observationThreshold" json:"observationThreshold"`

	// Turns between inquiries per session (default: 3).
	InquiryCooldownTurns int `mapstructure:"inquiryCooldownTurns" json:"inquiryCooldownTurns"`

	// Maximum pending inquiries per session (default: 2).
	MaxPendingInquiries int `mapstructure:"maxPendingInquiries" json:"maxPendingInquiries"`

	// Minimum confidence level for auto-save: "high", "medium", "low" (default: "high").
	AutoSaveConfidence types.Confidence `mapstructure:"autoSaveConfidence" json:"autoSaveConfidence"`

	// LLM provider for analysis (empty = use agent default).
	Provider string `mapstructure:"provider" json:"provider"`

	// Model ID for analysis (empty = use agent default).
	Model string `mapstructure:"model" json:"model"`
}

LibrarianConfig defines proactive knowledge librarian settings.

type LoadResult added in v0.7.0

type LoadResult struct {
	Config       *Config         `json:"config"`
	ExplicitKeys map[string]bool `json:"explicitKeys,omitempty"`
	AutoEnabled  AutoEnabledSet  `json:"autoEnabled,omitempty"`
}

LoadResult holds the configuration and metadata produced by Load().

func Load

func Load(configPath string) (*LoadResult, error)

Load reads configuration from file and environment. Returns LoadResult with the Config, explicitly-set keys, and auto-enable metadata.

type LocalEmbeddingConfig

type LocalEmbeddingConfig struct {
	// BaseURL is the Ollama endpoint (default: http://localhost:11434/v1).
	BaseURL string `mapstructure:"baseUrl" json:"baseUrl"`
	// Deprecated: Model is now unified in EmbeddingConfig.Model for all providers.
	// Retained only for backward-compatible config loading and migration.
	Model string `mapstructure:"model" json:"model,omitempty"`
}

LocalEmbeddingConfig defines settings for a local embedding provider.

type LoggingConfig

type LoggingConfig struct {
	// Log level (debug, info, warn, error)
	Level string `mapstructure:"level" json:"level"`

	// Output format (json, console)
	Format string `mapstructure:"format" json:"format"`

	// Output file path (empty = stdout)
	OutputPath string `mapstructure:"outputPath" json:"outputPath"`
}

LoggingConfig defines logging settings

type MCPConfig added in v0.4.0

type MCPConfig struct {
	// Enable MCP server integration
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Servers is a map of named MCP server configurations.
	Servers map[string]MCPServerConfig `mapstructure:"servers" json:"servers"`

	// DefaultTimeout for MCP operations (default: 30s)
	DefaultTimeout time.Duration `mapstructure:"defaultTimeout" json:"defaultTimeout"`

	// MaxOutputTokens limits the output size from MCP tool calls (default: 25000)
	MaxOutputTokens int `mapstructure:"maxOutputTokens" json:"maxOutputTokens"`

	// HealthCheckInterval for periodic server health probes (default: 30s)
	HealthCheckInterval time.Duration `mapstructure:"healthCheckInterval" json:"healthCheckInterval"`

	// AutoReconnect enables automatic reconnection on connection loss (default: true)
	AutoReconnect bool `mapstructure:"autoReconnect" json:"autoReconnect"`

	// MaxReconnectAttempts limits reconnection attempts (default: 5)
	MaxReconnectAttempts int `mapstructure:"maxReconnectAttempts" json:"maxReconnectAttempts"`
}

MCPConfig defines MCP (Model Context Protocol) server integration settings.

type MCPServerConfig added in v0.4.0

type MCPServerConfig struct {
	// Transport type: "stdio" (default), "http", "sse"
	Transport string `mapstructure:"transport" json:"transport"`

	// Command is the executable for stdio transport.
	Command string `mapstructure:"command" json:"command"`

	// Args are command-line arguments for stdio transport.
	Args []string `mapstructure:"args" json:"args"`

	// Env are environment variables for stdio transport (supports ${VAR} expansion).
	Env map[string]string `mapstructure:"env" json:"env"`

	// URL is the endpoint for http/sse transport.
	URL string `mapstructure:"url" json:"url"`

	// Headers are HTTP headers for http/sse transport (supports ${VAR} expansion).
	Headers map[string]string `mapstructure:"headers" json:"headers"`

	// Enabled controls whether this server is active (default: true when nil).
	Enabled *bool `mapstructure:"enabled" json:"enabled"`

	// Timeout overrides the global default timeout for this server.
	Timeout time.Duration `mapstructure:"timeout" json:"timeout"`

	// SafetyLevel for tools from this server: "safe", "moderate", "dangerous" (default: "dangerous")
	SafetyLevel string `mapstructure:"safetyLevel" json:"safetyLevel"`
}

MCPServerConfig defines a single MCP server connection.

func (MCPServerConfig) IsEnabled added in v0.4.0

func (s MCPServerConfig) IsEnabled() bool

IsEnabled returns whether the server is enabled (defaults to true when nil).

type MetricsExportConfig added in v0.5.0

type MetricsExportConfig struct {
	// Enabled activates metrics export endpoint.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Format is the metrics export format (default: "json").
	Format string `mapstructure:"format" json:"format"`
}

MetricsExportConfig defines metrics export settings.

type NegotiationConfig added in v0.5.0

type NegotiationConfig struct {
	// Enabled activates the P2P negotiation protocol.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// MaxRounds is the maximum number of counter-offers (default: 5).
	MaxRounds int `mapstructure:"maxRounds" json:"maxRounds"`

	// Timeout is the negotiation session timeout (default: 5m).
	Timeout time.Duration `mapstructure:"timeout" json:"timeout"`

	// AutoNegotiate enables automatic counter-offer generation.
	AutoNegotiate bool `mapstructure:"autoNegotiate" json:"autoNegotiate"`

	// MaxDiscount is the maximum discount percentage for auto-negotiation (0-1, default: 0.2).
	MaxDiscount float64 `mapstructure:"maxDiscount" json:"maxDiscount"`
}

NegotiationConfig defines P2P price negotiation settings.

type OIDCProviderConfig

type OIDCProviderConfig struct {
	IssuerURL    string   `mapstructure:"issuerUrl" json:"issuerUrl"`
	ClientID     string   `mapstructure:"clientId" json:"clientId"`
	ClientSecret string   `mapstructure:"clientSecret" json:"clientSecret"`
	RedirectURL  string   `mapstructure:"redirectUrl" json:"redirectUrl"`
	Scopes       []string `mapstructure:"scopes" json:"scopes"`
}

OIDCProviderConfig defines a single OIDC provider

type OSSandboxConfig added in v0.7.0

type OSSandboxConfig struct {
	// SeccompProfile selects the seccomp filter profile on Linux: "strict", "moderate", or "permissive".
	// Default: "moderate". NOT YET ENFORCED — the native (Landlock+seccomp)
	// backend is planned. The bwrap backend does not consume this field.
	SeccompProfile string `mapstructure:"seccompProfile" json:"seccompProfile,omitempty"`

	// SeatbeltCustomProfile is a path to a custom .sb profile on macOS (overrides generated profile).
	// Tilde and relative paths are normalized in PostLoad.
	SeatbeltCustomProfile string `mapstructure:"seatbeltCustomProfile" json:"seatbeltCustomProfile,omitempty"`
}

OSSandboxConfig holds platform-specific sandbox settings.

type ObservabilityConfig added in v0.5.0

type ObservabilityConfig struct {
	// Enabled activates the observability subsystem.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Tokens configures token usage tracking.
	Tokens TokenTrackingConfig `mapstructure:"tokens" json:"tokens"`

	// Health configures health check monitoring.
	Health HealthConfig `mapstructure:"health" json:"health"`

	// Audit configures audit log recording.
	Audit AuditConfig `mapstructure:"audit" json:"audit"`

	// Metrics configures metrics export format.
	Metrics MetricsExportConfig `mapstructure:"metrics" json:"metrics"`

	// TraceStore configures turn trace retention and cleanup.
	TraceStore TraceStoreConfig `mapstructure:"traceStore" json:"traceStore"`

	// Tracing configures OpenTelemetry distributed tracing.
	Tracing TracingConfig `mapstructure:"tracing" json:"tracing"`
}

ObservabilityConfig defines observability and monitoring settings.

type ObservationalMemoryConfig

type ObservationalMemoryConfig struct {
	// Enable the observational memory system
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// LLM provider for observer/reflector (empty = use agent default)
	Provider string `mapstructure:"provider" json:"provider"`

	// Model ID for observer/reflector (empty = use agent default)
	Model string `mapstructure:"model" json:"model"`

	// Token threshold to trigger observation (default: 1000)
	MessageTokenThreshold int `mapstructure:"messageTokenThreshold" json:"messageTokenThreshold"`

	// Token threshold to trigger reflection (default: 2000)
	ObservationTokenThreshold int `mapstructure:"observationTokenThreshold" json:"observationTokenThreshold"`

	// Max token budget for recent messages in context (default: 8000)
	MaxMessageTokenBudget int `mapstructure:"maxMessageTokenBudget" json:"maxMessageTokenBudget"`

	// MaxReflectionsInContext limits reflections injected into LLM context (default: 5, 0 = unlimited).
	MaxReflectionsInContext int `mapstructure:"maxReflectionsInContext" json:"maxReflectionsInContext"`

	// MaxObservationsInContext limits observations injected into LLM context (default: 20, 0 = unlimited).
	MaxObservationsInContext int `mapstructure:"maxObservationsInContext" json:"maxObservationsInContext"`

	// MemoryTokenBudget sets the max token budget for the memory section in system prompt (default: 4000).
	// Zero means use the default.
	MemoryTokenBudget int `mapstructure:"memoryTokenBudget" json:"memoryTokenBudget"`

	// ReflectionConsolidationThreshold is the min reflections before meta-reflection triggers (default: 5).
	// Zero means use the default.
	ReflectionConsolidationThreshold int `mapstructure:"reflectionConsolidationThreshold" json:"reflectionConsolidationThreshold"`
}

ObservationalMemoryConfig defines Observational Memory settings

type OntologyACLConfig added in v0.7.0

type OntologyACLConfig struct {
	// Enabled activates ACL policy enforcement.
	Enabled bool `mapstructure:"enabled" json:"enabled,omitempty"`
	// Roles maps principal names to permission levels ("read", "write", "admin").
	Roles map[string]string `mapstructure:"roles" json:"roles,omitempty"`
	// P2PPermission is the default permission for peer: prefix principals (default "read").
	P2PPermission string `mapstructure:"p2pPermission" json:"p2pPermission,omitempty"`
}

OntologyACLConfig configures role-based access control for ontology operations.

type OntologyConfig added in v0.7.0

type OntologyConfig struct {
	// Enabled activates the ontology registry and seed migration.
	Enabled bool `mapstructure:"enabled" json:"enabled,omitempty"`
	// ACL configures operation-level access control.
	ACL OntologyACLConfig `mapstructure:"acl" json:"acl,omitempty"`
	// Governance configures schema lifecycle management.
	Governance OntologyGovernanceConfig `mapstructure:"governance" json:"governance,omitempty"`
	// Exchange configures P2P ontology exchange.
	Exchange OntologyExchangeConfig `mapstructure:"exchange" json:"exchange,omitempty"`
}

OntologyConfig configures the ontology subsystem.

type OntologyExchangeConfig added in v0.7.0

type OntologyExchangeConfig struct {
	// Enabled activates P2P ontology exchange (requires both P2P and Ontology enabled).
	Enabled bool `mapstructure:"enabled" json:"enabled,omitempty"`
	// MinTrustForSchema is the minimum peer trust score for schema exchange (default 0.5).
	MinTrustForSchema float64 `mapstructure:"minTrustForSchema" json:"minTrustForSchema,omitempty"`
	// MinTrustForFacts is the minimum peer trust score for fact exchange (default 0.7).
	MinTrustForFacts float64 `mapstructure:"minTrustForFacts" json:"minTrustForFacts,omitempty"`
	// AutoImportMode determines how proposed schemas are imported: "shadow" (default), "governed", "disabled".
	AutoImportMode string `mapstructure:"autoImportMode" json:"autoImportMode,omitempty"`
	// MaxTypesPerImport limits types imported from a single peer exchange (default 10).
	MaxTypesPerImport int `mapstructure:"maxTypesPerImport" json:"maxTypesPerImport,omitempty"`
}

OntologyExchangeConfig configures P2P ontology exchange behavior.

type OntologyGovernanceConfig added in v0.7.0

type OntologyGovernanceConfig struct {
	// Enabled activates governance FSM enforcement on RegisterType/RegisterPredicate.
	Enabled bool `mapstructure:"enabled" json:"enabled,omitempty"`
	// MaxNewPerDay is the combined daily limit for type + predicate proposals.
	MaxNewPerDay int `mapstructure:"maxNewPerDay" json:"maxNewPerDay,omitempty"`
	// QuarantinePeriodHrs is the quarantine duration in hours.
	QuarantinePeriodHrs int `mapstructure:"quarantinePeriodHrs" json:"quarantinePeriodHrs,omitempty"`
	// ShadowModeDurationHrs is the shadow mode duration in hours.
	ShadowModeDurationHrs int `mapstructure:"shadowModeDurationHrs" json:"shadowModeDurationHrs,omitempty"`
	// MinUsageForPromotion is the minimum usage count for auto-promotion.
	MinUsageForPromotion int `mapstructure:"minUsageForPromotion" json:"minUsageForPromotion,omitempty"`
	// SchemaExplosionBudget is the monthly limit for new proposals.
	SchemaExplosionBudget int `mapstructure:"schemaExplosionBudget" json:"schemaExplosionBudget,omitempty"`
}

OntologyGovernanceConfig configures schema lifecycle governance.

type OrchestrationConfig added in v0.7.0

type OrchestrationConfig struct {
	// Mode selects the orchestration mode: "classic" (default) or "structured".
	// In structured mode, a CoordinatingExecutor wraps the agent executor
	// to apply delegation guard, budget policy, and recovery policy.
	Mode string `mapstructure:"mode" json:"mode"`

	// CircuitBreaker configures per-agent circuit breaking.
	CircuitBreaker CircuitBreakerCfg `mapstructure:"circuitBreaker" json:"circuitBreaker"`

	// Budget configures observational budget policy.
	Budget BudgetCfg `mapstructure:"budget" json:"budget"`

	// Recovery configures failure recovery policy.
	Recovery RecoveryCfg `mapstructure:"recovery" json:"recovery"`
}

OrchestrationConfig configures the structured multi-agent control plane.

func OrchestrationDefaults added in v0.7.0

func OrchestrationDefaults() OrchestrationConfig

OrchestrationDefaults returns an OrchestrationConfig with default values.

type OutputManagerConfig added in v0.6.0

type OutputManagerConfig struct {
	// Master switch (nil defaults to true — enabled by default)
	Enabled *bool `mapstructure:"enabled" json:"enabled"`

	// Maximum token budget for tool output (default: 2000)
	TokenBudget int `mapstructure:"tokenBudget" json:"tokenBudget"`

	// Ratio of head content to preserve during compression (default: 0.7)
	HeadRatio float64 `mapstructure:"headRatio" json:"headRatio"`

	// Ratio of tail content to preserve during compression (default: 0.3)
	TailRatio float64 `mapstructure:"tailRatio" json:"tailRatio"`
}

OutputManagerConfig defines token-based output management settings.

type OwnerProtectionConfig

type OwnerProtectionConfig struct {
	// OwnerName is the owner's name to block from P2P responses.
	OwnerName string `mapstructure:"ownerName" json:"ownerName"`

	// OwnerEmail is the owner's email to block from P2P responses.
	OwnerEmail string `mapstructure:"ownerEmail" json:"ownerEmail"`

	// OwnerPhone is the owner's phone number to block from P2P responses.
	OwnerPhone string `mapstructure:"ownerPhone" json:"ownerPhone"`

	// ExtraTerms are additional terms to block from P2P responses.
	ExtraTerms []string `mapstructure:"extraTerms" json:"extraTerms,omitempty"`

	// BlockConversations blocks all conversation-related fields from P2P responses (default: true).
	BlockConversations *bool `mapstructure:"blockConversations" json:"blockConversations"`
}

OwnerProtectionConfig configures owner data protection for P2P responses.

type P2PConfig

type P2PConfig struct {
	// Enable P2P networking.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// ListenAddrs are the multiaddrs to listen on (e.g. /ip4/0.0.0.0/tcp/9000).
	ListenAddrs []string `mapstructure:"listenAddrs" json:"listenAddrs"`

	// BootstrapPeers are initial peers to connect to for DHT bootstrapping.
	BootstrapPeers []string `mapstructure:"bootstrapPeers" json:"bootstrapPeers"`

	// Deprecated: KeyDir is the legacy directory for persisting node keys.
	// Node keys are now stored in SecretsStore (encrypted) when available.
	// This field is retained for backward compatibility and migration.
	KeyDir string `mapstructure:"keyDir" json:"keyDir,omitempty"`

	// EnableRelay allows this node to act as a relay for NAT traversal.
	EnableRelay bool `mapstructure:"enableRelay" json:"enableRelay"`

	// EnableMDNS enables multicast DNS for local peer discovery.
	EnableMDNS bool `mapstructure:"enableMdns" json:"enableMdns"`

	// MaxPeers is the maximum number of connected peers.
	MaxPeers int `mapstructure:"maxPeers" json:"maxPeers"`

	// HandshakeTimeout is the maximum duration for peer handshake.
	HandshakeTimeout time.Duration `mapstructure:"handshakeTimeout" json:"handshakeTimeout"`

	// SessionTokenTTL is the lifetime of session tokens after handshake.
	SessionTokenTTL time.Duration `mapstructure:"sessionTokenTtl" json:"sessionTokenTtl"`

	// AutoApproveKnownPeers skips HITL approval for previously authenticated peers.
	AutoApproveKnownPeers bool `mapstructure:"autoApproveKnownPeers" json:"autoApproveKnownPeers"`

	// FirewallRules defines static ACL rules for the knowledge firewall.
	FirewallRules []FirewallRule `mapstructure:"firewallRules" json:"firewallRules"`

	// GossipInterval is the interval for gossip-based agent card propagation.
	GossipInterval time.Duration `mapstructure:"gossipInterval" json:"gossipInterval"`

	// ZKHandshake enables ZK-enhanced handshake instead of plain signature mode.
	ZKHandshake bool `mapstructure:"zkHandshake" json:"zkHandshake"`

	// ZKAttestation enables ZK attestation proofs on responses to peers.
	ZKAttestation bool `mapstructure:"zkAttestation" json:"zkAttestation"`

	// ZKP holds zero-knowledge proof settings.
	ZKP ZKPConfig `mapstructure:"zkp" json:"zkp"`

	// Pricing for paid P2P tool invocations.
	Pricing P2PPricingConfig `mapstructure:"pricing" json:"pricing"`

	// OwnerProtection prevents owner PII from leaking via P2P.
	OwnerProtection OwnerProtectionConfig `mapstructure:"ownerProtection" json:"ownerProtection"`

	// MinTrustScore is the minimum reputation to accept requests (0.0 to 1.0, default 0.3).
	MinTrustScore float64 `mapstructure:"minTrustScore" json:"minTrustScore"`

	// ToolIsolation configures process isolation for remote tool invocations.
	ToolIsolation ToolIsolationConfig `mapstructure:"toolIsolation" json:"toolIsolation"`

	// RequireSignedChallenge rejects unsigned challenges from peers when true.
	// When false (default), unsigned legacy challenges are accepted for backward compatibility.
	RequireSignedChallenge bool `mapstructure:"requireSignedChallenge" json:"requireSignedChallenge"`

	// EnablePQHandshake enables post-quantum hybrid KEM (X25519-MLKEM768)
	// key exchange during peer handshake. When true, protocol v1.2 is
	// advertised and PQ session keys are derived. Default: false (opt-in).
	EnablePQHandshake bool `mapstructure:"enablePqHandshake" json:"enablePqHandshake"`

	// Workspace configures collaborative workspace settings for P2P agent co-work.
	Workspace WorkspaceConfig `mapstructure:"workspace" json:"workspace"`

	// Team configures team health monitoring and membership policies.
	Team TeamConfig `mapstructure:"team" json:"team"`

	// MaxSafetyLevel is the highest SafetyLevel a P2P peer may invoke.
	// Tools above this level are rejected. Valid values: "safe", "moderate", "dangerous".
	// Default: "moderate" — blocks Dangerous tools from remote peers.
	MaxSafetyLevel string `mapstructure:"maxSafetyLevel" json:"maxSafetyLevel"`

	// AllowedTools is an explicit whitelist of tool names that bypass the
	// SafetyLevel gate for P2P peers. An empty list means the SafetyLevel
	// gate alone decides (together with firewall ACL).
	AllowedTools []string `mapstructure:"allowedTools" json:"allowedTools,omitempty"`
}

P2PConfig defines peer-to-peer network settings for the Sovereign Agent Network.

func (P2PConfig) GetBootstrapPeers added in v0.7.0

func (c P2PConfig) GetBootstrapPeers() []string

GetBootstrapPeers returns the initial peers for DHT bootstrapping.

func (P2PConfig) GetEnableMDNS added in v0.7.0

func (c P2PConfig) GetEnableMDNS() bool

GetEnableMDNS reports whether multicast DNS discovery is enabled.

func (P2PConfig) GetEnableRelay added in v0.7.0

func (c P2PConfig) GetEnableRelay() bool

GetEnableRelay reports whether this node acts as a relay for NAT traversal.

func (P2PConfig) GetKeyDir added in v0.7.0

func (c P2PConfig) GetKeyDir() string

GetKeyDir returns the legacy directory for persisting node keys.

func (P2PConfig) GetListenAddrs added in v0.7.0

func (c P2PConfig) GetListenAddrs() []string

GetListenAddrs returns the multiaddrs to listen on.

func (P2PConfig) GetMaxPeers added in v0.7.0

func (c P2PConfig) GetMaxPeers() int

GetMaxPeers returns the maximum number of connected peers.

type P2PPricingConfig

type P2PPricingConfig struct {
	// Enable paid tool invocations.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// PerQuery is the default price per query in USDC (e.g. "0.50").
	PerQuery string `mapstructure:"perQuery" json:"perQuery"`

	// ToolPrices maps tool names to their specific prices in USDC.
	ToolPrices map[string]string `mapstructure:"toolPrices" json:"toolPrices,omitempty"`

	// TrustThresholds configures trust-based payment tier thresholds.
	TrustThresholds TrustThresholds `mapstructure:"trustThresholds" json:"trustThresholds"`

	// Settlement configures on-chain settlement behavior.
	Settlement SettlementConfig `mapstructure:"settlement" json:"settlement"`
}

P2PPricingConfig defines pricing for P2P tool invocations.

type PKCS11Config

type PKCS11Config struct {
	// ModulePath is the path to the PKCS#11 shared library (.so/.dylib/.dll).
	ModulePath string `mapstructure:"modulePath" json:"modulePath"`

	// SlotID is the PKCS#11 slot number to use.
	SlotID int `mapstructure:"slotId" json:"slotId"`

	// Pin is the PKCS#11 user PIN (prefer LANGO_PKCS11_PIN env var).
	Pin string `mapstructure:"pin" json:"pin,omitempty"`

	// KeyLabel is the label of the key object in the HSM.
	KeyLabel string `mapstructure:"keyLabel" json:"keyLabel"`
}

PKCS11Config defines PKCS#11 HSM specific settings.

type PaymentConfig

type PaymentConfig struct {
	// Enable blockchain payment features.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// WalletProvider selects the wallet backend: "local", "rpc", or "composite".
	WalletProvider string `mapstructure:"walletProvider" json:"walletProvider"`

	// Network defines blockchain network parameters.
	Network PaymentNetworkConfig `mapstructure:"network" json:"network"`

	// Limits defines spending restrictions.
	Limits SpendingLimitsConfig `mapstructure:"limits" json:"limits"`

	// X402 defines X402 protocol interception settings.
	X402 X402Config `mapstructure:"x402" json:"x402"`
}

PaymentConfig defines blockchain payment settings.

type PaymentNetworkConfig

type PaymentNetworkConfig struct {
	// ChainID is the EVM chain ID (default: 84532 = Base Sepolia).
	ChainID int64 `mapstructure:"chainId" json:"chainId"`

	// RPCURL is the JSON-RPC endpoint for the blockchain network.
	RPCURL string `mapstructure:"rpcUrl" json:"rpcUrl"`

	// USDCContract is the USDC token contract address on the target chain.
	USDCContract string `mapstructure:"usdcContract" json:"usdcContract"`
}

PaymentNetworkConfig defines blockchain network parameters.

type PresetInfo added in v0.6.0

type PresetInfo struct {
	Name PresetName
	Desc string
}

PresetInfo describes a preset for display.

func AllPresets added in v0.6.0

func AllPresets() []PresetInfo

AllPresets returns all available presets with descriptions.

type PresetName added in v0.6.0

type PresetName string

PresetName represents a named configuration preset.

const (
	PresetMinimal      PresetName = "minimal"
	PresetResearcher   PresetName = "researcher"
	PresetCollaborator PresetName = "collaborator"
	PresetFull         PresetName = "full"
)

type PresidioConfig

type PresidioConfig struct {
	Enabled        bool    `mapstructure:"enabled" json:"enabled"`
	URL            string  `mapstructure:"url" json:"url"`                       // default: http://localhost:5002
	ScoreThreshold float64 `mapstructure:"scoreThreshold" json:"scoreThreshold"` // default: 0.7
	Language       string  `mapstructure:"language" json:"language"`             // default: "en"
}

PresidioConfig defines Microsoft Presidio integration settings.

type ProvenanceConfig added in v0.7.0

type ProvenanceConfig struct {
	// Enabled activates the provenance system.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Checkpoints configures automatic checkpoint creation.
	Checkpoints CheckpointConfig `mapstructure:"checkpoints" json:"checkpoints"`
}

ProvenanceConfig defines session provenance tracking configuration.

type ProviderConfig

type ProviderConfig struct {
	// Provider type (openai, anthropic, gemini)
	Type types.ProviderType `mapstructure:"type" json:"type"`

	// API key for the provider (supports ${ENV_VAR} substitution)
	APIKey string `mapstructure:"apiKey" json:"apiKey"`

	// Base URL for OpenAI-compatible providers
	BaseURL string `mapstructure:"baseUrl" json:"baseUrl"`
}

ProviderConfig defines AI provider settings

type RAGConfig

type RAGConfig struct {
	// Enabled activates RAG context injection.
	Enabled bool `mapstructure:"enabled" json:"enabled"`
	// MaxResults is the maximum number of results to inject.
	MaxResults int `mapstructure:"maxResults" json:"maxResults"`
	// Collections to search (empty means all).
	Collections []string `mapstructure:"collections" json:"collections"`
	// MaxDistance is the maximum cosine distance for RAG results (0.0 = disabled).
	MaxDistance float32 `mapstructure:"maxDistance" json:"maxDistance"`
}

RAGConfig defines retrieval-augmented generation settings.

type RecoveryCfg added in v0.7.0

type RecoveryCfg struct {
	// MaxRetries is the maximum retry attempts on failure (default: 2).
	MaxRetries int `mapstructure:"maxRetries" json:"maxRetries"`

	// CircuitBreakerCooldown is the time before re-enabling a tripped agent (default: 5m).
	CircuitBreakerCooldown time.Duration `mapstructure:"circuitBreakerCooldown" json:"circuitBreakerCooldown"`
}

RecoveryCfg configures failure recovery policy.

type RemoteAgentConfig

type RemoteAgentConfig struct {
	// Name is the local name for this remote agent.
	Name string `mapstructure:"name" json:"name"`

	// AgentCardURL is the URL to fetch the agent card from.
	// Typically: https://host/.well-known/agent.json
	AgentCardURL string `mapstructure:"agentCardUrl" json:"agentCardUrl"`
}

RemoteAgentConfig defines an external A2A agent to connect to.

type RetrievalConfig added in v0.7.0

type RetrievalConfig struct {
	Enabled    bool             `mapstructure:"enabled" json:"enabled"`       // Enable agentic retrieval coordinator
	Feedback   bool             `mapstructure:"feedback" json:"feedback"`     // Context injection observability
	AutoAdjust AutoAdjustConfig `mapstructure:"autoAdjust" json:"autoAdjust"` // Relevance score auto-adjustment
}

RetrievalConfig controls the agentic retrieval coordinator.

type RiskConfig added in v0.5.0

type RiskConfig struct {
	// EscrowThreshold is the USDC amount above which escrow is forced (e.g. "5.00").
	EscrowThreshold string `mapstructure:"escrowThreshold" json:"escrowThreshold"`

	// HighTrustScore is the minimum trust score for DirectPay strategy (default: 0.8).
	HighTrustScore float64 `mapstructure:"highTrustScore" json:"highTrustScore"`

	// MediumTrustScore is the minimum trust score for non-ZK strategies (default: 0.5).
	MediumTrustScore float64 `mapstructure:"mediumTrustScore" json:"mediumTrustScore"`
}

RiskConfig defines trust-based payment strategy routing thresholds.

type RunLedgerConfig added in v0.7.0

type RunLedgerConfig struct {
	// Enabled activates the RunLedger system.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Shadow mode: journal records only, existing systems unaffected.
	Shadow bool `mapstructure:"shadow" json:"shadow"`

	// WriteThrough: all creates/updates go through ledger first, then mirror.
	WriteThrough bool `mapstructure:"writeThrough" json:"writeThrough"`

	// AuthoritativeRead: state reads come from ledger snapshots only.
	AuthoritativeRead bool `mapstructure:"authoritativeRead" json:"authoritativeRead"`

	// WorkspaceIsolation enables runtime PEV workspace wiring for coding-step validation.
	WorkspaceIsolation bool `mapstructure:"workspaceIsolation" json:"workspaceIsolation"`

	// StaleTTL is how long a paused run remains resumable (default: 1h).
	StaleTTL time.Duration `mapstructure:"staleTtl" json:"staleTtl"`

	// MaxRunHistory is the maximum number of runs to keep (0 = unlimited).
	MaxRunHistory int `mapstructure:"maxRunHistory" json:"maxRunHistory"`

	// ValidatorTimeout is the timeout for individual validator execution (default: 2m).
	ValidatorTimeout time.Duration `mapstructure:"validatorTimeout" json:"validatorTimeout"`

	// PlannerMaxRetries is how many times a malformed planner output is retried (default: 2).
	PlannerMaxRetries int `mapstructure:"plannerMaxRetries" json:"plannerMaxRetries"`
}

RunLedgerConfig defines the Task OS / RunLedger configuration.

type SandboxConfig added in v0.7.0

type SandboxConfig struct {
	// Enabled turns on OS-level sandboxing for tool-spawned child processes.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// FailClosed rejects tool execution when OS sandbox is unavailable (default: false = fail-open).
	FailClosed bool `mapstructure:"failClosed" json:"failClosed"`

	// Backend selects the OS sandbox isolation backend: "auto" (default), "seatbelt", "bwrap", "native", "none".
	// "auto" probes available backends and selects the best one.
	// "seatbelt" is macOS only.
	// "bwrap" requires the bubblewrap binary on Linux.
	// "native" (Landlock+seccomp) is not yet implemented.
	// "none" disables OS isolation even when sandbox.enabled is true.
	// Invalid values are rejected at startup.
	Backend string `mapstructure:"backend" json:"backend"`

	// WorkspacePath is the root directory for workspace-relative write access.
	// Defaults to CWD when empty. Tilde and relative paths are normalized in
	// PostLoad (relative paths resolve under DataRoot, ~ expands to $HOME).
	WorkspacePath string `mapstructure:"workspacePath" json:"workspacePath,omitempty"`

	// NetworkMode controls network access from sandboxed processes: "deny" or "allow" (default: "deny").
	// On Linux, enforced via bwrap when backend=bwrap or backend=auto:
	//   "deny"  → bwrap --unshare-net (new network namespace, lo down)
	//   "allow" → host network (no namespace unshare)
	NetworkMode string `mapstructure:"networkMode" json:"networkMode"`

	// AllowedNetworkIPs are IP addresses permitted for outbound connections (macOS Seatbelt only).
	// On Linux/bwrap this field is ignored — bwrap has no AF_INET filter, only
	// the all-or-nothing --unshare-net flag.
	AllowedNetworkIPs []string `mapstructure:"allowedNetworkIPs" json:"allowedNetworkIPs,omitempty"`

	// AllowedWritePaths are additional paths writable from the sandbox (beyond WorkspacePath).
	// Each entry is normalized in PostLoad (tilde and relative paths resolved).
	AllowedWritePaths []string `mapstructure:"allowedWritePaths" json:"allowedWritePaths,omitempty"`

	// ExcludedCommands lists command basenames (e.g. "git", "docker") that
	// SHALL run unsandboxed. Matching is performed against the basename of the
	// user command's first whitespace-separated token (NOT against cmd.Args[0],
	// which is always "sh" because exec.Tool wraps commands in `sh -c`).
	// Each excluded execution is recorded in audit as a SandboxDecisionEvent
	// with Decision="excluded" and the matched pattern. Use sparingly —
	// excluded commands fully bypass isolation.
	ExcludedCommands []string `mapstructure:"excludedCommands" json:"excludedCommands,omitempty"`

	// TimeoutPerTool is the maximum duration for a single sandboxed tool execution (default: 30s).
	TimeoutPerTool time.Duration `mapstructure:"timeoutPerTool" json:"timeoutPerTool,omitempty"`

	// OS holds platform-specific sandbox settings.
	OS OSSandboxConfig `mapstructure:"os" json:"os"`
}

SandboxConfig defines general-purpose OS-level tool execution sandbox settings. This applies to child processes spawned by exec tools, MCP stdio servers, and skill scripts. It is independent of p2p.toolIsolation, which controls subprocess/container isolation for P2P.

type SecurityConfig

type SecurityConfig struct {
	// Interceptor configuration
	Interceptor InterceptorConfig `mapstructure:"interceptor" json:"interceptor"`
	// Signer configuration
	Signer SignerConfig `mapstructure:"signer" json:"signer"`
	// DBEncryption configuration (SQLCipher transparent encryption)
	DBEncryption DBEncryptionConfig `mapstructure:"dbEncryption" json:"dbEncryption"`
	// KMS configuration (Cloud KMS / HSM backends)
	KMS KMSConfig `mapstructure:"kms" json:"kms"`
}

SecurityConfig defines security settings

type ServerConfig

type ServerConfig struct {
	// Host to bind to (default: "localhost")
	Host string `mapstructure:"host" json:"host"`

	// Port to listen on (default: 18789)
	Port int `mapstructure:"port" json:"port"`

	// Enable HTTP API endpoints
	HTTPEnabled bool `mapstructure:"httpEnabled" json:"httpEnabled"`

	// Enable WebSocket server
	WebSocketEnabled bool `mapstructure:"wsEnabled" json:"wsEnabled"`

	// Allowed origins for WebSocket CORS (empty = same-origin, ["*"] = allow all)
	AllowedOrigins []string `mapstructure:"allowedOrigins" json:"allowedOrigins"`
}

ServerConfig defines gateway server settings

type SessionConfig

type SessionConfig struct {
	// Database path for standalone CLI access (defaults to ~/.lango/lango.db).
	// In normal operation the bootstrap Ent client is reused instead.
	DatabasePath string `mapstructure:"databasePath" json:"databasePath"`

	// Session TTL before expiration
	TTL time.Duration `mapstructure:"ttl" json:"ttl"`

	// Maximum history turns per session
	MaxHistoryTurns int `mapstructure:"maxHistoryTurns" json:"maxHistoryTurns"`
}

SessionConfig defines session storage settings. The primary database is always ~/.lango/lango.db (opened during bootstrap). DatabasePath is used as a fallback for standalone CLI commands.

type SettlementConfig added in v0.4.0

type SettlementConfig struct {
	// ReceiptTimeout is the maximum wait time for on-chain receipt confirmation (default: 2m).
	ReceiptTimeout time.Duration `mapstructure:"receiptTimeout" json:"receiptTimeout"`

	// MaxRetries is the maximum number of submission retries (default: 3).
	MaxRetries int `mapstructure:"maxRetries" json:"maxRetries"`
}

SettlementConfig configures on-chain settlement parameters.

type SignerConfig

type SignerConfig struct {
	Provider string `mapstructure:"provider" json:"provider"` // "local", "rpc", "enclave"
	RPCUrl   string `mapstructure:"rpcUrl" json:"rpcUrl"`     // for RPC provider
	KeyID    string `mapstructure:"keyId" json:"keyId"`       // Key identifier
}

SignerConfig defines Secure Signer settings

type SkillConfig

type SkillConfig struct {
	// Enable the skill system.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// SkillsDir is the directory containing skill files (default: ~/.lango/skills).
	SkillsDir string `mapstructure:"skillsDir" json:"skillsDir"`

	// AllowImport enables importing skills from external URLs and GitHub repositories.
	AllowImport bool `mapstructure:"allowImport" json:"allowImport"`

	// MaxBulkImport limits the number of skills in a single bulk import operation (default: 50).
	MaxBulkImport int `mapstructure:"maxBulkImport" json:"maxBulkImport"`

	// ImportConcurrency sets the number of concurrent HTTP requests during bulk import (default: 5).
	ImportConcurrency int `mapstructure:"importConcurrency" json:"importConcurrency"`

	// ImportTimeout is the overall timeout for skill import operations (default: 2m).
	ImportTimeout time.Duration `mapstructure:"importTimeout" json:"importTimeout"`
}

SkillConfig defines file-based skill settings.

type SlackConfig

type SlackConfig struct {
	// Enable Slack channel
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Bot OAuth token
	BotToken string `mapstructure:"botToken" json:"botToken"`

	// App-level token for Socket Mode
	AppToken string `mapstructure:"appToken" json:"appToken"`

	// Signing secret for request verification
	SigningSecret string `mapstructure:"signingSecret" json:"signingSecret"`
}

SlackConfig defines Slack app settings

type SmartAccountConfig added in v0.5.0

type SmartAccountConfig struct {
	Enabled              bool   `mapstructure:"enabled" json:"enabled"`
	FactoryAddress       string `mapstructure:"factoryAddress" json:"factoryAddress"`
	EntryPointAddress    string `mapstructure:"entryPointAddress" json:"entryPointAddress"`
	SafeSingletonAddress string `mapstructure:"safeSingletonAddress" json:"safeSingletonAddress"` // Safe L2 singleton implementation
	Safe7579Address      string `mapstructure:"safe7579Address" json:"safe7579Address"`
	FallbackHandler      string `mapstructure:"fallbackHandler" json:"fallbackHandler"`
	BundlerURL           string `mapstructure:"bundlerURL" json:"bundlerURL"`

	Session   SmartAccountSessionConfig   `mapstructure:"session" json:"session"`
	Modules   SmartAccountModulesConfig   `mapstructure:"modules" json:"modules"`
	Paymaster SmartAccountPaymasterConfig `mapstructure:"paymaster" json:"paymaster"`
}

SmartAccountConfig defines ERC-7579 smart account settings.

func (SmartAccountConfig) Validate added in v0.6.0

func (c SmartAccountConfig) Validate() error

Validate checks that required fields are set when smart account is enabled.

type SmartAccountModulesConfig added in v0.5.0

type SmartAccountModulesConfig struct {
	SessionValidatorAddress string `mapstructure:"sessionValidatorAddress" json:"sessionValidatorAddress"`
	SpendingHookAddress     string `mapstructure:"spendingHookAddress" json:"spendingHookAddress"`
	EscrowExecutorAddress   string `mapstructure:"escrowExecutorAddress" json:"escrowExecutorAddress"`
}

SmartAccountModulesConfig defines module contract addresses.

type SmartAccountPaymasterConfig added in v0.5.0

type SmartAccountPaymasterConfig struct {
	Enabled          bool   `mapstructure:"enabled" json:"enabled"`
	Provider         string `mapstructure:"provider" json:"provider"`   // "circle"|"pimlico"|"alchemy"
	Mode             string `mapstructure:"mode" json:"mode,omitempty"` // "rpc" (default) | "permit"
	RPCURL           string `mapstructure:"rpcURL" json:"rpcURL"`
	TokenAddress     string `mapstructure:"tokenAddress" json:"tokenAddress"` // USDC address
	PaymasterAddress string `mapstructure:"paymasterAddress" json:"paymasterAddress"`
	PolicyID         string `mapstructure:"policyId" json:"policyId,omitempty"`
	FallbackMode     string `mapstructure:"fallbackMode" json:"fallbackMode,omitempty"` // "abort"|"direct"
}

SmartAccountPaymasterConfig defines paymaster settings for gasless transactions.

type SmartAccountSessionConfig added in v0.5.0

type SmartAccountSessionConfig struct {
	MaxDuration     time.Duration `mapstructure:"maxDuration" json:"maxDuration"`
	DefaultGasLimit uint64        `mapstructure:"defaultGasLimit" json:"defaultGasLimit"`
	MaxActiveKeys   int           `mapstructure:"maxActiveKeys" json:"maxActiveKeys"`
}

SmartAccountSessionConfig defines session key settings.

type SpendingLimitsConfig

type SpendingLimitsConfig struct {
	// MaxPerTx is the maximum amount per transaction in USDC (e.g. "1.00").
	MaxPerTx string `mapstructure:"maxPerTx" json:"maxPerTx"`

	// MaxDaily is the maximum daily spending in USDC (e.g. "10.00").
	MaxDaily string `mapstructure:"maxDaily" json:"maxDaily"`

	// AutoApproveBelow is the amount below which transactions are auto-approved.
	AutoApproveBelow string `mapstructure:"autoApproveBelow" json:"autoApproveBelow"`
}

SpendingLimitsConfig defines spending restrictions for payment transactions.

type TeamConfig added in v0.6.0

type TeamConfig struct {
	// HealthCheckInterval is the interval between team health pings (default: 30s).
	HealthCheckInterval time.Duration `mapstructure:"healthCheckInterval" json:"healthCheckInterval"`

	// MaxMissedHeartbeats is the maximum consecutive missed pings before a member is unhealthy (default: 3).
	MaxMissedHeartbeats int `mapstructure:"maxMissedHeartbeats" json:"maxMissedHeartbeats"`

	// MinReputationScore is the minimum reputation to remain on a team (default: 0.3).
	MinReputationScore float64 `mapstructure:"minReputationScore" json:"minReputationScore"`

	// GitStateTracking enables tracking git HEAD hashes from health ping responses.
	GitStateTracking bool `mapstructure:"gitStateTracking" json:"gitStateTracking"`

	// AutoSyncOnDivergence automatically triggers sync when git state divergence is detected.
	AutoSyncOnDivergence bool `mapstructure:"autoSyncOnDivergence" json:"autoSyncOnDivergence"`
}

TeamConfig configures team health monitoring and membership policies.

type TelegramConfig

type TelegramConfig struct {
	// Enable Telegram channel
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Bot token from BotFather
	BotToken string `mapstructure:"botToken" json:"botToken"`

	// Allowed user/group IDs (empty = allow all)
	Allowlist []int64 `mapstructure:"allowlist" json:"allowlist"`
}

TelegramConfig defines Telegram bot settings

type TokenTrackingConfig added in v0.5.0

type TokenTrackingConfig struct {
	// Enabled activates token tracking (default: true when observability is enabled).
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// PersistHistory enables DB-backed persistent storage.
	PersistHistory bool `mapstructure:"persistHistory" json:"persistHistory"`

	// RetentionDays controls how long token usage records are kept (default: 30).
	RetentionDays int `mapstructure:"retentionDays" json:"retentionDays"`
}

TokenTrackingConfig defines token usage tracking settings.

type ToolIsolationConfig

type ToolIsolationConfig struct {
	// Enabled turns on subprocess isolation for remote peer tool invocations.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// TimeoutPerTool is the maximum duration for a single tool execution (default: 30s).
	TimeoutPerTool time.Duration `mapstructure:"timeoutPerTool" json:"timeoutPerTool"`

	// MaxMemoryMB is a soft memory limit per subprocess in megabytes (Phase 2).
	MaxMemoryMB int `mapstructure:"maxMemoryMB" json:"maxMemoryMB"`

	// Container configures container-based tool execution sandbox (Phase 2).
	Container ContainerSandboxConfig `mapstructure:"container" json:"container"`
}

ToolIsolationConfig configures subprocess isolation for P2P tool execution.

type ToolsConfig

type ToolsConfig struct {
	Exec           ExecToolConfig       `mapstructure:"exec" json:"exec"`
	Filesystem     FilesystemToolConfig `mapstructure:"filesystem" json:"filesystem"`
	Browser        BrowserToolConfig    `mapstructure:"browser" json:"browser"`
	OutputManager  OutputManagerConfig  `mapstructure:"outputManager" json:"outputManager"`
	MaxOutputChars int                  `mapstructure:"maxOutputChars" json:"maxOutputChars"`
}

ToolsConfig defines tool-specific settings

type TraceStoreConfig added in v0.7.0

type TraceStoreConfig struct {
	// MaxAge is the maximum age of traces before cleanup (default: 720h / 30 days).
	MaxAge time.Duration `mapstructure:"maxAge" json:"maxAge"`

	// MaxTraces is the maximum number of traces to retain (default: 10000).
	MaxTraces int `mapstructure:"maxTraces" json:"maxTraces"`

	// FailedTraceMultiplier extends retention for failed traces (default: 2).
	FailedTraceMultiplier int `mapstructure:"failedTraceMultiplier" json:"failedTraceMultiplier"`

	// CleanupInterval is how often the cleanup goroutine runs (default: 1h).
	CleanupInterval time.Duration `mapstructure:"cleanupInterval" json:"cleanupInterval"`
}

TraceStoreConfig configures turn trace retention and cleanup.

func TraceStoreDefaults added in v0.7.0

func TraceStoreDefaults() TraceStoreConfig

TraceStoreDefaults returns a TraceStoreConfig with default values.

type TracingConfig added in v0.7.0

type TracingConfig struct {
	// Enabled activates distributed tracing.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Exporter selects the trace exporter: "stdout" (default) or "none".
	Exporter string `mapstructure:"exporter" json:"exporter"`
}

TracingConfig defines OpenTelemetry tracing settings.

type TrustThresholds added in v0.4.0

type TrustThresholds struct {
	// PostPayMinScore is the minimum reputation score for post-pay eligibility (default: 0.8).
	PostPayMinScore float64 `mapstructure:"postPayMinScore" json:"postPayMinScore"`
}

TrustThresholds defines score thresholds for payment tier routing.

type WorkflowConfig

type WorkflowConfig struct {
	// Enable the workflow engine.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// Maximum number of concurrently executing workflow steps.
	MaxConcurrentSteps int `mapstructure:"maxConcurrentSteps" json:"maxConcurrentSteps"`

	// Default timeout for a single workflow step (e.g. "10m").
	DefaultTimeout time.Duration `mapstructure:"defaultTimeout" json:"defaultTimeout"`

	// Directory to store workflow state for resume capability.
	StateDir string `mapstructure:"stateDir" json:"stateDir"`

	// Default delivery channels when deliver_to is not specified (e.g. ["telegram"]).
	DefaultDeliverTo []string `mapstructure:"defaultDeliverTo" json:"defaultDeliverTo"`
}

WorkflowConfig defines workflow engine settings.

type WorkspaceConfig added in v0.6.0

type WorkspaceConfig struct {
	// Enabled turns on collaborative workspaces.
	Enabled bool `mapstructure:"enabled" json:"enabled"`

	// DataDir is the directory for storing workspace data.
	DataDir string `mapstructure:"dataDir" json:"dataDir"`

	// MaxWorkspaces is the maximum number of concurrent workspaces.
	MaxWorkspaces int `mapstructure:"maxWorkspaces" json:"maxWorkspaces"`

	// MaxBundleSizeBytes is the maximum size of a workspace bundle in bytes.
	MaxBundleSizeBytes int64 `mapstructure:"maxBundleSizeBytes" json:"maxBundleSizeBytes"`

	// ChroniclerEnabled turns on workspace activity chronicling.
	ChroniclerEnabled bool `mapstructure:"chroniclerEnabled" json:"chroniclerEnabled"`

	// AutoSandbox automatically sandboxes workspace operations.
	AutoSandbox bool `mapstructure:"autoSandbox" json:"autoSandbox"`

	// ContributionTracking enables tracking of per-agent contributions.
	ContributionTracking bool `mapstructure:"contributionTracking" json:"contributionTracking"`

	// EnableIncrementalBundle enables incremental bundle creation (base..HEAD) instead of full repo bundles.
	EnableIncrementalBundle bool `mapstructure:"enableIncrementalBundle" json:"enableIncrementalBundle"`

	// BranchPerTask creates isolated task/{id} branches for each agent task to avoid conflicts.
	BranchPerTask bool `mapstructure:"branchPerTask" json:"branchPerTask"`

	// MaxIncrementalBundleSizeBytes is the maximum size of an incremental bundle in bytes.
	MaxIncrementalBundleSizeBytes int64 `mapstructure:"maxIncrementalBundleSizeBytes" json:"maxIncrementalBundleSizeBytes"`
}

WorkspaceConfig configures collaborative workspace settings for P2P agent co-work.

type X402Config

type X402Config struct {
	// AutoIntercept enables automatic interception of HTTP 402 responses.
	AutoIntercept bool `mapstructure:"autoIntercept" json:"autoIntercept"`

	// MaxAutoPayAmount is the maximum amount to auto-pay for X402 challenges.
	MaxAutoPayAmount string `mapstructure:"maxAutoPayAmount" json:"maxAutoPayAmount"`
}

X402Config defines X402 protocol interception settings.

type ZKPConfig

type ZKPConfig struct {
	// ProofCacheDir is the directory for caching compiled circuits and proving keys.
	ProofCacheDir string `mapstructure:"proofCacheDir" json:"proofCacheDir"`

	// ProvingScheme selects the ZKP proving scheme: "plonk" or "groth16".
	ProvingScheme string `mapstructure:"provingScheme" json:"provingScheme"`

	// SRSMode selects the SRS generation mode: "unsafe" (default) or "file".
	SRSMode string `mapstructure:"srsMode" json:"srsMode"`

	// SRSPath is the path to the SRS file (used when SRSMode == "file").
	SRSPath string `mapstructure:"srsPath" json:"srsPath"`

	// MaxCredentialAge is the maximum age for ZK credentials (e.g. "24h").
	MaxCredentialAge string `mapstructure:"maxCredentialAge" json:"maxCredentialAge"`
}

ZKPConfig defines zero-knowledge proof settings.

Jump to

Keyboard shortcuts

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