mermaid-cli 0.6.0

Open-source AI pair programmer with agentic capabilities. Local-first with Ollama, native tool calling, and beautiful TUI.
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
//! Subagent execution engine
//!
//! Spawns autonomous sub-agents that run in parallel, each with their own
//! conversation context and full tool access (minus `agent`).
//! Progress is tracked via shared state for live UI rendering.

use std::sync::{Arc, Mutex};
use std::time::Instant;

use tokio::sync::RwLock;
use tokio::task::JoinHandle;
use tracing::{info, warn};

use crate::agents::{ActionResult as AgentActionResult, AgentAction};
use crate::constants::MAX_CONCURRENT_AGENTS;
use crate::models::{
    ChatMessage, Model, ModelConfig, ReasoningLevel, StreamCallback, StreamEvent, ToolCall,
};
use crate::prompts;
use crate::runtime::agent_loop::{self, AgentObserver, LoopControl, MAX_AGENT_ITERATIONS};
use crate::utils::MutexExt;

/// Progress state for a single running subagent.
/// Written by the subagent task, read by the UI render loop.
#[derive(Debug, Clone)]
pub struct SubagentProgress {
    pub id: usize,
    pub description: String,
    pub status: SubagentStatus,
    pub tool_uses: usize,
    pub tokens: usize,
    pub started_at: Instant,
}

/// Status of a running subagent
#[derive(Debug, Clone)]
pub enum SubagentStatus {
    Running,
    Completed,
    Failed(String),
}

/// Final result returned when a subagent finishes
#[derive(Debug, Clone)]
pub struct SubagentResult {
    pub id: usize,
    pub description: String,
    pub response: String,
    pub tool_uses: usize,
    pub tokens: usize,
    pub duration_secs: f64,
    pub success: bool,
}

/// Observer that bridges the shared agent loop to subagent progress state.
struct SubagentObserver {
    progress: Arc<Mutex<Vec<SubagentProgress>>>,
    index: usize,
}

impl AgentObserver for SubagentObserver {
    fn check_interrupt(&mut self) -> LoopControl {
        // Subagents don't get interrupted individually.
        // Parent abort (via JoinHandle::abort()) is the cancellation mechanism.
        LoopControl::Continue
    }

    fn on_status(&mut self, _message: &str) {}

    fn on_tool_result(
        &mut self,
        _tool_name: &str,
        _tool_call_id: &str,
        _action: &AgentAction,
        _result: &AgentActionResult,
    ) {
        let mut progress = self.progress.lock_mut_safe();
        if let Some(entry) = progress.get_mut(self.index) {
            entry.tool_uses += 1;
        }
    }

    fn on_error(&mut self, error: &str) {
        warn!(subagent_index = self.index, "Subagent error: {}", error);
    }

    fn on_generation_start(&mut self) {}

    fn on_generation_complete(&mut self, tokens: usize) {
        let mut progress = self.progress.lock_mut_safe();
        if let Some(entry) = progress.get_mut(self.index) {
            entry.tokens += tokens;
        }
    }
}

/// Run a single subagent to completion.
async fn run_subagent(
    model: Arc<RwLock<Box<dyn Model>>>,
    config: ModelConfig,
    id: usize,
    prompt: String,
    description: String,
    progress: Arc<Mutex<Vec<SubagentProgress>>>,
    progress_index: usize,
) -> SubagentResult {
    let started_at = Instant::now();

    // Build fresh message history for this subagent
    let system_prompt = config
        .system_prompt
        .clone()
        .unwrap_or_else(prompts::get_system_prompt);
    let mut messages = vec![
        ChatMessage::system(system_prompt),
        ChatMessage::user(prompt),
    ];

    // First model call. Subagents don't surface reasoning to the parent
    // (the parent just sees the final summary), so we drop Reasoning
    // chunks. Text + tool calls feed the agent loop the same way the
    // legacy text accumulator did.
    let response_text = Arc::new(std::sync::Mutex::new(String::new()));
    let typed_tool_calls = Arc::new(std::sync::Mutex::new(Vec::<ToolCall>::new()));
    let text_clone = Arc::clone(&response_text);
    let tool_clone = Arc::clone(&typed_tool_calls);
    let callback: StreamCallback = Arc::new(move |event| match event {
        StreamEvent::Text(chunk) => {
            text_clone.lock_mut_safe().push_str(&chunk);
        },
        StreamEvent::ToolCall(tc) => {
            tool_clone.lock_mut_safe().push(tc);
        },
        StreamEvent::Reasoning(_) | StreamEvent::Done { .. } => {},
    });

    let initial_result = {
        let model_guard = model.read().await;
        model_guard.chat(&messages, &config, Some(callback)).await
    };

    let (content, initial_tool_calls, initial_tokens) = match initial_result {
        Ok(response) => {
            let streamed_text = response_text.lock_mut_safe().clone();
            let content = if !streamed_text.is_empty() {
                streamed_text
            } else {
                response.content.clone()
            };
            let tokens = response.usage.map(|u| u.total_tokens).unwrap_or(0);
            let streamed_tool_calls = std::mem::take(&mut *typed_tool_calls.lock_mut_safe());
            let tool_calls = if !streamed_tool_calls.is_empty() {
                streamed_tool_calls
            } else {
                response.tool_calls.unwrap_or_default()
            };

            {
                let mut prog = progress.lock_mut_safe();
                if let Some(entry) = prog.get_mut(progress_index) {
                    entry.tokens += tokens;
                }
            }

            (content, tool_calls, tokens)
        },
        Err(e) => {
            let error_msg = e.to_string();
            {
                let mut prog = progress.lock_mut_safe();
                if let Some(entry) = prog.get_mut(progress_index) {
                    entry.status = SubagentStatus::Failed(error_msg.clone());
                }
            }
            return SubagentResult {
                id,
                description,
                response: error_msg,
                tool_uses: 0,
                tokens: 0,
                duration_secs: started_at.elapsed().as_secs_f64(),
                success: false,
            };
        },
    };

    // If no tool calls, subagent is done after the first response
    if initial_tool_calls.is_empty() {
        {
            let mut prog = progress.lock_mut_safe();
            if let Some(entry) = prog.get_mut(progress_index) {
                entry.status = SubagentStatus::Completed;
            }
        }
        return SubagentResult {
            id,
            description,
            response: content,
            tool_uses: 0,
            tokens: initial_tokens,
            duration_secs: started_at.elapsed().as_secs_f64(),
            success: true,
        };
    }

    // Has tool calls -- enter agent loop
    let assistant_msg =
        ChatMessage::assistant(content.clone()).with_tool_calls(initial_tool_calls.clone());
    messages.push(assistant_msg);

    let mut observer = SubagentObserver {
        progress: Arc::clone(&progress),
        index: progress_index,
    };

    let loop_result = agent_loop::run_agent_loop(
        Arc::clone(&model),
        &config,
        &mut messages,
        initial_tool_calls,
        &mut observer,
        MAX_AGENT_ITERATIONS,
    )
    .await;

    match loop_result {
        Ok(result) => {
            let total_tokens = initial_tokens + result.total_tokens;
            let total_tool_uses = result.tool_results.len();
            let final_response = if result.final_response.is_empty() {
                content
            } else {
                result.final_response
            };

            {
                let mut prog = progress.lock_mut_safe();
                if let Some(entry) = prog.get_mut(progress_index) {
                    entry.status = SubagentStatus::Completed;
                    entry.tokens = total_tokens;
                    entry.tool_uses = total_tool_uses;
                }
            }

            SubagentResult {
                id,
                description,
                response: final_response,
                tool_uses: total_tool_uses,
                tokens: total_tokens,
                duration_secs: started_at.elapsed().as_secs_f64(),
                success: !result.interrupted,
            }
        },
        Err(e) => {
            let error_msg = e.to_string();
            let (tool_uses, tokens) = {
                let prog = progress.lock_mut_safe();
                prog.get(progress_index)
                    .map(|p| (p.tool_uses, p.tokens))
                    .unwrap_or((0, initial_tokens))
            };

            {
                let mut prog = progress.lock_mut_safe();
                if let Some(entry) = prog.get_mut(progress_index) {
                    entry.status = SubagentStatus::Failed(error_msg.clone());
                }
            }

            SubagentResult {
                id,
                description,
                response: error_msg,
                tool_uses,
                tokens,
                duration_secs: started_at.elapsed().as_secs_f64(),
                success: false,
            }
        },
    }
}

/// Spawn multiple subagents in parallel.
///
/// Returns JoinHandles so the caller can decide how to wait:
/// - TUI: polls `is_finished()` with `render_and_check_interrupt` between checks
/// - Non-interactive: `join_all` directly
///
/// Agents beyond `MAX_CONCURRENT_AGENTS` are returned as immediate failed results.
pub fn spawn_subagents(
    agents: Vec<(String, String)>,
    model: Arc<RwLock<Box<dyn Model>>>,
    config: &ModelConfig,
    progress: Arc<Mutex<Vec<SubagentProgress>>>,
) -> (Vec<JoinHandle<SubagentResult>>, Vec<SubagentResult>) {
    let mut handles = Vec::new();
    let mut overflow_results = Vec::new();

    // Initialize progress entries
    {
        let mut prog = progress.lock_mut_safe();
        for (i, (_prompt, description)) in agents.iter().enumerate() {
            if i < MAX_CONCURRENT_AGENTS {
                prog.push(SubagentProgress {
                    id: i,
                    description: description.clone(),
                    status: SubagentStatus::Running,
                    tool_uses: 0,
                    tokens: 0,
                    started_at: Instant::now(),
                });
            }
        }
    }

    for (i, (prompt, description)) in agents.into_iter().enumerate() {
        if i >= MAX_CONCURRENT_AGENTS {
            warn!(
                "Exceeded MAX_CONCURRENT_AGENTS ({}), skipping agent: {}",
                MAX_CONCURRENT_AGENTS, description
            );
            overflow_results.push(SubagentResult {
                id: i,
                description,
                response: format!(
                    "Exceeded maximum of {} concurrent agents. This agent was not spawned.",
                    MAX_CONCURRENT_AGENTS
                ),
                tool_uses: 0,
                tokens: 0,
                duration_secs: 0.0,
                success: false,
            });
            continue;
        }

        // Build subagent-specific config. Subagents skip reasoning to
        // keep them fast and focused — the orchestrating turn already
        // did the planning.
        let mut subagent_config = config.clone();
        subagent_config.is_subagent = true;
        subagent_config.reasoning = ReasoningLevel::None;

        let model_clone = Arc::clone(&model);
        let progress_clone = Arc::clone(&progress);

        info!(agent_id = i, description = %description, "Spawning subagent");

        let handle = tokio::spawn(async move {
            run_subagent(
                model_clone,
                subagent_config,
                i,
                prompt,
                description,
                progress_clone,
                i,
            )
            .await
        });

        handles.push(handle);
    }

    (handles, overflow_results)
}

/// Collect results from completed subagent handles.
/// Handles panicked/cancelled tasks gracefully.
pub async fn collect_subagent_results(
    handles: Vec<JoinHandle<SubagentResult>>,
    mut overflow_results: Vec<SubagentResult>,
) -> Vec<SubagentResult> {
    let mut results = Vec::with_capacity(handles.len() + overflow_results.len());

    for (i, handle) in handles.into_iter().enumerate() {
        match handle.await {
            Ok(result) => results.push(result),
            Err(e) => {
                warn!("Subagent task failed: {}", e);
                results.push(SubagentResult {
                    id: i,
                    description: "Unknown".to_string(),
                    response: format!("Agent task failed: {}", e),
                    tool_uses: 0,
                    tokens: 0,
                    duration_secs: 0.0,
                    success: false,
                });
            },
        }
    }

    results.append(&mut overflow_results);
    results.sort_by_key(|r| r.id);
    results
}

/// Format a SubagentResult into a tool result message string for the parent model.
pub fn format_subagent_tool_result(result: &SubagentResult) -> String {
    if result.success {
        format!(
            "Agent '{}' completed successfully ({} tool uses, {} tokens, {:.1}s):\n\n{}",
            result.description,
            result.tool_uses,
            result.tokens,
            result.duration_secs,
            result.response
        )
    } else {
        format!(
            "Agent '{}' failed: {} ({} tool uses, {} tokens, {:.1}s)",
            result.description,
            result.response,
            result.tool_uses,
            result.tokens,
            result.duration_secs
        )
    }
}