brainos-core 0.3.0

Configuration and bootstrapping for Brain OS cognitive engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
//! Configuration management for Brain.
//!
//! Loads configuration from multiple sources with this priority (highest -> lowest):
//! 1. Environment variables (`BRAIN_` prefix, e.g. `BRAIN_LLM__MODEL`)
//! 2. User config file (`~/.brain/config.yaml`)
//! 3. Embedded defaults (compiled into the binary)

/// Default configuration embedded at compile time.
/// This means `brain` works anywhere without needing config files on disk.
const DEFAULT_CONFIG: &str = include_str!("../default.yaml");

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Top-level Brain configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BrainConfig {
    pub brain: GeneralConfig,
    pub storage: StorageConfig,
    pub llm: LlmConfig,
    pub embedding: EmbeddingConfig,
    pub memory: MemoryConfig,
    pub encryption: EncryptionConfig,
    pub security: SecurityConfig,
    pub actions: ActionsConfig,
    pub proactivity: ProactivityConfig,
    pub adapters: AdaptersConfig,
    pub access: AccessConfig,
    #[serde(default)]
    pub channel: ChannelIntelligenceConfig,
    #[serde(default)]
    pub agents: AgentsConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeneralConfig {
    pub version: String,
    pub data_dir: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageConfig {
    pub ruvector_path: String,
    pub sqlite_path: String,
    pub hnsw: HnswConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HnswConfig {
    pub ef_construction: u32,
    pub m: u32,
    pub ef_search: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmConfig {
    pub provider: String,
    pub model: String,
    pub base_url: String,
    pub temperature: f64,
    pub max_tokens: u32,
    /// API key for the LLM provider (required for OpenAI, OpenRouter, etc.).
    /// Can also be set via `BRAIN_LLM__API_KEY` environment variable.
    #[serde(default)]
    pub api_key: String,
    /// Optional multi-provider entries. When non-empty, startup probes each
    /// entry's `/models` endpoint and selects the first reachable one whose
    /// `preferred_models` are live. When empty, the legacy single-provider
    /// fields above are used as-is.
    #[serde(default)]
    pub providers: Vec<ProviderEntry>,
}

/// One entry in `llm.providers` — a named destination that the cortex
/// will probe at startup. Only two transport kinds are recognised:
/// `ollama` (local) and `openai_compat` (any OpenAI-compatible endpoint).
/// A preset name (`groq`, `openrouter`, `deepseek`, `together`,
/// `gemini-compat`, `openai`) is also accepted as shorthand for
/// `openai_compat` with a prefilled `base_url`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderEntry {
    /// Human-readable identifier (`"primary"`, `"groq-free"`, …).
    pub name: String,
    /// Transport kind or preset name.
    pub kind: String,
    /// Override the preset's base_url; required when `kind` is
    /// `openai_compat` without a preset.
    #[serde(default)]
    pub base_url: String,
    /// Bearer token for OpenAI-compatible providers.
    #[serde(default)]
    pub api_key: String,
    /// Fallback model used when no `preferred_models` entry is live.
    pub model: String,
    /// Priority-ordered models. The first one present in the live
    /// `list_models` response wins.
    #[serde(default)]
    pub preferred_models: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmbeddingConfig {
    /// Embedding model name (e.g. "nomic-embed-text" for Ollama,
    /// "text-embedding-3-small" for OpenAI). Must be available in
    /// the same service configured under `llm`.
    pub model: String,
    /// Output vector dimension — must exactly match the model's output size.
    /// Ollama nomic-embed-text → 768, OpenAI text-embedding-3-small → 1536.
    pub dimensions: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryConfig {
    pub episodic: EpisodicConfig,
    pub semantic: SemanticConfig,
    pub search: SearchConfig,
    pub consolidation: ConsolidationConfig,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct EpisodicConfig {}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SemanticConfig {
    pub similarity_threshold: f64,
    pub max_results: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchConfig {
    pub rrf_k: u32,
    /// Candidates fetched from each source (BM25, ANN) before RRF fusion.
    #[serde(default = "default_pre_fusion_limit")]
    pub pre_fusion_limit: u32,
    /// Weight for importance in final reranking (0.0–1.0).
    #[serde(default = "default_importance_weight")]
    pub importance_weight: f64,
    /// Weight for recency in final reranking (0.0–1.0).
    #[serde(default = "default_recency_weight")]
    pub recency_weight: f64,
    /// Decay rate for the forgetting curve (higher = faster forgetting).
    #[serde(default = "default_decay_rate")]
    pub decay_rate: f64,
}

fn default_pre_fusion_limit() -> u32 {
    50
}
fn default_importance_weight() -> f64 {
    0.3
}
fn default_recency_weight() -> f64 {
    0.2
}
fn default_decay_rate() -> f64 {
    0.01
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsolidationConfig {
    pub enabled: bool,
    pub interval_hours: u32,
    pub forgetting_threshold: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptionConfig {
    pub enabled: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityConfig {
    pub exec_allowlist: Vec<String>,
    pub exec_timeout_seconds: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActionsConfig {
    pub web_search: WebSearchActionConfig,
    pub scheduling: SchedulingActionConfig,
    pub messaging: MessagingActionConfig,
    #[serde(default)]
    pub resilience: ResilienceConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResilienceConfig {
    pub max_retries: u32,
    pub retry_base_ms: u64,
    pub circuit_breaker_threshold: u32,
    pub circuit_breaker_cooldown_secs: u64,
}

impl Default for ResilienceConfig {
    fn default() -> Self {
        Self {
            max_retries: 2,
            retry_base_ms: 500,
            circuit_breaker_threshold: 5,
            circuit_breaker_cooldown_secs: 60,
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum WebSearchProvider {
    /// Built-in DuckDuckGo HTML scraper. Zero-config, no API key, no
    /// Docker — basic quality but always available.
    #[default]
    #[serde(alias = "duckduckgo", rename = "duckduckgo")]
    DuckDuckGo,
    Searxng,
    Tavily,
    Custom,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebSearchActionConfig {
    pub enabled: bool,
    #[serde(default)]
    pub provider: WebSearchProvider,
    pub endpoint: String,
    #[serde(default)]
    pub api_key: String,
    pub timeout_ms: u64,
    pub default_top_k: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchedulingActionConfig {
    pub enabled: bool,
    pub mode: SchedulingMode,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SchedulingMode {
    PersistOnly,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelConfig {
    pub url: String,
    #[serde(default)]
    pub body: String,
    #[serde(default)]
    pub headers: HashMap<String, String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessagingActionConfig {
    pub enabled: bool,
    pub timeout_ms: u64,
    #[serde(deserialize_with = "deserialize_channels", default)]
    pub channels: HashMap<String, ChannelConfig>,
}

/// Deserialize channels supporting both old format (string URL) and new format (ChannelConfig).
fn deserialize_channels<'de, D>(deserializer: D) -> Result<HashMap<String, ChannelConfig>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum ChannelEntry {
        Full(ChannelConfig),
        UrlOnly(String),
    }

    let raw: HashMap<String, ChannelEntry> = HashMap::deserialize(deserializer)?;
    Ok(raw
        .into_iter()
        .map(|(k, v)| {
            let config = match v {
                ChannelEntry::Full(c) => c,
                ChannelEntry::UrlOnly(url) => ChannelConfig {
                    url,
                    body: String::new(),
                    headers: HashMap::new(),
                },
            };
            (k, config)
        })
        .collect())
}

/// Channel intelligence configuration — bidirectional relay gateways
/// (custom WS agents) that integrate with the channel router and
/// confirmation correlator.
///
/// Distinct from `actions.messaging.channels`, which configures one-way
/// webhook pushes. Entries here open a long-lived WebSocket and can
/// carry user responses back into Brain.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ChannelIntelligenceConfig {
    #[serde(default)]
    pub relays: Vec<RelayEntry>,
    /// Generic preset-driven transports (`http_polled`, `webhook_inbound`,
    /// `webhook_outbound`). Each entry names a preset id that ships
    /// embedded under `crates/channel/presets/` or lives at
    /// `~/.brain/presets/<id>.yaml`.
    #[serde(default)]
    pub transports: Vec<TransportEntry>,
}

/// A single preset-driven transport — which preset, what id, what
/// secrets to plug into the preset's templates.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransportEntry {
    /// Stable id registered with the channel router (e.g. `"chat-main"`).
    pub id: String,
    /// Human-readable label.
    pub label: String,
    /// Preset id — resolved via the channel crate's preset loader.
    pub preset: String,
    /// Memory namespace attributed to inbound messages on this transport.
    #[serde(default = "default_relay_namespace")]
    pub namespace: String,
    /// Credential substituted into `{credential}` in url/body templates
    /// (bot token, webhook URL, app id — whatever the preset expects).
    /// May be empty.
    #[serde(default)]
    pub credential: String,
    /// Optional signing secret used by `webhook_inbound` transports
    /// whose preset declares a `verifier` (HMAC shared key, Ed25519
    /// pubkey hex, ...).
    #[serde(default)]
    pub signing_secret: Option<String>,
}

/// One relay gateway entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RelayEntry {
    /// Stable id registered with the channel router (e.g. `"chat-main"`).
    pub id: String,
    /// Human-readable label used in CLI and audit entries.
    pub label: String,
    /// WebSocket URL of the gateway.
    pub url: String,
    /// Memory namespace attributed to messages arriving on this relay.
    #[serde(default = "default_relay_namespace")]
    pub namespace: String,
    /// Optional bearer token forwarded to the gateway (if supported).
    #[serde(default)]
    pub api_key: String,
    /// Reconnection tuning — initial backoff in milliseconds.
    #[serde(default = "default_relay_initial_backoff_ms")]
    pub initial_backoff_ms: u64,
    /// Reconnection tuning — max backoff in milliseconds.
    #[serde(default = "default_relay_max_backoff_ms")]
    pub max_backoff_ms: u64,
}

fn default_relay_namespace() -> String {
    "personal".to_string()
}
fn default_relay_initial_backoff_ms() -> u64 {
    1_000
}
fn default_relay_max_backoff_ms() -> u64 {
    60_000
}

/// Agent delegation configuration — specialist CLI/HTTP agents that
/// orchestrator-level `Implement` steps can hand off to.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AgentsConfig {
    /// Manually-registered delegates. Kept for advanced setups and
    /// backward compatibility; most users rely on `auto_discovery`.
    #[serde(default)]
    pub delegates: Vec<AgentEntry>,
    /// Ordered fallback agent names applied when a delegation fails on
    /// a retryable error. Names must match discovered ids or `delegates`
    /// entries.
    #[serde(default)]
    pub fallbacks: Vec<String>,
    /// Whether timeout failures should trigger fallback retries
    /// (default: true). Set to false for tasks where retry cost is
    /// prohibitive.
    #[serde(default = "default_retry_on_timeout")]
    pub retry_on_timeout: bool,
    /// Scan `$PATH` on startup and auto-register known CLI agents using
    /// the built-in fingerprint table. Default: true. Set to `false` to
    /// go fully manual via `delegates[]`.
    #[serde(default = "default_auto_discovery")]
    pub auto_discovery: bool,
    /// Per-agent overrides merged on top of discovery defaults. Keyed
    /// by the canonical agent id from the fingerprint table.
    #[serde(default)]
    pub discovery_overrides: std::collections::HashMap<String, AgentDiscoveryOverride>,
}

fn default_retry_on_timeout() -> bool {
    true
}

fn default_auto_discovery() -> bool {
    true
}

/// Tweak a single auto-discovered agent. All fields are optional —
/// unset ones keep the fingerprint default.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AgentDiscoveryOverride {
    /// Force a specific binary path instead of the `$PATH` hit.
    #[serde(default)]
    pub binary: Option<String>,
    /// Exclude from the registry entirely.
    #[serde(default)]
    pub disabled: bool,
    /// Override the invocation args (supports `{prompt}` / `{task_id}`).
    #[serde(default)]
    pub args: Option<Vec<String>>,
    /// Force stdin vs. argv prompt delivery.
    #[serde(default)]
    pub prompt_via_stdin: Option<bool>,
}

/// One registered delegate. Currently only `kind = "subprocess"` is
/// supported — any CLI agent the orchestrator can spawn. Auto-discovery
/// covers most common agents without needing manual entries here.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentEntry {
    /// Registered name — this is what appears in `StepAction::Implement`.
    pub name: String,
    /// Adapter kind (`"subprocess"`).
    pub kind: String,
    /// Optional alias registered alongside `name`. Handy for routing
    /// shorthand request names to the canonical entry.
    #[serde(default)]
    pub alias: Option<String>,
    /// Binary to launch. Required for `subprocess`.
    #[serde(default)]
    pub binary: String,
    /// Args passed to the binary. Supports `{prompt}` and `{task_id}`
    /// substitution.
    #[serde(default)]
    pub args: Vec<String>,
    /// Default working directory for the delegate. Task-level workdir
    /// (set by the orchestrator) wins when present.
    #[serde(default)]
    pub workdir: Option<String>,
    /// Whether the prompt is written to the child's stdin rather than
    /// templated into `args`. Defaults to `true`. Ignored for
    /// argv-templated entries that don't read stdin.
    #[serde(default = "default_prompt_via_stdin")]
    pub prompt_via_stdin: bool,
    /// Declared capability tags (e.g. `["code-edit","rust"]`).
    #[serde(default)]
    pub tags: Vec<String>,
}

fn default_prompt_via_stdin() -> bool {
    true
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProactivityConfig {
    pub enabled: bool,
    pub max_per_day: u32,
    pub min_interval_minutes: u32,
    pub quiet_hours: QuietHoursConfig,
    #[serde(default)]
    pub delivery: DeliveryConfig,
    #[serde(default)]
    pub open_loop: OpenLoopDetectionConfig,
}

/// Configuration for open-loop (unresolved commitment) detection.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenLoopDetectionConfig {
    /// Enable open-loop detection.
    pub enabled: bool,
    /// How many hours back to scan for commitments.
    pub scan_window_hours: u32,
    /// Hours after a commitment before it's flagged as unresolved.
    pub resolution_window_hours: u32,
    /// Check interval in minutes.
    pub check_interval_minutes: u32,
}

impl Default for OpenLoopDetectionConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            scan_window_hours: 72,
            resolution_window_hours: 24,
            check_interval_minutes: 120,
        }
    }
}

/// Configuration for proactive notification delivery.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeliveryConfig {
    /// Always write to outbox (drain on next interaction).
    pub outbox: bool,
    /// Push to live sessions via broadcast channel.
    pub broadcast: bool,
    /// Messaging channel keys (from actions.messaging.channels) to push proactive notifications.
    pub webhook_channels: Vec<String>,
    /// Maximum age (days) before undelivered outbox items are pruned.
    pub max_outbox_age_days: u32,
}

impl Default for DeliveryConfig {
    fn default() -> Self {
        Self {
            outbox: true,
            broadcast: true,
            webhook_channels: Vec::new(),
            max_outbox_age_days: 7,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QuietHoursConfig {
    pub start: String,
    pub end: String,
    #[serde(default = "default_timezone")]
    pub timezone: String,
}

fn default_timezone() -> String {
    "UTC".to_string()
}

/// A single API key entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiKeyConfig {
    /// The raw API key string.
    pub key: String,
    /// Human-readable name for this key (for display/audit purposes).
    pub name: String,
    /// Granted permissions: `"read"` and/or `"write"`.
    pub permissions: Vec<String>,
}

impl ApiKeyConfig {
    /// Returns true if this key grants the requested permission.
    pub fn has_permission(&self, perm: &str) -> bool {
        self.permissions.iter().any(|p| p == perm)
    }
}

/// Access-control configuration (API keys).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccessConfig {
    pub api_keys: Vec<ApiKeyConfig>,
}

impl AccessConfig {
    /// Find a key entry by its raw key string.
    pub fn find_key(&self, key: &str) -> Option<&ApiKeyConfig> {
        self.api_keys.iter().find(|k| k.key == key)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdaptersConfig {
    pub http: HttpAdapterConfig,
    pub ws: WebSocketAdapterConfig,
    pub mcp: McpAdapterConfig,
    pub grpc: GrpcAdapterConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpAdapterConfig {
    pub enabled: bool,
    pub host: String,
    pub port: u16,
    pub cors: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebSocketAdapterConfig {
    pub enabled: bool,
    pub port: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpAdapterConfig {
    pub enabled: bool,
    pub stdio: bool,
    pub http: bool,
    pub port: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GrpcAdapterConfig {
    pub enabled: bool,
    pub port: u16,
}

impl BrainConfig {}

mod loader;

#[cfg(test)]
mod tests;