apollo-agent 0.6.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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! Plugin system — JSON-RPC 2.0 interface + lifecycle hooks.
//!
//! Two extension surfaces:
//! 1. JSON-RPC methods (existing) — regular plugin methods
//! 2. Lifecycle hooks — intercept tool calls, session events, etc.

use crate::tools::ToolResult;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

// ── Core Plugin trait ─────────────────────────────────────────────────────

/// Plugin trait — implement this to extend aclaw with JSON-RPC methods
#[async_trait]
pub trait Plugin: Send + Sync {
    /// Plugin name (e.g., "ai", "remote", "tools", "vibemania", "git")
    fn name(&self) -> &str;

    /// Plugin version
    fn version(&self) -> &str;

    /// List available methods this plugin provides
    fn methods(&self) -> Vec<MethodSpec>;

    /// Execute a method (JSON-RPC style)
    async fn call(&self, method: &str, params: Value) -> Result<Value, PluginError>;

    /// Called after registration — gives the plugin a chance to register tools and hooks.
    /// Default implementation does nothing.
    async fn on_register(&self, _ctx: &mut PluginContext) {}
}

/// Method specification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MethodSpec {
    pub name: String,
    pub description: String,
    pub params: HashMap<String, String>,
    pub returns: String,
}

/// Plugin error
#[derive(Debug, Serialize, Deserialize)]
pub struct PluginError {
    pub code: i32,
    pub message: String,
    pub data: Option<Value>,
}

impl PluginError {
    pub fn new(code: i32, message: &str) -> Self {
        Self {
            code,
            message: message.to_string(),
            data: None,
        }
    }
}

// ── Lifecycle Hook System ─────────────────────────────────────────────────

/// Events that lifecycle hooks can intercept
#[derive(Debug, Clone)]
pub enum LifecycleEvent {
    /// Before a tool executes (tool_name, arguments_json)
    BeforeToolCall(String, String),
    /// After a tool completes (tool_name, arguments_json, result)
    AfterToolCall(String, String, ToolResult),
    /// A conversation session started (session_id)
    SessionStart(String),
    /// A conversation session ended (session_id)
    SessionEnd(String),
    /// Agent loop started (chat_id, message)
    AgentStart(String, String),
    /// Agent loop completed (chat_id, response)
    AgentDone(String, String),
}

// Re-export hook decision types from agent hooks
pub use crate::agent::hooks::HookDecision;

/// A lifecycle hook — registered by plugins or core
#[async_trait]
pub trait LifecycleHook: Send + Sync {
    fn name(&self) -> &str;

    /// Called on any lifecycle event. Return Ok(()) to continue, Err to abort (tool-call only).
    async fn on_event(&self, event: &LifecycleEvent) -> anyhow::Result<()>;
}

/// Hook that can block tool execution based on custom logic
#[async_trait]
pub trait PreToolHook: Send + Sync {
    fn name(&self) -> &str;
    async fn before_tool_call(&self, name: &str, arguments: &str) -> HookDecision;
}

/// Hook that observes tool results (logging, metrics, auditing)
#[async_trait]
pub trait PostToolHook: Send + Sync {
    fn name(&self) -> &str;
    async fn after_tool_call(&self, name: &str, arguments: &str, result: &ToolResult);
}

/// Central hook manager — dispatches events to all registered hooks
#[derive(Default)]
pub struct HookManager {
    lifecycle_hooks: Vec<Arc<dyn LifecycleHook>>,
    pre_hooks: Vec<Arc<dyn PreToolHook>>,
    post_hooks: Vec<Arc<dyn PostToolHook>>,
}

impl HookManager {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn register_lifecycle(&mut self, hook: Arc<dyn LifecycleHook>) {
        self.lifecycle_hooks.push(hook);
    }

    pub fn register_pre_tool(&mut self, hook: Arc<dyn PreToolHook>) {
        self.pre_hooks.push(hook);
    }

    pub fn register_post_tool(&mut self, hook: Arc<dyn PostToolHook>) {
        self.post_hooks.push(hook);
    }

    /// Fire event to all lifecycle hooks
    pub async fn emit(&self, event: &LifecycleEvent) {
        for hook in &self.lifecycle_hooks {
            if let Err(e) = hook.on_event(event).await {
                tracing::warn!(
                    "LifecycleHook '{}' error on {:?}: {}",
                    hook.name(),
                    event,
                    e
                );
            }
        }
    }

    /// Run pre-tool hooks — first Block wins
    pub async fn check_pre_tool(&self, name: &str, arguments: &str) -> HookDecision {
        for hook in &self.pre_hooks {
            match hook.before_tool_call(name, arguments).await {
                HookDecision::Block(reason) => return HookDecision::Block(reason),
                HookDecision::Allow => {}
            }
        }
        HookDecision::Allow
    }

    /// Run post-tool hooks
    pub async fn notify_post_tool(&self, name: &str, arguments: &str, result: &ToolResult) {
        for hook in &self.post_hooks {
            hook.after_tool_call(name, arguments, result).await;
        }
    }
}

/// Plugin context — passed to plugins during registration, allows tool registration
#[derive(Default)]
pub struct PluginContext {
    /// Tools registered by plugins
    pub tools: Vec<Arc<dyn crate::tools::Tool>>,
    /// Hook manager for lifecycle hooks
    pub hooks: HookManager,
    /// Channels registered by plugins, keyed by the name `--channel` selects.
    pub channels: Vec<(String, crate::channels::ChannelBuilder)>,
}

impl PluginContext {
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a tool that the agent can call
    pub fn register_tool(&mut self, tool: Arc<dyn crate::tools::Tool>) {
        self.tools.push(tool);
    }

    /// Register a channel the user can select with `--channel <name>`.
    ///
    /// This is the whole integration: no feature flag, no `mod.rs` entry, no
    /// arm in the `serve` match. The builder receives the same
    /// `[channel].settings` a built-in would.
    pub fn register_channel<F>(&mut self, name: impl Into<String>, builder: F)
    where
        F: Fn(
                &crate::channels::ChannelSettings,
            ) -> anyhow::Result<Box<dyn crate::channels::Channel>>
            + Send
            + Sync
            + 'static,
    {
        self.channels.push((name.into(), Arc::new(builder)));
    }

    /// Register a lifecycle hook
    pub fn register_lifecycle_hook(&mut self, hook: Arc<dyn LifecycleHook>) {
        self.hooks.register_lifecycle(hook);
    }

    /// Register a pre-tool hook
    pub fn register_pre_tool_hook(&mut self, hook: Arc<dyn PreToolHook>) {
        self.hooks.register_pre_tool(hook);
    }

    /// Register a post-tool hook
    pub fn register_post_tool_hook(&mut self, hook: Arc<dyn PostToolHook>) {
        self.hooks.register_post_tool(hook);
    }
}

// ── Plugin Registry ───────────────────────────────────────────────────────

/// Plugin registry — manage installed plugins
pub struct PluginRegistry {
    plugins: HashMap<String, Arc<dyn Plugin>>,
    hooks: HookManager,
    channels: crate::channels::ChannelRegistry,
    tools: Vec<Arc<dyn crate::tools::Tool>>,
    host_plugins: Vec<crate::plugin_hosts::HostPluginEntry>,
}

impl PluginRegistry {
    pub fn new() -> Self {
        Self {
            plugins: HashMap::new(),
            hooks: HookManager::new(),
            channels: crate::channels::ChannelRegistry::with_builtins(),
            tools: Vec::new(),
            host_plugins: Vec::new(),
        }
    }

    /// Tools contributed by plugins during `on_register`.
    ///
    /// `LoopRunner::with_plugin_registry` appends these to the agent's tool
    /// list. They were previously logged and dropped, so a plugin could
    /// "register" a tool the agent could never call.
    pub fn tools(&self) -> &[Arc<dyn crate::tools::Tool>] {
        &self.tools
    }

    /// Host plugin directories found by `ingest_host_plugins`.
    pub fn host_plugins(&self) -> &[crate::plugin_hosts::HostPluginEntry] {
        &self.host_plugins
    }

    /// Every channel that can be selected by name — built-ins plus whatever
    /// plugins registered during `on_register`.
    pub fn channels(&self) -> &crate::channels::ChannelRegistry {
        &self.channels
    }

    /// Discover OpenClaw/Hermes plugin directories and keep them.
    ///
    /// Kept, not just logged: `host_plugins()` is what feeds SKILL.md-bearing
    /// plugin directories into skill discovery. A `HostPluginEntry` carries no
    /// entrypoint, so a plugin whose manifest declares neither a skill nor an
    /// in-process registration still does nothing — see `docs/` before adding
    /// an execution model for those.
    pub fn ingest_host_plugins(&mut self, workspace: &std::path::Path, extra: &[PathBuf]) {
        self.ingest_host_plugins_trusting(workspace, extra, &[]);
    }

    /// As `ingest_host_plugins`, additionally building the manifest-declared
    /// tools of plugins named in `trusted`.
    ///
    /// Trust is per plugin id and defaults to empty, because discovery finds a
    /// directory — it does not vouch for it. See `plugin_exec` for what a
    /// trusted plugin is still not allowed to do.
    pub fn ingest_host_plugins_trusting(
        &mut self,
        workspace: &std::path::Path,
        extra: &[PathBuf],
        trusted: &[String],
    ) {
        let found = crate::plugin_hosts::discover_host_plugins(workspace, extra);
        for p in &found {
            tracing::info!(
                "[plugin-host] {:?} {} {:?}",
                p.kind,
                p.name.as_deref().unwrap_or("?"),
                p.path
            );
            for tool in crate::plugin_exec::HostPluginToolAdapter::build(p, trusted) {
                let tool: Arc<dyn crate::tools::Tool> = Arc::new(tool);
                tracing::info!(
                    "[plugin-host] {} contributed trusted tool: {}",
                    p.id,
                    tool.name()
                );
                self.tools.push(tool);
            }
        }
        self.host_plugins.extend(found);
    }

    /// Register a plugin and call its on_register with a PluginContext
    pub async fn register(&mut self, plugin: Arc<dyn Plugin>) {
        let name = plugin.name().to_string();
        let mut ctx = PluginContext::default();
        plugin.on_register(&mut ctx).await;
        // Keep the tools the plugin exposed — `tools()` hands them to the agent.
        for tool in ctx.tools {
            tracing::info!("[plugin] '{}' registered tool: {}", name, tool.name());
            self.tools.push(tool);
        }
        // Merge channels so `--channel <name>` can reach them.
        for (channel_name, builder) in ctx.channels {
            tracing::info!("[plugin] '{}' registered channel: {}", name, channel_name);
            self.channels.register_builder(channel_name, builder);
        }
        // Merge hooks
        self.hooks.lifecycle_hooks.extend(ctx.hooks.lifecycle_hooks);
        self.hooks.pre_hooks.extend(ctx.hooks.pre_hooks);
        self.hooks.post_hooks.extend(ctx.hooks.post_hooks);
        self.plugins.insert(name, plugin);
    }

    /// Register a plugin without async (for tests, legacy)
    pub fn register_sync(&mut self, plugin: Arc<dyn Plugin>) {
        self.plugins.insert(plugin.name().to_string(), plugin);
    }

    /// Register a lifecycle hook directly (not from a plugin)
    pub fn register_hook(&mut self, hook: Arc<dyn LifecycleHook>) {
        self.hooks.register_lifecycle(hook);
    }

    /// Register a pre-tool hook directly (not from a plugin)
    pub fn register_pre_tool_hook(&mut self, hook: Arc<dyn PreToolHook>) {
        self.hooks.register_pre_tool(hook);
    }

    /// Access the hook manager
    pub fn hooks(&self) -> &HookManager {
        &self.hooks
    }

    /// Call a plugin method
    pub async fn call(
        &self,
        plugin: &str,
        method: &str,
        params: Value,
    ) -> Result<Value, PluginError> {
        let p = self
            .plugins
            .get(plugin)
            .ok_or_else(|| PluginError::new(-32601, "Plugin not found"))?;
        p.call(method, params).await
    }

    /// List all plugins
    pub fn list(&self) -> Vec<String> {
        self.plugins.keys().cloned().collect()
    }

    /// Get plugin info
    pub fn info(&self, name: &str) -> Option<PluginInfo> {
        self.plugins.get(name).map(|p| PluginInfo {
            name: p.name().to_string(),
            version: p.version().to_string(),
            methods: p.methods(),
        })
    }

    /// Emit lifecycle event to all registered hooks
    pub async fn emit(&self, event: &LifecycleEvent) {
        self.hooks.emit(event).await;
    }

    /// Run pre-tool checks
    pub async fn check_pre_tool(&self, name: &str, arguments: &str) -> HookDecision {
        self.hooks.check_pre_tool(name, arguments).await
    }

    /// Notify post-tool hooks
    pub async fn notify_post_tool(&self, name: &str, arguments: &str, result: &ToolResult) {
        self.hooks.notify_post_tool(name, arguments, result).await;
    }
}

impl Default for PluginRegistry {
    fn default() -> Self {
        Self::new()
    }
}

// ── Built-in shell plugin (argv spawn, no sh -c) ─────────────────────────

/// JSON-RPC plugin exposing `shell` when `policy.allow_plugin_shell` is enabled.
pub struct ShellPlugin {
    policy: crate::policy::ExecutionPolicy,
}

impl ShellPlugin {
    pub fn new(policy: crate::policy::ExecutionPolicy) -> Self {
        Self { policy }
    }
}

#[async_trait]
impl Plugin for ShellPlugin {
    fn name(&self) -> &str {
        "tools"
    }

    fn version(&self) -> &str {
        "0.1.0"
    }

    fn methods(&self) -> Vec<MethodSpec> {
        vec![MethodSpec {
            name: "shell".to_string(),
            description: "Execute shell command".to_string(),
            params: {
                let mut m = HashMap::new();
                m.insert("cmd".to_string(), "string".to_string());
                m
            },
            returns: "string".to_string(),
        }]
    }

    async fn call(&self, method: &str, params: Value) -> Result<Value, PluginError> {
        if method != "shell" {
            return Err(PluginError::new(-32601, "Method not found"));
        }
        if !self.policy.allow_plugin_shell {
            return Err(PluginError::new(
                -32604,
                "Plugin shell execution is disabled by policy",
            ));
        }

        let cmd = params
            .get("cmd")
            .and_then(|v| v.as_str())
            .ok_or_else(|| PluginError::new(-32602, "Missing cmd parameter"))?;

        if let Err(reason) = self.policy.check_shell_command(cmd) {
            return Err(PluginError::new(-32604, &reason));
        }

        match crate::process_cmd::run_argv_command(cmd, 120).await {
            Ok((output, ok)) => Ok(serde_json::json!({
                "stdout": output,
                "success": ok,
            })),
            Err(e) => Err(PluginError::new(-32603, &e.to_string())),
        }
    }
}

// ── Plugin Info ───────────────────────────────────────────────────────────

#[derive(Debug, Serialize, Deserialize)]
pub struct PluginInfo {
    pub name: String,
    pub version: String,
    pub methods: Vec<MethodSpec>,
}

// ── Built-in lifecycle hooks ──────────────────────────────────────────────

/// Append short session notes on agent completion.
pub struct SessionNoteLifecycleHook {
    workspace: std::path::PathBuf,
}

impl SessionNoteLifecycleHook {
    pub fn new(workspace: std::path::PathBuf) -> Self {
        Self { workspace }
    }
}

#[async_trait]
impl LifecycleHook for SessionNoteLifecycleHook {
    fn name(&self) -> &str {
        "session_note"
    }

    async fn on_event(&self, event: &LifecycleEvent) -> anyhow::Result<()> {
        if let LifecycleEvent::AgentDone(chat_id, response) = event {
            let redacted = crate::redaction::redact_text(response);
            let preview: String = redacted.chars().take(200).collect();
            if !preview.is_empty() {
                let _ = crate::memory::session_note::append_session_note(
                    &self.workspace,
                    chat_id,
                    &preview,
                );
            }
        }
        Ok(())
    }
}

/// Logging hook — traces every lifecycle event
pub struct LoggingLifecycleHook;

#[async_trait]
impl LifecycleHook for LoggingLifecycleHook {
    fn name(&self) -> &str {
        "logging"
    }

    async fn on_event(&self, event: &LifecycleEvent) -> anyhow::Result<()> {
        match event {
            LifecycleEvent::BeforeToolCall(name, args) => {
                tracing::debug!("[hook] before_tool {} args_len:{}", name, args.len());
            }
            LifecycleEvent::AfterToolCall(name, _args, result) => {
                tracing::debug!(
                    "[hook] after_tool {} is_error:{} len:{}",
                    name,
                    result.is_error,
                    result.output.len()
                );
            }
            LifecycleEvent::SessionStart(id) => {
                tracing::info!("[hook] session_start {}", id);
            }
            LifecycleEvent::SessionEnd(id) => {
                tracing::info!("[hook] session_end {}", id);
            }
            LifecycleEvent::AgentStart(chat_id, msg) => {
                tracing::debug!("[hook] agent_start {} msg_len:{}", chat_id, msg.len());
            }
            LifecycleEvent::AgentDone(chat_id, response) => {
                tracing::debug!(
                    "[hook] agent_done {} response_len:{}",
                    chat_id,
                    response.len()
                );
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    struct TestPlugin;

    #[async_trait]
    impl Plugin for TestPlugin {
        fn name(&self) -> &str {
            "test"
        }

        fn version(&self) -> &str {
            "0.1.0"
        }

        fn methods(&self) -> Vec<MethodSpec> {
            vec![MethodSpec {
                name: "echo".to_string(),
                description: "Echo input".to_string(),
                params: HashMap::new(),
                returns: "object".to_string(),
            }]
        }

        async fn call(&self, method: &str, params: Value) -> Result<Value, PluginError> {
            match method {
                "echo" => Ok(json!({ "result": params })),
                _ => Err(PluginError::new(-32601, "Method not found")),
            }
        }
    }

    #[tokio::test]
    async fn shell_plugin_uses_argv_not_shell_when_allowed() {
        let policy = crate::policy::ExecutionPolicy {
            allow_plugin_shell: true,
            ..Default::default()
        };
        let plugin = ShellPlugin::new(policy);
        let result = plugin
            .call("shell", json!({ "cmd": "echo plugin_ok" }))
            .await
            .unwrap();
        assert_eq!(result["success"], true);
        assert!(result["stdout"].as_str().unwrap().contains("plugin_ok"));
    }

    #[tokio::test]
    async fn shell_plugin_denied_when_policy_off() {
        let plugin = ShellPlugin::new(crate::policy::ExecutionPolicy {
            allow_plugin_shell: false,
            ..Default::default()
        });
        let err = plugin
            .call("shell", json!({ "cmd": "echo x" }))
            .await
            .unwrap_err();
        assert_eq!(err.code, -32604);
    }

    #[tokio::test]
    async fn test_plugin_call() {
        let mut registry = PluginRegistry::new();
        registry.register_sync(Arc::new(TestPlugin));

        let result = registry
            .call("test", "echo", json!({ "code": "fn main() {}" }))
            .await
            .unwrap();

        assert!(result.get("result").is_some());
    }

    #[tokio::test]
    async fn test_hook_manager_emit() {
        let mut manager = HookManager::new();
        manager.register_lifecycle(Arc::new(LoggingLifecycleHook));
        let _ = manager.check_pre_tool("test", "{}").await;
        manager
            .notify_post_tool("test", "{}", &ToolResult::success("ok"))
            .await;
        // No crash = success
    }

    #[tokio::test]
    async fn test_plugin_context_register_tool() {
        let mut ctx = PluginContext::new();
        // Just verify no crash
        ctx.register_lifecycle_hook(Arc::new(LoggingLifecycleHook));
        assert!(ctx.hooks.lifecycle_hooks.len() == 1);
    }
}