mofa-foundation 0.1.1

MoFA Foundation - Core building blocks and utilities
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
//! Standard LLM-based agent execution engine
//!
//! Provides specialized execution for LLM-based agents with:
//! - LLM chat completion with tool calling
//! - Tool execution loop with iteration limits
//! - Session management
//! - Message history tracking
//!
//! # Architecture
//!
//! This module uses composition over inheritance:
//! - Composes `BaseAgent` for MoFAAgent functionality
//! - Adds LLM-specific functionality on top
//!
//! ```text
//! +-------------------------------------------------------------+
//! |                     AgentExecutor                            |
//! +-------------------------------------------------------------+
//! |           BaseAgent (MoFAAgent implementation)               |
//! |   - id, name, capabilities, state                            |
//! |   - initialize, execute, shutdown                            |
//! +-------------------------------------------------------------+
//! |  + llm: Arc<dyn LLMProvider>                                |
//! |  + context: Arc<RwLock<PromptContext>>                       |
//! |  + tools: Arc<RwLock<SimpleToolRegistry>>                     |
//! |  + sessions: Arc<SessionManager>                              |
//! |  + config: AgentExecutorConfig                                |
//! +-------------------------------------------------------------+
//! ```

use async_trait::async_trait;
use mofa_kernel::agent::context::AgentContext;
use mofa_kernel::agent::error::{AgentError, AgentResult};
use mofa_kernel::agent::types::{ChatCompletionRequest, ChatMessage, LLMProvider, ToolDefinition};
use mofa_kernel::agent::{AgentCapabilities, AgentState, MoFAAgent};
use mofa_kernel::agent::{AgentInput, AgentOutput, InputType, OutputType};
use serde_json::Value;
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use tokio::sync::RwLock;

use crate::agent::base::BaseAgent;
use crate::agent::context::prompt::PromptContext;

use super::components::tool::SimpleToolRegistry;
use super::{Session, SessionManager};
use mofa_kernel::agent::components::tool::{Tool, ToolInput, ToolRegistry};

// ============================================================================
// Agent Executor Configuration
// ============================================================================

/// Agent execution configuration
#[derive(Clone)]
pub struct AgentExecutorConfig {
    /// Maximum tool iterations per message
    pub max_iterations: usize,
    /// Session timeout (optional)
    pub session_timeout: Option<std::time::Duration>,
    /// Default model to use
    pub default_model: Option<String>,
    /// Temperature for LLM calls
    pub temperature: Option<f32>,
    /// Max tokens for LLM responses
    pub max_tokens: Option<u32>,
}

impl Default for AgentExecutorConfig {
    fn default() -> Self {
        Self {
            max_iterations: 10,
            session_timeout: None,
            default_model: None,
            temperature: None,
            max_tokens: None,
        }
    }
}

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

    pub fn with_max_iterations(mut self, max: usize) -> Self {
        self.max_iterations = max;
        self
    }

    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.default_model = Some(model.into());
        self
    }

    pub fn with_temperature(mut self, temp: f32) -> Self {
        self.temperature = Some(temp);
        self
    }
}

// ============================================================================
// Agent Executor
// ============================================================================

/// Standard LLM-based agent executor
///
/// This executor handles the complete agent loop:
/// 1. Build context with system prompt, history, and current message
/// 2. Call LLM with tool definitions
/// 3. Execute tools if called
/// 4. Repeat until no more tool calls or max iterations reached
///
/// Uses composition with `BaseAgent` to avoid reimplementing MoFAAgent.
///
/// # Architecture
///
/// ```text
/// AgentExecutor
/// ├── BaseAgent (provides MoFAAgent implementation)
/// └── LLM-specific fields (llm, context, tools, sessions, config)
/// ```
///
/// # Example
///
/// ```rust,ignore
/// use mofa_foundation::agent::executor::{AgentExecutor, AgentExecutorConfig};
/// use std::sync::Arc;
///
/// let llm = Arc::new(MyLLMProvider::new());
/// let executor = AgentExecutor::new(llm, "/path/to/workspace").await?;
///
/// let response = executor.process_message("session", "Hello").await?;
/// ```
pub struct AgentExecutor {
    /// Base agent provides MoFAAgent implementation
    base: BaseAgent,

    /// ===== LLM-specific fields =====
    /// LLM provider
    llm: Arc<dyn LLMProvider>,
    /// Prompt context builder
    context: Arc<RwLock<PromptContext>>,
    /// Tool registry
    tools: Arc<RwLock<SimpleToolRegistry>>,
    /// Session manager
    sessions: Arc<SessionManager>,
    /// Configuration
    config: AgentExecutorConfig,
}

impl AgentExecutor {
    /// Create a new agent executor
    pub async fn new(llm: Arc<dyn LLMProvider>, workspace: impl AsRef<Path>) -> AgentResult<Self> {
        let workspace = workspace.as_ref();
        let context = Arc::new(RwLock::new(PromptContext::new(workspace).await?));
        let sessions = Arc::new(SessionManager::with_jsonl(workspace).await?);
        let tools = Arc::new(RwLock::new(SimpleToolRegistry::new()));

        // Create base agent with appropriate capabilities
        let base = BaseAgent::new(uuid::Uuid::now_v7().to_string(), "LLMExecutor")
            .with_description("LLM-based agent with tool calling")
            .with_version("1.0.0")
            .with_capabilities(
                AgentCapabilities::builder()
                    .tag("llm")
                    .tag("tool-calling")
                    .input_type(InputType::Text)
                    .output_type(OutputType::Text)
                    .supports_tools(true)
                    .build(),
            );

        Ok(Self {
            base,
            llm,
            context,
            tools,
            sessions,
            config: AgentExecutorConfig::default(),
        })
    }

    /// Create with custom configuration
    pub async fn with_config(
        llm: Arc<dyn LLMProvider>,
        workspace: impl AsRef<Path>,
        config: AgentExecutorConfig,
    ) -> AgentResult<Self> {
        let workspace = workspace.as_ref();
        let context = Arc::new(RwLock::new(PromptContext::new(workspace).await?));
        let sessions = Arc::new(SessionManager::with_jsonl(workspace).await?);
        let tools = Arc::new(RwLock::new(SimpleToolRegistry::new()));

        // Create base agent with appropriate capabilities
        let base = BaseAgent::new(uuid::Uuid::now_v7().to_string(), "LLMExecutor")
            .with_description("LLM-based agent with tool calling")
            .with_version("1.0.0")
            .with_capabilities(
                AgentCapabilities::builder()
                    .tag("llm")
                    .tag("tool-calling")
                    .input_type(InputType::Text)
                    .output_type(OutputType::Text)
                    .supports_tools(true)
                    .build(),
            );

        Ok(Self {
            base,
            llm,
            context,
            tools,
            sessions,
            config,
        })
    }

    /// Register a tool
    pub async fn register_tool(&self, tool: Arc<dyn Tool>) -> AgentResult<()> {
        let mut tools = self.tools.write().await;
        tools.register(tool)
    }

    /// Process a user message
    pub async fn process_message(
        &mut self,
        session_key: &str,
        message: &str,
    ) -> AgentResult<String> {
        // 1. Get or create session
        let session = self.sessions.get_or_create(session_key).await;

        // 2. Build system prompt
        let system_prompt = {
            let mut ctx = self.context.write().await;
            ctx.build_system_prompt().await?
        };

        // 3. Build messages
        let mut messages = self
            .build_messages(&session, &system_prompt, message)
            .await?;

        // 4. Run agent loop
        let response = self.run_agent_loop(&mut messages).await?;

        // 5. Update session
        let mut session_updated = session.clone();
        session_updated.add_message("user", message);
        session_updated.add_message("assistant", &response);
        self.sessions.save(&session_updated).await?;

        Ok(response)
    }

    /// Build the message list for LLM
    async fn build_messages(
        &self,
        session: &Session,
        system_prompt: &str,
        current_message: &str,
    ) -> AgentResult<Vec<ChatMessage>> {
        let mut messages = Vec::new();

        // System prompt
        messages.push(ChatMessage {
            role: "system".to_string(),
            content: Some(system_prompt.to_string()),
            tool_call_id: None,
            tool_calls: None,
        });

        // History
        let history = session.get_history(50); // Limit to recent messages
        for msg in history {
            messages.push(ChatMessage {
                role: msg.role,
                content: Some(msg.content),
                tool_call_id: None,
                tool_calls: None,
            });
        }

        // Current message
        messages.push(ChatMessage {
            role: "user".to_string(),
            content: Some(current_message.to_string()),
            tool_call_id: None,
            tool_calls: None,
        });

        Ok(messages)
    }

    /// Run the main agent loop with LLM and tool execution
    async fn run_agent_loop(&self, messages: &mut Vec<ChatMessage>) -> AgentResult<String> {
        for _iteration in 0..self.config.max_iterations {
            // Get tool definitions
            let tools = {
                let tools_guard = self.tools.read().await;
                tools_guard.list()
            };

            // Convert to OpenAI format
            let tool_definitions = if tools.is_empty() {
                None
            } else {
                Some(
                    tools
                        .iter()
                        .map(|t| ToolDefinition {
                            name: t.name.clone(),
                            description: t.description.clone(),
                            parameters: t.parameters_schema.clone(),
                        })
                        .collect(),
                )
            };

            // Call LLM
            let request = ChatCompletionRequest {
                messages: messages.clone(),
                model: self.config.default_model.clone(),
                tools: tool_definitions,
                temperature: self.config.temperature,
                max_tokens: self.config.max_tokens,
            };

            let response = self.llm.chat(request).await?;

            // Check for tool calls
            if let Some(tool_calls) = response.tool_calls {
                if tool_calls.is_empty() {
                    // No more tools, return response
                    return Ok(response.content.unwrap_or_default());
                }

                // Add assistant message with tool calls
                messages.push(ChatMessage {
                    role: "assistant".to_string(),
                    content: response.content,
                    tool_call_id: None,
                    tool_calls: Some(tool_calls.clone()),
                });

                // Execute tools
                for tool_call in tool_calls {
                    // Convert arguments to HashMap
                    let _args_map: HashMap<String, Value> =
                        if let Value::Object(map) = &tool_call.arguments {
                            map.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
                        } else {
                            return Err(AgentError::ExecutionFailed(format!(
                                "Invalid tool arguments for {}: {:?}",
                                tool_call.name, tool_call.arguments
                            )));
                        };

                    let result = {
                        let tools_guard = self.tools.read().await;
                        if let Some(tool) = tools_guard.get(&tool_call.name) {
                            let input = ToolInput::from_json(tool_call.arguments.clone());
                            tool.execute(input, &AgentContext::new("executor")).await
                        } else {
                            return Err(AgentError::ExecutionFailed(format!(
                                "Tool not found: {}",
                                tool_call.name
                            )));
                        }
                    };

                    // ToolResult is a struct with success bool and output
                    let result_str = if result.success {
                        result.to_string_output()
                    } else {
                        format!(
                            "Error: {}",
                            result.error.unwrap_or_else(|| "Unknown error".to_string())
                        )
                    };

                    // Add tool result message
                    messages.push(ChatMessage {
                        role: "tool".to_string(),
                        content: Some(result_str),
                        tool_call_id: Some(tool_call.id.clone()),
                        tool_calls: None,
                    });
                }
            } else {
                // No tool calls, return response
                return Ok(response.content.unwrap_or_default());
            }
        }

        // Max iterations exceeded
        Ok("I've completed processing but hit the maximum iteration limit.".to_string())
    }

    /// Get the session manager
    pub fn sessions(&self) -> &Arc<SessionManager> {
        &self.sessions
    }

    /// Get the tool registry
    pub fn tools(&self) -> &Arc<RwLock<SimpleToolRegistry>> {
        &self.tools
    }

    /// Get the prompt context
    pub fn context(&self) -> &Arc<RwLock<PromptContext>> {
        &self.context
    }

    /// Get the LLM provider
    pub fn llm(&self) -> &Arc<dyn LLMProvider> {
        &self.llm
    }

    /// Get the configuration
    pub fn config(&self) -> &AgentExecutorConfig {
        &self.config
    }

    /// Get mutable reference to base agent
    pub fn base_mut(&mut self) -> &mut BaseAgent {
        &mut self.base
    }

    /// Get reference to base agent
    pub fn base(&self) -> &BaseAgent {
        &self.base
    }
}

// ============================================================================
// MoFAAgent Trait Implementation via Delegation
// ============================================================================

#[async_trait]
impl MoFAAgent for AgentExecutor {
    fn id(&self) -> &str {
        self.base.id()
    }

    fn name(&self) -> &str {
        self.base.name()
    }

    fn capabilities(&self) -> &AgentCapabilities {
        self.base.capabilities()
    }

    fn state(&self) -> AgentState {
        self.base.state()
    }

    async fn initialize(&mut self, ctx: &AgentContext) -> AgentResult<()> {
        // Initialize base agent
        self.base.initialize(ctx).await?;

        // Additional executor-specific initialization
        self.base.transition_to(AgentState::Ready)?;

        Ok(())
    }

    async fn execute(
        &mut self,
        input: AgentInput,
        _ctx: &AgentContext,
    ) -> AgentResult<AgentOutput> {
        // For simplicity, use the text content from the input
        let message = input.as_text().unwrap_or("");
        let session_key = "default"; // Use default session for now

        // Process the message using the executor
        let response = self.process_message(session_key, message).await?;

        // Return the response as AgentOutput
        Ok(AgentOutput::text(response))
    }

    async fn shutdown(&mut self) -> AgentResult<()> {
        // Shutdown base agent
        self.base.shutdown().await
    }
}