apollo-agent 0.3.0

Local-first Rust AI agent runtime — Telegram-first, trait-driven, SurrealDB + RocksDB state layer.
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.

use serde::{Deserialize, Serialize};
use std::path::PathBuf;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    pub provider: ProviderConfig,
    pub embeddings: EmbeddingsConfig,
    pub agent: AgentConfig,
    pub model: String,
    pub system_prompt: String,
    pub workspace: PathBuf,
    pub storage: StorageConfig,
    pub runtime: RuntimeConfig,
    pub hosting: HostingConfig,
    pub observability: ObservabilityConfig,
    pub channel: ChannelConfig,
    pub gateway: GatewayConfig,
    pub policy: PolicyConfig,
    pub plugin_layer: PluginLayerConfig,
    pub group_chat: GroupChatConfig,
    pub toolsets: ToolsetConfig,
    pub memory: MemoryIdeasConfig,
    #[serde(default)]
    pub zkr: ZkrConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ProviderConfig {
    pub name: String,
    pub api_key: Option<String>,
    pub base_url: Option<String>,
    /// Let the provider run web search on its own infrastructure instead of
    /// apollo's `web_search` tool. Anthropic only; billed by the provider.
    pub native_web_search: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct EmbeddingsConfig {
    pub enabled: bool,
    pub provider: String,
    pub api_key: Option<String>,
    pub model: Option<String>,
    pub base_url: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AgentConfig {
    /// Hard circuit breaker (absolute max execution rounds)
    pub max_rounds: usize,
    /// Max conversation history (prevents context overflow)
    pub max_history_messages: usize,
    /// Max chars for a single tool result
    pub max_tool_result_chars: usize,
    /// Max context chars before triggering mid-loop compaction
    pub max_context_chars: usize,
    /// Fast/cheap model for planning + summarization
    pub fast_model: String,
    /// Heavy model for complex coding/reasoning
    pub heavy_model: String,
    /// Per-tool allow/deny rules
    pub permissions: PermissionRulesConfig,
    /// Initial safety profile: `full`, `auto`, `prompt`, or `tools_only` (drives default `AgentMode`).
    pub permission_profile: String,
    /// Agent loop implementation: `legacy` (apollo's built-in state machine)
    /// or `rx4` (the rotary harness engine). apollo keeps ownership of context
    /// assembly and tools either way; `rx4` hands the loop itself to rx4.
    pub engine: String,
}

/// Which agent loop executes a turn.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AgentEngine {
    /// apollo's built-in Planning → Executing → Summarizing state machine.
    #[default]
    Legacy,
    /// The rx4 (rotary) harness engine, via `agent::rotary_bridge`.
    Rx4,
}

impl AgentConfig {
    /// Parse the configured engine. Unknown values fall back to `Legacy` with
    /// a warning rather than failing startup.
    pub fn engine(&self) -> AgentEngine {
        match self.engine.trim().to_ascii_lowercase().as_str() {
            "rx4" | "rotary" => AgentEngine::Rx4,
            "legacy" | "" => AgentEngine::Legacy,
            other => {
                tracing::warn!("unknown agent.engine {other:?}, using legacy");
                AgentEngine::Legacy
            }
        }
    }
}

impl Default for AgentConfig {
    fn default() -> Self {
        Self {
            max_rounds: 50,
            max_history_messages: 10,
            max_tool_result_chars: 20_000,
            max_context_chars: 150_000,
            fast_model: "claude-haiku-4-5-20251001".to_string(),
            heavy_model: "claude-sonnet-4-6".to_string(),
            permissions: PermissionRulesConfig::default(),
            permission_profile: "auto".to_string(),
            engine: "legacy".to_string(),
        }
    }
}

/// Per-tool permission rules.
///
/// `deny` blocks matching tools outright (checked first).
/// `allow` restricts to only those tools when non-empty (allowlist mode).
/// Supports exact tool names and glob-style `*` wildcards.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct PermissionRulesConfig {
    /// Tools that are always blocked (e.g. `["exec", "shell"]`).
    pub deny: Vec<String>,
    /// If non-empty, only these tools are allowed (allowlist mode).
    pub allow: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RuntimeConfig {
    pub kind: String, // "native", "docker"
    pub docker_image: Option<String>,
    pub memory_limit_mb: Option<u64>,
    pub state_path: Option<PathBuf>,
    pub self_update: SelfUpdateConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SelfUpdateConfig {
    pub enabled: bool,
    pub interval_secs: u64,
    pub remote: String,
    pub branch: String,
    pub restart_service: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct StorageConfig {
    pub backend: String, // "surreal"
    pub root: PathBuf,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct HostingConfig {
    pub enabled: bool,
    pub tenant_root: PathBuf,
    pub session_timeout_minutes: u64,
    pub default_channel: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ObservabilityConfig {
    pub service_name: String,
    pub environment: String,
    pub json_logs: bool,
    pub trace_header_name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ChannelConfig {
    pub kind: String, // "cli", "telegram", "discord", "websocket"
    pub token: Option<String>,
    /// When non-empty, only these Telegram (or channel) chat IDs may send inbound messages.
    pub allowed_chat_ids: Vec<String>,
    /// When non-empty, only these sender user IDs may send inbound messages.
    pub allowed_sender_ids: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct GatewayConfig {
    pub bind: String,
    pub auth_token: Option<String>,
    pub enable_admin_api: bool,
    pub request_body_limit_kb: usize,
    pub request_timeout_secs: u64,
    pub rate_limit_per_minute: usize,
    pub trusted_proxies: Vec<String>,
    pub allowed_origins: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PolicyConfig {
    pub allow_shell: bool,
    pub allow_dynamic_tools: bool,
    pub allow_plugin_shell: bool,
    pub allow_plugin_git: bool,
    pub allow_computer_use: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PluginLayerConfig {
    pub enabled: bool,
    #[serde(default = "default_manifest_path")]
    pub manifest_path: PathBuf,
    /// Extra directories to scan for OpenClaw SKILL.md and Hermes plugin.json
    #[serde(default)]
    pub host_plugin_roots: Vec<PathBuf>,
    pub hook_events: Vec<String>,
    pub allow_core_fallback: bool,
    pub layered_overrides: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct GroupChatConfig {
    pub enable_ambient_questions: bool,
    pub rolling_memory_namespace: String,
    pub rolling_memory_max_chars: usize,
    pub rolling_memory_recent_turns: usize,
    pub ambient_question_window: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ToolsetConfig {
    pub enabled: Vec<String>,
    pub disabled: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct MemoryIdeasConfig {
    /// One logical user across channels (merged history when set).
    pub principal_id: Option<String>,
    /// Inject brief + recall gate + idea graph context each turn.
    pub inject_context: bool,
    pub graph_recall_limit: usize,
    /// Route heartbeat synthetic messages to this chat_id (e.g. telegram chat id).
    pub heartbeat_chat_id: Option<String>,
    /// After idle, expand open loops into dream nodes (graph).
    pub dream_on_heartbeat: bool,
}

impl Default for MemoryIdeasConfig {
    fn default() -> Self {
        Self {
            principal_id: None,
            inject_context: true,
            graph_recall_limit: 5,
            heartbeat_chat_id: None,
            dream_on_heartbeat: false,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ZkrConfig {
    pub enabled: bool,
    pub database: PathBuf,
    pub tenant_id: String,
    pub person_id: String,
    pub auto_capture: bool,
    pub inject_recall: bool,
    pub recall_limit: u32,
    pub self_improve: bool,
}

impl Default for ZkrConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            database: PathBuf::from(".apollo/zkr.db"),
            tenant_id: "apollo".to_string(),
            person_id: "local".to_string(),
            auto_capture: true,
            inject_recall: true,
            recall_limit: 5,
            self_improve: true,
        }
    }
}

/// Apply a named onboarding permission profile to `cfg` (policy, toolsets, and `permission_profile`).
pub fn apply_permission_profile(cfg: &mut Config, profile: &str) {
    let p = profile.trim().to_ascii_lowercase().replace(['-', ' '], "_");
    match p.as_str() {
        "full" => {
            cfg.agent.permission_profile = "full".to_string();
            cfg.policy.allow_shell = true;
            cfg.policy.allow_dynamic_tools = true;
            cfg.policy.allow_computer_use = true;
            cfg.toolsets = ToolsetConfig::default();
            cfg.agent.permissions = PermissionRulesConfig::default();
        }
        "auto" => {
            cfg.agent.permission_profile = "auto".to_string();
            cfg.policy = PolicyConfig::default();
            cfg.toolsets = ToolsetConfig::default();
            cfg.agent.permissions = PermissionRulesConfig::default();
        }
        "prompt" => {
            cfg.agent.permission_profile = "prompt".to_string();
            cfg.policy = PolicyConfig::default();
            cfg.toolsets = ToolsetConfig::default();
            cfg.agent.permissions = PermissionRulesConfig::default();
        }
        "tools_only" | "tools" => {
            cfg.agent.permission_profile = "tools_only".to_string();
            cfg.policy.allow_shell = false;
            cfg.policy.allow_dynamic_tools = false;
            cfg.policy.allow_computer_use = false;
            cfg.toolsets.enabled = vec![
                "web".to_string(),
                "memory".to_string(),
                "sessions".to_string(),
            ];
            cfg.toolsets.disabled = vec![
                "browser".to_string(),
                "vibemania".to_string(),
                "create_tool".to_string(),
                "mcp".to_string(),
            ];
            cfg.agent.permissions = PermissionRulesConfig::default();
        }
        _ => {
            cfg.agent.permission_profile = "auto".to_string();
            cfg.policy = PolicyConfig::default();
            cfg.toolsets = ToolsetConfig::default();
            cfg.agent.permissions = PermissionRulesConfig::default();
        }
    }
}

impl Config {
    pub fn load(path: &str) -> anyhow::Result<Self> {
        let content = std::fs::read_to_string(path)?;
        let config: Config = serde_json::from_str(&content)?;
        Ok(config)
    }

    pub fn default_config() -> Self {
        Self {
            provider: ProviderConfig::default(),
            embeddings: EmbeddingsConfig::default(),
            agent: AgentConfig::default(),
            model: "claude-sonnet-4-6".to_string(),
            system_prompt: "You are a helpful AI assistant.".to_string(),
            workspace: PathBuf::from("."),
            storage: StorageConfig::default(),
            runtime: RuntimeConfig::default(),
            hosting: HostingConfig::default(),
            observability: ObservabilityConfig::default(),
            channel: ChannelConfig::default(),
            gateway: GatewayConfig::default(),
            policy: PolicyConfig::default(),
            plugin_layer: PluginLayerConfig::default(),
            group_chat: GroupChatConfig::default(),
            toolsets: ToolsetConfig::default(),
            memory: MemoryIdeasConfig::default(),
            zkr: ZkrConfig::default(),
        }
    }
}

impl Default for Config {
    fn default() -> Self {
        Self::default_config()
    }
}

impl Default for ProviderConfig {
    fn default() -> Self {
        Self {
            name: "anthropic".to_string(),
            api_key: None,
            base_url: None,
            native_web_search: false,
        }
    }
}

impl Default for EmbeddingsConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            provider: "noop".to_string(),
            api_key: None,
            model: None,
            base_url: None,
        }
    }
}

impl Default for RuntimeConfig {
    fn default() -> Self {
        Self {
            kind: "native".to_string(),
            docker_image: None,
            memory_limit_mb: None,
            state_path: None,
            self_update: SelfUpdateConfig::default(),
        }
    }
}

impl Default for SelfUpdateConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            interval_secs: 900,
            remote: "origin".to_string(),
            branch: "main".to_string(),
            restart_service: Some("apollo".to_string()),
        }
    }
}

impl Default for StorageConfig {
    fn default() -> Self {
        Self {
            backend: "surreal".to_string(),
            root: PathBuf::from(".apollo"),
        }
    }
}

impl Default for HostingConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            tenant_root: PathBuf::from(".apollo/tenants"),
            session_timeout_minutes: 120,
            default_channel: "gateway".to_string(),
        }
    }
}

impl Default for ObservabilityConfig {
    fn default() -> Self {
        Self {
            service_name: "apollo".to_string(),
            environment: "development".to_string(),
            json_logs: false,
            trace_header_name: "traceparent".to_string(),
        }
    }
}

impl Default for ChannelConfig {
    fn default() -> Self {
        Self {
            kind: "cli".to_string(),
            token: None,
            allowed_chat_ids: Vec::new(),
            allowed_sender_ids: Vec::new(),
        }
    }
}

impl Default for GatewayConfig {
    fn default() -> Self {
        Self {
            bind: "127.0.0.1:8080".to_string(),
            auth_token: None,
            enable_admin_api: false,
            request_body_limit_kb: 512,
            request_timeout_secs: 60,
            rate_limit_per_minute: 120,
            trusted_proxies: Vec::new(),
            allowed_origins: Vec::new(),
        }
    }
}

impl Default for PolicyConfig {
    fn default() -> Self {
        Self {
            allow_shell: true,
            allow_dynamic_tools: true,
            allow_plugin_shell: true,
            allow_plugin_git: true,
            allow_computer_use: true,
        }
    }
}

fn default_manifest_path() -> PathBuf {
    PathBuf::from("plugins/manifest.json")
}

impl Default for PluginLayerConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            manifest_path: default_manifest_path(),
            host_plugin_roots: Vec::new(),
            hook_events: vec![
                "before_message".to_string(),
                "after_message".to_string(),
                "before_tool".to_string(),
                "after_tool".to_string(),
            ],
            allow_core_fallback: true,
            layered_overrides: vec!["system_prompt".to_string(), "toolsets".to_string()],
        }
    }
}

impl Default for GroupChatConfig {
    fn default() -> Self {
        Self {
            enable_ambient_questions: true,
            rolling_memory_namespace: "group_memory".to_string(),
            rolling_memory_max_chars: 6_000,
            rolling_memory_recent_turns: 16,
            ambient_question_window: 24,
        }
    }
}

#[cfg(test)]
mod permission_profile_tests {
    use super::*;

    #[test]
    fn full_enables_shell_and_resets_toolsets() {
        let mut cfg = Config::default();
        cfg.policy.allow_shell = false;
        cfg.toolsets.enabled = vec!["browser".into()];
        apply_permission_profile(&mut cfg, "full");
        assert_eq!(cfg.agent.permission_profile, "full");
        assert!(cfg.policy.allow_shell);
        assert!(cfg.policy.allow_dynamic_tools);
        assert!(cfg.toolsets.enabled.is_empty());
    }

    #[test]
    fn tools_only_disables_shell_and_limits_toolsets() {
        let mut cfg = Config::default();
        apply_permission_profile(&mut cfg, "tools-only");
        assert_eq!(cfg.agent.permission_profile, "tools_only");
        assert!(!cfg.policy.allow_shell);
        assert!(!cfg.policy.allow_dynamic_tools);
        assert_eq!(
            cfg.toolsets.enabled,
            vec![
                "web".to_string(),
                "memory".to_string(),
                "sessions".to_string()
            ]
        );
        assert!(cfg.toolsets.disabled.contains(&"browser".to_string()));
    }

    #[test]
    fn engine_defaults_to_legacy() {
        assert_eq!(AgentConfig::default().engine(), AgentEngine::Legacy);
    }

    #[test]
    fn engine_parses_rx4_aliases() {
        for value in ["rx4", "RX4", " rotary "] {
            let cfg = AgentConfig {
                engine: value.to_string(),
                ..AgentConfig::default()
            };
            assert_eq!(cfg.engine(), AgentEngine::Rx4, "value: {value:?}");
        }
    }

    #[test]
    fn unknown_engine_falls_back_to_legacy() {
        for value in ["nope", ""] {
            let cfg = AgentConfig {
                engine: value.to_string(),
                ..AgentConfig::default()
            };
            assert_eq!(cfg.engine(), AgentEngine::Legacy, "value: {value:?}");
        }
    }

    #[test]
    fn unknown_profile_falls_back_to_auto_defaults() {
        let mut cfg = Config::default();
        cfg.policy.allow_shell = false;
        apply_permission_profile(&mut cfg, "nope");
        assert_eq!(cfg.agent.permission_profile, "auto");
        assert!(cfg.policy.allow_shell);
    }
}