enki-next 0.5.79

Enki's Rust agent runtime, workflow engine, and shared core abstractions.
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
use crate::agent::{Agent, AgentDefinition, AgentExecutionContext, AgentRunResult};
use crate::llm::LlmProvider;
use crate::memory::MemoryManager;
use crate::registry::{AgentCard, AgentRegistry, AgentStatus, FirstMatchSelector, PeerSelector};
use crate::tooling::delegation_tools::{DelegateTaskTool, DiscoverAgentsTool};
use crate::tooling::tool_calling::{RegistryToolExecutor, ToolExecutor};
use crate::tooling::types::{DelegateFn, Tool, ToolRegistry, WorkflowToolContext};
use crate::workflow::{TaskTarget, WorkflowTaskResult, WorkflowTaskRunner};
use async_trait::async_trait;
use serde_json::json;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

// ---------------------------------------------------------------------------
// MultiAgentRuntime
// ---------------------------------------------------------------------------

/// A runtime that manages multiple named agents sharing a common
/// `AgentRegistry`.  Agents can discover each other and delegate tasks
/// through runtime-injected tools.
pub struct MultiAgentRuntime {
    registry: Arc<AgentRegistry>,
    agents: HashMap<String, Arc<Agent>>,
    #[allow(dead_code)]
    selector: Box<dyn PeerSelector>,
}

impl MultiAgentRuntime {
    pub fn builder() -> MultiAgentRuntimeBuilder {
        MultiAgentRuntimeBuilder::new()
    }

    /// Process a request targeting a specific agent by `agent_id`.
    pub async fn process(
        &self,
        agent_id: &str,
        session_id: &str,
        message: &str,
    ) -> Result<String, String> {
        Ok(self
            .process_detailed(agent_id, session_id, message, None)
            .await?
            .content)
    }

    pub async fn process_detailed(
        &self,
        agent_id: &str,
        session_id: &str,
        message: &str,
        on_step: Option<std::sync::Arc<dyn Fn(crate::agent::types::ExecutionStep) + Send + Sync>>,
    ) -> Result<AgentRunResult, String> {
        let agent = self
            .agents
            .get(agent_id)
            .ok_or_else(|| format!("Agent '{agent_id}' not found in runtime."))?;

        Ok(agent.run_detailed(session_id, message, on_step).await)
    }

    pub fn registry(&self) -> &Arc<AgentRegistry> {
        &self.registry
    }

    pub fn agent_ids(&self) -> Vec<&String> {
        self.agents.keys().collect()
    }
}

// ---------------------------------------------------------------------------
// RuntimeDelegateFn — the callback wired into each agent's DelegationContext
// ---------------------------------------------------------------------------

struct RuntimeDelegateFn {
    agents: HashMap<String, Arc<Agent>>,
}

#[async_trait(?Send)]
impl DelegateFn for RuntimeDelegateFn {
    async fn delegate(&self, target_agent_id: &str, task: &str) -> Result<String, String> {
        let agent = self
            .agents
            .get(target_agent_id)
            .ok_or_else(|| format!("Agent '{target_agent_id}' not found."))?;

        // Use a delegation-specific session so we don't pollute the caller's history
        let session_id = format!("delegation-{}-{}", target_agent_id, uuid_v4_simple());
        Ok(agent.run(&session_id, task).await)
    }
}

fn uuid_v4_simple() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or_default();
    format!("{nanos:x}")
}

fn workflow_task_failure_message(result: &AgentRunResult) -> Option<String> {
    if result
        .steps
        .last()
        .is_some_and(|step| matches!(step.kind.as_str(), "failed" | "error"))
    {
        return Some(result.content.trim().to_string());
    }

    if result.content.trim_start().starts_with("LLM error:") {
        return Some(result.content.trim().to_string());
    }

    None
}

#[async_trait(?Send)]
impl WorkflowTaskRunner for MultiAgentRuntime {
    async fn run_task(
        &self,
        target: &TaskTarget,
        metadata: &WorkflowToolContext,
        workspace_dir: &std::path::Path,
        prompt: &str,
    ) -> Result<WorkflowTaskResult, String> {
        let agent_id = match target {
            TaskTarget::AgentId(agent_id) => {
                if !self.agents.contains_key(agent_id) {
                    return Err(format!("Workflow target agent '{}' not found.", agent_id));
                }
                agent_id.clone()
            }
            TaskTarget::Capabilities(required) => {
                let cards = self.registry().list_all().await;
                let mut matches = cards
                    .into_iter()
                    .filter(|card| card.status == AgentStatus::Online)
                    .filter(|card| {
                        required.iter().all(|required| {
                            card.capabilities
                                .iter()
                                .any(|capability| capability == required)
                        })
                    })
                    .map(|card| card.agent_id)
                    .collect::<Vec<_>>();
                matches.sort();
                match matches.as_slice() {
                    [agent_id] => agent_id.clone(),
                    [] => {
                        return Err(format!(
                            "No online agent matched workflow capabilities: {}",
                            required.join(", ")
                        ));
                    }
                    _ => {
                        return Err(format!(
                            "Multiple agents matched workflow capabilities {}: {}",
                            required.join(", "),
                            matches.join(", ")
                        ));
                    }
                }
            }
        };

        let agent = self
            .agents
            .get(&agent_id)
            .ok_or_else(|| format!("Workflow target agent '{}' not found.", agent_id))?;
        let session_id = format!(
            "wf-{}-{}-attempt-{}",
            metadata.run_id, metadata.node_id, metadata.attempt
        );
        let result = agent
            .run_detailed_with_context(
                &session_id,
                prompt,
                AgentExecutionContext {
                    workspace_dir: Some(workspace_dir.to_path_buf()),
                    workflow: Some(metadata.clone()),
                },
                None,
            )
            .await;

        if let Some(error) = workflow_task_failure_message(&result) {
            return Err(error);
        }

        Ok(WorkflowTaskResult {
            content: result.content.clone(),
            value: json!({
                "content": result.content,
                "agent_id": agent_id,
                "session_id": session_id,
                "attempt": metadata.attempt,
            }),
            agent_id,
            steps: result.steps,
        })
    }
}
// ---------------------------------------------------------------------------
// MultiAgentRuntimeBuilder
// ---------------------------------------------------------------------------

struct AgentSpec {
    agent_id: String,
    definition: AgentDefinition,
    capabilities: Vec<String>,
    llm: Option<Box<dyn LlmProvider>>,
    memory: Option<MemoryManager>,
    tool_registry: ToolRegistry,
    tool_executor: Option<Box<dyn ToolExecutor>>,
}

pub struct MultiAgentRuntimeBuilder {
    specs: Vec<AgentSpec>,
    selector: Option<Box<dyn PeerSelector>>,
    workspace_home: Option<PathBuf>,
}

impl MultiAgentRuntimeBuilder {
    pub fn new() -> Self {
        Self {
            specs: Vec::new(),
            selector: None,
            workspace_home: None,
        }
    }

    /// Add an agent with a definition and declared capabilities.
    pub fn add_agent(
        mut self,
        agent_id: impl Into<String>,
        definition: AgentDefinition,
        capabilities: Vec<String>,
    ) -> Self {
        self.specs.push(AgentSpec {
            agent_id: agent_id.into(),
            definition,
            capabilities,
            llm: None,
            memory: None,
            tool_registry: ToolRegistry::new(),
            tool_executor: None,
        });
        self
    }

    /// Add an agent with a custom LLM provider.
    pub fn add_agent_with_llm(
        mut self,
        agent_id: impl Into<String>,
        definition: AgentDefinition,
        capabilities: Vec<String>,
        llm: Box<dyn LlmProvider>,
    ) -> Self {
        self.specs.push(AgentSpec {
            agent_id: agent_id.into(),
            definition,
            capabilities,
            llm: Some(llm),
            memory: None,
            tool_registry: ToolRegistry::new(),
            tool_executor: None,
        });
        self
    }

    /// Add an agent with a full custom spec including tools, executor, memory,
    /// and LLM.
    pub fn add_agent_full(
        mut self,
        agent_id: impl Into<String>,
        definition: AgentDefinition,
        capabilities: Vec<String>,
        llm: Option<Box<dyn LlmProvider>>,
        memory: Option<MemoryManager>,
        tool_registry: ToolRegistry,
        tool_executor: Option<Box<dyn ToolExecutor>>,
    ) -> Self {
        self.specs.push(AgentSpec {
            agent_id: agent_id.into(),
            definition,
            capabilities,
            llm,
            memory,
            tool_registry,
            tool_executor,
        });
        self
    }

    pub fn with_selector(mut self, selector: Box<dyn PeerSelector>) -> Self {
        self.selector = Some(selector);
        self
    }

    pub fn with_workspace_home(mut self, home: impl Into<PathBuf>) -> Self {
        self.workspace_home = Some(home.into());
        self
    }

    pub async fn build(self) -> Result<MultiAgentRuntime, String> {
        let registry = Arc::new(AgentRegistry::new());
        let selector = self
            .selector
            .unwrap_or_else(|| Box::new(FirstMatchSelector));

        // Phase 1: Build all agents (without delegation context yet — we need
        // the full agent map for the delegate_fn).
        let mut agents: HashMap<String, Arc<Agent>> = HashMap::new();

        for spec in &self.specs {
            // Register the agent card in the registry
            let card = AgentCard::new(
                &spec.agent_id,
                &spec.definition.name,
                &spec.definition.system_prompt_preamble,
                spec.capabilities.clone(),
            )
            .with_status(AgentStatus::Online);
            registry.register(card).await;
        }

        // Phase 2: Build agents with delegation tools injected.
        for spec in self.specs {
            let mut tool_registry = spec.tool_registry;

            // We inject placeholder delegation tools here. They'll work via
            // the DelegationContext attached to each ToolContext at call time.
            // The actual delegate_fn is wired below in Phase 3.
            tool_registry.insert(
                "discover_agents".to_string(),
                Arc::new(DiscoverAgentsTool) as Arc<dyn Tool>,
            );
            tool_registry.insert(
                "delegate_task".to_string(),
                Arc::new(DelegateTaskTool) as Arc<dyn Tool>,
            );

            let tool_executor = spec
                .tool_executor
                .unwrap_or_else(|| Box::new(RegistryToolExecutor));

            let agent = Agent::with_definition_tool_registry_executor_llm_and_workspace(
                spec.definition,
                tool_registry,
                tool_executor,
                spec.llm,
                spec.memory,
                self.workspace_home.clone(),
            )
            .await?;

            agents.insert(spec.agent_id, Arc::new(agent));
        }

        Ok(MultiAgentRuntime {
            registry,
            agents,
            selector,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::{AgentDefinition, ExecutionStep};
    use crate::llm::{
        ChatMessage, LlmConfig, LlmError, LlmProvider, LlmResponse, Result as LlmResult,
        ToolDefinition,
    };
    use async_trait::async_trait;
    use futures::stream;
    use std::collections::VecDeque;
    use std::sync::Mutex;
    use std::time::{SystemTime, UNIX_EPOCH};

    #[derive(Clone)]
    struct RecordingLlm {
        responses: Arc<Mutex<VecDeque<LlmResponse>>>,
    }

    impl RecordingLlm {
        fn new(responses: Vec<LlmResponse>) -> Self {
            Self {
                responses: Arc::new(Mutex::new(responses.into())),
            }
        }
    }

    #[async_trait]
    impl LlmProvider for RecordingLlm {
        async fn complete(
            &self,
            _messages: &[ChatMessage],
            _config: &LlmConfig,
        ) -> LlmResult<LlmResponse> {
            Err(LlmError::Provider("not used".to_string()))
        }

        async fn complete_stream(
            &self,
            _messages: &[ChatMessage],
            _config: &LlmConfig,
        ) -> LlmResult<crate::llm::ResponseStream> {
            Ok(Box::pin(stream::empty()))
        }

        async fn complete_with_tools(
            &self,
            _messages: &[ChatMessage],
            _tools: &[ToolDefinition],
            _config: &LlmConfig,
        ) -> LlmResult<LlmResponse> {
            self.responses
                .lock()
                .unwrap()
                .pop_front()
                .ok_or_else(|| LlmError::Provider("missing response".to_string()))
        }

        fn name(&self) -> &'static str {
            "recording"
        }

        fn available_models(&self) -> Vec<&'static str> {
            vec!["recording"]
        }
    }

    fn temp_home(label: &str) -> PathBuf {
        let path = std::env::temp_dir().join(format!(
            "core-next-multi-agent-tests-{label}-{}",
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or_default()
        ));
        std::fs::create_dir_all(&path).unwrap();
        path
    }

    #[test]
    fn workflow_task_failure_message_detects_terminal_agent_failures() {
        let failure = workflow_task_failure_message(&AgentRunResult {
            content: "LLM error: Model returned an empty response with no tool calls.".into(),
            steps: vec![ExecutionStep {
                index: 3,
                phase: "recover".into(),
                kind: "failed".into(),
                detail: "LLM error: Model returned an empty response with no tool calls.".into(),
            }],
        });

        assert_eq!(
            failure.as_deref(),
            Some("LLM error: Model returned an empty response with no tool calls.")
        );
    }

    #[test]
    fn workflow_task_failure_message_ignores_successful_agent_results() {
        let failure = workflow_task_failure_message(&AgentRunResult {
            content: "Finished the task successfully.".into(),
            steps: vec![ExecutionStep {
                index: 2,
                phase: "respond".into(),
                kind: "final".into(),
                detail: "Finished the task successfully.".into(),
            }],
        });

        assert!(failure.is_none());
    }

    #[tokio::test]
    async fn multi_agent_runtime_registers_agents() {
        let home = temp_home("register");
        let runtime = MultiAgentRuntime::builder()
            .add_agent_with_llm(
                "coder",
                AgentDefinition {
                    name: "Coder".into(),
                    system_prompt_preamble: "You write code.".into(),
                    model: "recording".into(),
                    max_iterations: 2,
                },
                vec!["code-gen".into()],
                Box::new(RecordingLlm::new(vec![LlmResponse {
                    content: "ok".into(),
                    usage: None,
                    tool_calls: vec![],
                    model: "recording".into(),
                    finish_reason: Some("stop".into()),
                }])),
            )
            .add_agent_with_llm(
                "researcher",
                AgentDefinition {
                    name: "Researcher".into(),
                    system_prompt_preamble: "You do research.".into(),
                    model: "recording".into(),
                    max_iterations: 2,
                },
                vec!["research".into()],
                Box::new(RecordingLlm::new(vec![LlmResponse {
                    content: "ok".into(),
                    usage: None,
                    tool_calls: vec![],
                    model: "recording".into(),
                    finish_reason: Some("stop".into()),
                }])),
            )
            .with_workspace_home(home)
            .build()
            .await
            .unwrap();

        let all = runtime.registry().list_all().await;
        assert_eq!(all.len(), 2);

        let coder = runtime.registry().get("coder").await.unwrap();
        assert_eq!(coder.capabilities, vec!["code-gen"]);
        assert_eq!(coder.status, AgentStatus::Online);
    }

    #[tokio::test]
    async fn multi_agent_runtime_processes_request() {
        let home = temp_home("process");
        let runtime = MultiAgentRuntime::builder()
            .add_agent_with_llm(
                "helper",
                AgentDefinition {
                    name: "Helper".into(),
                    system_prompt_preamble: "You help.".into(),
                    model: "recording".into(),
                    max_iterations: 2,
                },
                vec![],
                Box::new(RecordingLlm::new(vec![LlmResponse {
                    content: "I helped!".into(),
                    usage: None,
                    tool_calls: vec![],
                    model: "recording".into(),
                    finish_reason: Some("stop".into()),
                }])),
            )
            .with_workspace_home(home)
            .build()
            .await
            .unwrap();

        let response = runtime
            .process("helper", "s1", "do something")
            .await
            .unwrap();
        assert_eq!(response, "I helped!");
    }

    #[tokio::test]
    async fn multi_agent_runtime_unknown_agent_returns_error() {
        let home = temp_home("unknown");
        let runtime = MultiAgentRuntime::builder()
            .add_agent_with_llm(
                "only-agent",
                AgentDefinition {
                    name: "Only".into(),
                    system_prompt_preamble: "...".into(),
                    model: "recording".into(),
                    max_iterations: 2,
                },
                vec![],
                Box::new(RecordingLlm::new(vec![LlmResponse {
                    content: "ok".into(),
                    usage: None,
                    tool_calls: vec![],
                    model: "recording".into(),
                    finish_reason: Some("stop".into()),
                }])),
            )
            .with_workspace_home(home)
            .build()
            .await
            .unwrap();

        let result = runtime.process("ghost", "s1", "hello").await;
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("not found"));
    }
}