Skip to main content

re_agent/
capability.rs

1//! Capability-Registry: die eine Wahrheit darüber, was die Engine kann.
2//!
3//! Editor-UI, Direkt-KI und MCP-Server speisen sich alle aus derselben
4//! Liste — neue Engine-Funktionen sind damit automatisch auch KI-Werkzeuge.
5
6use serde::{Deserialize, Serialize};
7use serde_json::{json, Value};
8use std::collections::BTreeMap;
9
10/// JSON-Wert (Parameter/Rückgaben der Werkzeuge).
11pub type Json = Value;
12
13/// Selbstbeschreibung eines Werkzeugs — kompatibel zu OpenAI tool-schema
14/// und MCP `tools/list`, daher hier generisch gehalten.
15#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
16pub struct ToolSpec {
17    pub name: String,
18    pub description: String,
19    /// JSON-Schema-Fragment: `{"typ": "object", "felder": {...}}` o. ä.
20    /// M1 nutzt ein vereinfachtes Schema; M4 normalisiert es vollständig.
21    pub params: Json,
22}
23
24impl ToolSpec {
25    pub fn new(name: impl Into<String>, description: impl Into<String>, params: Json) -> Self {
26        Self {
27            name: name.into(),
28            description: description.into(),
29            params,
30        }
31    }
32
33    /// Parameterloses Werkzeug.
34    pub fn simple(name: impl Into<String>, description: impl Into<String>) -> Self {
35        Self::new(name, description, json!({ "typ": "object", "felder": {} }))
36    }
37}
38
39#[derive(Debug, thiserror::Error)]
40pub enum CapabilityError {
41    #[error("unbekanntes Werkzeug: {0}")]
42    Unknown(String),
43    #[error("Werkzeug '{name}' fehlgeschlagen: {reason}")]
44    Run { name: String, reason: String },
45}
46
47type Runner = Box<dyn Fn(Json) -> Result<Json, String> + Send>;
48
49pub struct Capability {
50    pub spec: ToolSpec,
51    runner: Runner,
52}
53
54/// Registry aller Engine-Funktionen. `call` ist `&self`, damit der
55/// Agent-Loop parallel zum Editor lesen kann; schreibende Capabilities
56/// kapseln ihre innere Mutabilität selbst (Editor-Channel, Mutex, …).
57#[derive(Default)]
58pub struct CapabilityRegistry {
59    tools: BTreeMap<String, Capability>,
60}
61
62impl CapabilityRegistry {
63    pub fn new() -> Self {
64        Self::default()
65    }
66
67    pub fn register<F>(&mut self, spec: ToolSpec, f: F)
68    where
69        F: Fn(Json) -> Result<Json, String> + Send + 'static,
70    {
71        let name = spec.name.clone();
72        tracing::debug!(tool = %name, "Capability registriert");
73        self.tools.insert(
74            name,
75            Capability {
76                spec,
77                runner: Box::new(f),
78            },
79        );
80    }
81
82    pub fn remove(&mut self, name: &str) -> Option<ToolSpec> {
83        self.tools.remove(name).map(|c| c.spec)
84    }
85
86    pub fn len(&self) -> usize {
87        self.tools.len()
88    }
89
90    pub fn is_empty(&self) -> bool {
91        self.tools.is_empty()
92    }
93
94    pub fn specs(&self) -> Vec<ToolSpec> {
95        self.tools.values().map(|c| c.spec.clone()).collect()
96    }
97
98    pub fn has(&self, name: &str) -> bool {
99        self.tools.contains_key(name)
100    }
101
102    /// Ein Werkzeug ausführen (Direktweg des Agent-Loops).
103    pub fn call(&self, name: &str, args: Json) -> Result<Json, CapabilityError> {
104        let cap = self
105            .tools
106            .get(name)
107            .ok_or_else(|| CapabilityError::Unknown(name.to_string()))?;
108        (cap.runner)(args).map_err(|reason| CapabilityError::Run {
109            name: name.to_string(),
110            reason,
111        })
112    }
113
114    /// Kompakte Werkzeugliste für den System-Prompt (Token-sparend).
115    pub fn prompt_block(&self) -> String {
116        let mut out = String::from("Verfügbare Werkzeuge:\n");
117        for c in self.tools.values() {
118            out.push_str(&format!("- {}: {}\n", c.spec.name, c.spec.description));
119        }
120        out
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127
128    #[test]
129    fn registry_registriert_und_ruft_au() {
130        let mut reg = CapabilityRegistry::new();
131        reg.register(
132            ToolSpec::new("add", "zwei Zahlen addieren", json!({})),
133            |args| {
134                let a = args.get("a").and_then(|v| v.as_i64()).ok_or("a fehlt")?;
135                let b = args.get("b").and_then(|v| v.as_i64()).ok_or("b fehlt")?;
136                Ok(json!(a + b))
137            },
138        );
139        assert_eq!(
140            reg.call("add", json!({"a": 2, "b": 40})).unwrap(),
141            json!(42)
142        );
143        assert!(matches!(
144            reg.call("fehlt", json!({})),
145            Err(CapabilityError::Unknown(_))
146        ));
147        assert!(reg.call("add", json!({})).is_err());
148        assert!(reg.prompt_block().contains("add"));
149    }
150}