enki-runtime 0.1.4

A Rust-based agent mesh framework for building local and distributed AI agent systems
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
//! Mesh configuration from TOML files.

use super::{AgentConfig, MemoryConfig};
use crate::core::error::{Error, Result};
use serde::{Deserialize, Serialize};
use std::path::Path;

/// Configuration for a multi-agent mesh.
///
/// This struct allows defining multiple agents in a single TOML file.
///
/// # Example
///
/// ```toml
/// name = "research_mesh"
///
/// [memory]
/// backend = "sqlite"
/// path = "./data/knowledge.db"
///
/// [[agents]]
/// name = "researcher"
/// model = "ollama::gemma3:latest"
/// system_prompt = "You are a research assistant."
/// temperature = 0.7
///
/// [[agents]]
/// name = "summarizer"
/// model = "ollama::gemma3:latest"
/// system_prompt = "You are a summarization expert."
/// temperature = 0.5
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MeshConfig {
    /// Name of the mesh
    pub name: String,

    /// Version of the mesh configuration
    #[serde(default)]
    pub version: Option<String>,

    /// Name of the agent to use as coordinator (must exist in agents list)
    /// Takes precedence over auto_coordinator if both are set
    #[serde(default)]
    pub coordinator: Option<String>,

    /// If true, mesh will auto-generate a coordinator agent with orchestration capabilities
    /// Only used if coordinator is not explicitly set
    #[serde(default)]
    pub auto_coordinator: bool,

    /// Default model for auto-generated coordinator (defaults to first agent's model)
    #[serde(default)]
    pub coordinator_model: Option<String>,

    /// Shared memory configuration for all agents (can be overridden per-agent)
    #[serde(default)]
    pub memory: Option<MemoryConfig>,

    /// List of agent configurations
    #[serde(default)]
    pub agents: Vec<AgentConfig>,
}

impl Default for MeshConfig {
    fn default() -> Self {
        Self {
            name: "mesh".to_string(),
            version: None,
            coordinator: None,
            auto_coordinator: false,
            coordinator_model: None,
            memory: None,
            agents: Vec::new(),
        }
    }
}

impl MeshConfig {
    /// Create a new MeshConfig with a name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            version: None,
            coordinator: None,
            auto_coordinator: false,
            coordinator_model: None,
            memory: None,
            agents: Vec::new(),
        }
    }

    /// Parse a MeshConfig from a TOML string.
    ///
    /// # Example
    ///
    /// ```rust
    /// use enki_runtime::config::MeshConfig;
    ///
    /// let toml = r#"
    /// name = "my_mesh"
    ///
    /// [[agents]]
    /// name = "agent1"
    /// model = "ollama::llama2"
    /// "#;
    ///
    /// let config = MeshConfig::from_toml(toml).unwrap();
    /// assert_eq!(config.name, "my_mesh");
    /// assert_eq!(config.agents.len(), 1);
    /// ```
    pub fn from_toml(toml_str: &str) -> Result<Self> {
        toml::from_str(toml_str)
            .map_err(|e| Error::ConfigError(format!("Failed to parse TOML: {}", e)))
    }

    /// Load a MeshConfig from a TOML file.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use enki_runtime::config::MeshConfig;
    ///
    /// let config = MeshConfig::from_file("agents.toml").unwrap();
    /// ```
    pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
        let content = std::fs::read_to_string(path.as_ref()).map_err(|e| {
            Error::ConfigError(format!(
                "Failed to read file '{}': {}",
                path.as_ref().display(),
                e
            ))
        })?;
        Self::from_toml(&content)
    }

    /// Add an agent configuration.
    pub fn add_agent(mut self, agent: AgentConfig) -> Self {
        self.agents.push(agent);
        self
    }

    /// Get agent config by name.
    pub fn get_agent(&self, name: &str) -> Option<&AgentConfig> {
        self.agents.iter().find(|a| a.name == name)
    }

    /// Get the coordinator agent configuration.
    ///
    /// Priority order:
    /// 1. Explicitly set `coordinator` field (must exist in agents list)
    /// 2. First agent in the list (default behavior)
    ///
    /// Returns None if no agents are defined.
    pub fn get_coordinator(&self) -> Option<&AgentConfig> {
        // If coordinator is explicitly set, find it
        if let Some(ref coordinator_name) = self.coordinator {
            return self.get_agent(coordinator_name);
        }

        // Check if there's an auto-generated coordinator
        if self.auto_coordinator {
            if let Some(coord) = self.get_agent("coordinator") {
                return Some(coord);
            }
        }

        // Fallback to first agent
        self.agents.first()
    }

    /// Get the name of the coordinator agent.
    pub fn get_coordinator_name(&self) -> Option<&str> {
        self.get_coordinator().map(|a| a.name.as_str())
    }

    /// Ensure a coordinator agent exists if auto_coordinator is enabled.
    ///
    /// This creates a built-in coordinator agent with orchestration capabilities
    /// that knows about all other agents in the mesh.
    ///
    /// Call this after loading the config and before using the mesh.
    pub fn ensure_coordinator(&mut self) {
        // Skip if coordinator is explicitly set
        if self.coordinator.is_some() {
            return;
        }

        // Skip if auto_coordinator is not enabled
        if !self.auto_coordinator {
            return;
        }

        // Skip if coordinator already exists
        if self.get_agent("coordinator").is_some() {
            return;
        }

        // Determine the model to use for coordinator
        let model = self
            .coordinator_model
            .clone()
            .or_else(|| self.agents.first().map(|a| a.model.clone()))
            .unwrap_or_else(|| "ollama::gemma3:latest".to_string());

        // Build list of available agents for the system prompt
        let agent_list: Vec<String> = self
            .agents
            .iter()
            .map(|a| {
                let desc = if a.system_prompt.len() > 100 {
                    format!("{}...", &a.system_prompt[..100])
                } else {
                    a.system_prompt.clone()
                };
                format!("- {}: {}", a.name, desc)
            })
            .collect();

        let system_prompt = format!(
            r#"You are a coordinator agent responsible for orchestrating tasks across multiple specialized agents.

Your role is to:
1. Understand user requests and break them down into subtasks
2. Delegate subtasks to the most appropriate specialized agent
3. Synthesize responses from multiple agents when needed
4. Provide cohesive, helpful responses to the user

Available agents in this mesh:
{}

When delegating tasks, consider each agent's specialization and choose the best fit.
If a task requires multiple agents, coordinate their efforts and combine their outputs."#,
            agent_list.join("\n")
        );

        let coordinator = AgentConfig::new("coordinator", model)
            .with_system_prompt(system_prompt)
            .with_temperature(0.7);

        // Insert coordinator at the beginning
        self.agents.insert(0, coordinator);
    }

    /// Set the coordinator agent by name.
    pub fn with_coordinator(mut self, name: impl Into<String>) -> Self {
        self.coordinator = Some(name.into());
        self
    }

    /// Enable auto-coordinator with optional model.
    pub fn with_auto_coordinator(mut self, model: Option<String>) -> Self {
        self.auto_coordinator = true;
        self.coordinator_model = model;
        self
    }
}

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

    #[test]
    fn test_parse_mesh_config() {
        let toml = r#"
            name = "test_mesh"

            [[agents]]
            name = "agent1"
            model = "ollama::llama2"
            system_prompt = "First agent"

            [[agents]]
            name = "agent2"
            model = "openai::gpt-4"
            temperature = 0.8
        "#;

        let config = MeshConfig::from_toml(toml).unwrap();
        assert_eq!(config.name, "test_mesh");
        assert_eq!(config.agents.len(), 2);
        assert_eq!(config.agents[0].name, "agent1");
        assert_eq!(config.agents[1].name, "agent2");
        assert_eq!(config.agents[1].temperature, Some(0.8));
    }

    #[test]
    fn test_get_agent() {
        let config = MeshConfig::new("test")
            .add_agent(AgentConfig::new("agent1", "ollama::llama2"))
            .add_agent(AgentConfig::new("agent2", "ollama::llama2"));

        assert!(config.get_agent("agent1").is_some());
        assert!(config.get_agent("agent2").is_some());
        assert!(config.get_agent("nonexistent").is_none());
    }

    #[test]
    fn test_empty_agents() {
        let toml = r#"
            name = "empty_mesh"
        "#;

        let config = MeshConfig::from_toml(toml).unwrap();
        assert_eq!(config.name, "empty_mesh");
        assert!(config.agents.is_empty());
    }

    #[test]
    fn test_get_coordinator_default_first_agent() {
        let config = MeshConfig::new("test")
            .add_agent(AgentConfig::new("agent1", "ollama::llama2"))
            .add_agent(AgentConfig::new("agent2", "ollama::llama2"));

        // Default: first agent is coordinator
        let coordinator = config.get_coordinator();
        assert!(coordinator.is_some());
        assert_eq!(coordinator.unwrap().name, "agent1");
    }

    #[test]
    fn test_get_coordinator_designated() {
        let config = MeshConfig::new("test")
            .add_agent(AgentConfig::new("agent1", "ollama::llama2"))
            .add_agent(AgentConfig::new("agent2", "ollama::llama2"))
            .with_coordinator("agent2");

        // Designated coordinator takes precedence
        let coordinator = config.get_coordinator();
        assert!(coordinator.is_some());
        assert_eq!(coordinator.unwrap().name, "agent2");
    }

    #[test]
    fn test_ensure_coordinator_auto() {
        let mut config = MeshConfig::new("test")
            .add_agent(AgentConfig::new("worker1", "ollama::llama2"))
            .add_agent(AgentConfig::new("worker2", "ollama::llama2"))
            .with_auto_coordinator(None);

        // Before ensure_coordinator
        assert_eq!(config.agents.len(), 2);

        // After ensure_coordinator
        config.ensure_coordinator();
        assert_eq!(config.agents.len(), 3);

        // Coordinator should be first
        assert_eq!(config.agents[0].name, "coordinator");

        // get_coordinator should return the auto-generated coordinator
        let coordinator = config.get_coordinator();
        assert!(coordinator.is_some());
        assert_eq!(coordinator.unwrap().name, "coordinator");

        // System prompt should mention available agents
        assert!(config.agents[0].system_prompt.contains("worker1"));
        assert!(config.agents[0].system_prompt.contains("worker2"));
    }

    #[test]
    fn test_ensure_coordinator_skips_if_designated() {
        let mut config = MeshConfig::new("test")
            .add_agent(AgentConfig::new("agent1", "ollama::llama2"))
            .add_agent(AgentConfig::new("agent2", "ollama::llama2"))
            .with_coordinator("agent1")
            .with_auto_coordinator(None);

        config.auto_coordinator = true; // Also set auto_coordinator

        // Should not create auto coordinator when designated exists
        config.ensure_coordinator();
        assert_eq!(config.agents.len(), 2); // No new agent added
    }

    #[test]
    fn test_parse_coordinator_from_toml() {
        let toml = r#"
            name = "test_mesh"
            coordinator = "agent2"

            [[agents]]
            name = "agent1"
            model = "ollama::llama2"

            [[agents]]
            name = "agent2"
            model = "ollama::llama2"
        "#;

        let config = MeshConfig::from_toml(toml).unwrap();
        assert_eq!(config.coordinator, Some("agent2".to_string()));

        let coordinator = config.get_coordinator();
        assert_eq!(coordinator.unwrap().name, "agent2");
    }

    #[test]
    fn test_parse_auto_coordinator_from_toml() {
        let toml = r#"
            name = "test_mesh"
            auto_coordinator = true
            coordinator_model = "ollama::gemma3:latest"

            [[agents]]
            name = "worker1"
            model = "ollama::llama2"
        "#;

        let mut config = MeshConfig::from_toml(toml).unwrap();
        assert!(config.auto_coordinator);
        assert_eq!(
            config.coordinator_model,
            Some("ollama::gemma3:latest".to_string())
        );

        config.ensure_coordinator();
        assert_eq!(config.agents.len(), 2);
        assert_eq!(config.agents[0].name, "coordinator");
        assert_eq!(config.agents[0].model, "ollama::gemma3:latest");
    }
}