bzzz-cli 0.1.0

Bzzz CLI - Command line interface for Agent orchestration
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
//! Run command

use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};

use anyhow::{Context, Result};
use bzzz_core::{
    create_runtime,
    pattern::{execute_with_timeout, get_executor, PatternContext},
    AgentSpecParser, CancellationToken, ExecutionContext, Run, RunTarget, RuntimeKind,
    SwarmFileParser,
};
use tokio::sync::Mutex;

use crate::commands::output::{OutputFormat, RunOutput};
use crate::run_registry::RunState;

/// Adaptive runtime monitor for dynamic worker adjustment
pub struct AdaptiveMonitor {
    /// Start time of monitoring
    start_time: Instant,
    /// Number of workers being monitored
    worker_count: usize,
    /// Check interval in milliseconds
    check_interval_ms: u64,
    /// Metrics collected during execution
    metrics: Arc<Mutex<AdaptiveMetrics>>,
}

/// Metrics collected during adaptive execution
#[derive(Debug, Default)]
pub struct AdaptiveMetrics {
    /// Total checks performed
    checks_count: u64,
    /// Workers that completed successfully
    workers_completed: u64,
    /// Workers that failed
    workers_failed: u64,
    /// Average execution time per worker (ms)
    avg_worker_time_ms: u64,
    /// Peak concurrent workers observed
    peak_concurrent: usize,
}

impl AdaptiveMonitor {
    /// Create a new adaptive monitor
    pub fn new(worker_count: usize) -> Self {
        Self {
            start_time: Instant::now(),
            worker_count,
            check_interval_ms: 500, // Default check interval
            metrics: Arc::new(Mutex::new(AdaptiveMetrics::default())),
        }
    }

    /// Get the metrics (for external access if needed)
    #[allow(dead_code)]
    pub fn metrics(&self) -> Arc<Mutex<AdaptiveMetrics>> {
        self.metrics.clone()
    }

    /// Log monitoring status
    pub fn log_status(&self, format: OutputFormat) {
        if format == OutputFormat::Text {
            let elapsed = self.start_time.elapsed();
            println!(
                "  [Adaptive] {} workers, {}ms elapsed, checking every {}ms",
                self.worker_count,
                elapsed.as_millis(),
                self.check_interval_ms
            );
        }
    }

    /// Record a worker completion
    pub async fn record_completion(&self, success: bool, duration_ms: u64) {
        let mut metrics = self.metrics.lock().await;
        metrics.checks_count += 1;
        if success {
            metrics.workers_completed += 1;
        } else {
            metrics.workers_failed += 1;
        }
        // Update average worker time
        let total_time = metrics.avg_worker_time_ms * (metrics.workers_completed + metrics.workers_failed - 1) + duration_ms;
        metrics.avg_worker_time_ms = total_time / (metrics.workers_completed + metrics.workers_failed);
    }

    /// Record peak concurrent workers
    pub async fn record_concurrent(&self, count: usize) {
        let mut metrics = self.metrics.lock().await;
        if count > metrics.peak_concurrent {
            metrics.peak_concurrent = count;
        }
    }

    /// Print final report
    pub async fn print_report(&self, format: OutputFormat) {
        let metrics = self.metrics.lock().await;
        let elapsed = self.start_time.elapsed();

        if format == OutputFormat::Text {
            println!("  [Adaptive] Execution Summary:");
            println!("    Total time: {}ms", elapsed.as_millis());
            println!("    Checks performed: {}", metrics.checks_count);
            println!("    Workers completed: {}", metrics.workers_completed);
            println!("    Workers failed: {}", metrics.workers_failed);
            println!("    Avg worker time: {}ms", metrics.avg_worker_time_ms);
            println!("    Peak concurrent: {}", metrics.peak_concurrent);
        }
    }
}

pub async fn execute(
    file: PathBuf,
    background: bool,
    timeout_secs: Option<u64>,
    runtime: &str,
    input: Option<String>,
    output_format: OutputFormat,
    adaptive: bool,
) -> Result<()> {
    if output_format == OutputFormat::Text {
        println!("🚀 Running: {}", file.display());
        if adaptive {
            println!("  Mode: Adaptive runtime monitoring enabled");
        }
    }

    let input_value: Option<serde_json::Value> = match input {
        Some(s) => Some(
            serde_json::from_str(&s)
                .context("Failed to parse --input as JSON")?,
        ),
        None => None,
    };

    let cli_runtime_kind = match runtime {
        "docker" => RuntimeKind::Docker,
        "http" => RuntimeKind::Http,
        _ => RuntimeKind::Local,
    };

    let ext = file
        .extension()
        .map(|e| e.to_string_lossy().to_string())
        .unwrap_or_default();
    let _is_swarm = ext == "swarm" || ext == "yaml" || ext == "yml";

    if let Ok(swarm) = SwarmFileParser::from_yaml_file(&file) {
        let swarm_runtime_kind = swarm.runtime.unwrap_or(cli_runtime_kind);
        run_swarm(
            &file,
            swarm,
            background,
            timeout_secs,
            swarm_runtime_kind,
            input_value,
            output_format,
            adaptive,
        )
        .await
    } else if let Ok(spec) = AgentSpecParser::from_yaml_file(&file) {
        let spec_runtime_kind = cli_runtime_kind;
        run_agent(&file, spec, background, timeout_secs, spec_runtime_kind, output_format, adaptive).await
    } else {
        anyhow::bail!(
            "Failed to parse {} as SwarmFile or Agent Spec",
            file.display()
        )
    }
}

async fn run_agent(
    file: &std::path::Path,
    spec: bzzz_core::AgentSpec,
    background: bool,
    timeout_secs: Option<u64>,
    runtime_kind: RuntimeKind,
    output_format: OutputFormat,
    adaptive: bool,
) -> Result<()> {
    if output_format == OutputFormat::Text {
        println!("  Agent: {}", spec.id.as_str());
        println!("  Runtime: {:?}", runtime_kind);
    }

    // Create adaptive monitor if enabled
    let monitor = if adaptive {
        Some(AdaptiveMonitor::new(1))
    } else {
        None
    };

    let runtime = create_runtime(runtime_kind)?;
    let registry = crate::run_registry::RunRegistry::default();
    let ctx = runtime.create(&spec).await?;

    let mut run = Run::new(
        RunTarget::Agent {
            spec_path: file.to_path_buf(),
        },
        runtime_kind,
    );

    if let Some(secs) = timeout_secs {
        run = run.with_timeout(Duration::from_secs(secs));
    }

    let handle = if background {
        runtime.execute_background(&ctx, &run).await?
    } else {
        runtime.execute(&ctx, &run).await?
    };

    let pid = handle
        .runtime_handle
        .strip_prefix("pid:")
        .and_then(|s| s.parse::<u32>().ok());

    let run_state = RunState::new(
        handle.run_id.clone(),
        runtime_kind,
        file.to_path_buf(),
        std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
    )
    .with_pid_opt(pid);

    registry.register(&run_state)?;

    // Log adaptive status if enabled
    if let Some(ref m) = monitor {
        m.log_status(output_format);
    }

    if background {
        if output_format == OutputFormat::Json {
            let out = RunOutput {
                run_id: handle.run_id.as_str().to_string(),
                status: "Running".to_string(),
                output: None,
                error: None,
                duration_ms: 0,
                artifacts_count: 0,
            };
            println!("{}", serde_json::to_string(&out)?);
        } else {
            println!("  Run ID: {}", handle.run_id.as_str());
            println!("  Status: Running in background");
            println!(
                "  Use `bzzz status --id {}` to check progress",
                handle.run_id.as_str()
            );
        }
    } else {
        let start_time = Instant::now();
        let result = runtime.wait(&handle).await?;
        let duration_ms = start_time.elapsed().as_millis() as u64;

        registry.update_status(handle.run_id.as_str(), result.status)?;

        // Record completion in adaptive monitor
        if let Some(ref m) = monitor {
            m.record_completion(result.status == bzzz_core::RunStatus::Completed, duration_ms).await;
            m.print_report(output_format).await;
        }

        if output_format == OutputFormat::Json {
            let out = RunOutput {
                run_id: handle.run_id.as_str().to_string(),
                status: format!("{:?}", result.status),
                output: None,
                error: result.error.map(|e| format!("{:?}", e)),
                duration_ms: result.metrics.wall_time_ms,
                artifacts_count: result.artifacts.len(),
            };
            println!("{}", serde_json::to_string(&out)?);
        } else {
            println!("  Run ID: {}", handle.run_id.as_str());
            println!("  Status: {:?}", result.status);
            if let Some(error) = result.error {
                println!("  Error: {:?}", error);
            }
            println!("  Duration: {}ms", result.metrics.wall_time_ms);
        }
    }

    Ok(())
}

#[allow(clippy::too_many_arguments)]
async fn run_swarm(
    file: &std::path::Path,
    mut swarm: bzzz_core::SwarmFile,
    _background: bool,
    timeout_secs: Option<u64>,
    runtime_kind: RuntimeKind,
    input_value: Option<serde_json::Value>,
    output_format: OutputFormat,
    adaptive: bool,
) -> Result<()> {

    // Pre-check: simple tasks skip full orchestration
    if swarm.is_simple() {
        return run_simple_swarm(
            file,
            swarm,
            timeout_secs,
            runtime_kind,
            input_value,
            output_format,
            adaptive,
        )
        .await;
    }
    if output_format == OutputFormat::Text {
        println!("  Swarm: {}", swarm.id.as_str());
        println!("  Workers: {}", swarm.workers.len());
        println!("  Pattern: {}", swarm.flow.type_name());
        println!("  Runtime: {:?}", runtime_kind);
    }

    // Create adaptive monitor if enabled
    let monitor = if adaptive {
        let m = AdaptiveMonitor::new(swarm.workers.len());
        m.log_status(output_format);
        Some(m)
    } else {
        None
    };

    if let Some(secs) = timeout_secs {
        swarm = swarm.with_timeout(Duration::from_secs(secs));
    }

    let runtime = create_runtime(runtime_kind)?;
    let swarm_dir = file.parent().unwrap_or_else(|| std::path::Path::new("."));
    let runtime_ctx = ExecutionContext::new(format!("swarm-{}", swarm.id.as_str()), runtime_kind)
        .with_working_dir(swarm_dir.to_path_buf());

    let pattern_ctx = match input_value {
        Some(input) => PatternContext::with_input(swarm, runtime_ctx, input),
        None => PatternContext::new(swarm, runtime_ctx),
    };

    let executor = get_executor(&pattern_ctx.swarm.flow);
    let cancel = CancellationToken::new();

    if output_format == OutputFormat::Text {
        println!("  Executor: {}", executor.name());
    }

    // Record concurrent workers at start
    if let Some(ref m) = monitor {
        m.record_concurrent(pattern_ctx.swarm.workers.len()).await;
    }

    let result = execute_with_timeout(&*executor, &pattern_ctx, runtime, &cancel).await?;

    // Print adaptive report if enabled
    if let Some(ref m) = monitor {
        m.record_completion(result.status == bzzz_core::RunStatus::Completed, result.metrics.wall_time_ms).await;
        m.print_report(output_format).await;
    }

    if output_format == OutputFormat::Json {
        let out = RunOutput {
            run_id: result.run_id.as_str().to_string(),
            status: format!("{:?}", result.status),
            output: result.output,
            error: result.error.map(|e| format!("{:?}", e)),
            duration_ms: result.metrics.wall_time_ms,
            artifacts_count: result.artifacts.len(),
        };
        println!("{}", serde_json::to_string(&out)?);
    } else {
        println!("  Run ID: {}", result.run_id.as_str());
        println!("  Status: {:?}", result.status);

        if let Some(error) = result.error {
            println!("  Error: {:?}", error);
        }

        println!("  Duration: {}ms", result.metrics.wall_time_ms);

        if !result.artifacts.is_empty() {
            println!("  Artifacts: {} produced", result.artifacts.len());
        }

        if let Some(output) = result.output {
            println!("  Output:");
            println!("{}", serde_json::to_string_pretty(&output)?);
        }
    }

    Ok(())
}
/// Execute a simple swarm directly without full orchestration overhead.
///
/// Simple swarms have exactly one worker and a simple pattern.
/// This bypasses scope propagation and runs the worker directly.
#[allow(clippy::too_many_arguments)]
#[allow(dead_code)]
async fn run_simple_swarm(
    file: &std::path::Path,
    swarm: bzzz_core::SwarmFile,
    timeout_secs: Option<u64>,
    runtime_kind: RuntimeKind,
    input_value: Option<serde_json::Value>,
    output_format: OutputFormat,
    adaptive: bool,
) -> Result<()> {
    if output_format == OutputFormat::Text {
        println!("  Swarm: {} (simple task)", swarm.id.as_str());
        println!("  Worker: {}", swarm.workers[0].name);
        println!("  Runtime: {:?}", runtime_kind);
    }

    // Create adaptive monitor if enabled
    let monitor = if adaptive {
        let m = AdaptiveMonitor::new(1);
        m.log_status(output_format);
        Some(m)
    } else {
        None
    };

    // Apply timeout if specified
    let swarm = match timeout_secs {
        Some(secs) => swarm.with_timeout(Duration::from_secs(secs)),
        None => swarm,
    };

    let runtime = create_runtime(runtime_kind)?;
    let swarm_dir = file.parent().unwrap_or_else(|| std::path::Path::new("."));
    let runtime_ctx = ExecutionContext::new(format!("simple-{}", swarm.id.as_str()), runtime_kind)
        .with_working_dir(swarm_dir.to_path_buf());

    // Create minimal pattern context
    let pattern_ctx = match input_value {
        Some(input) => PatternContext::with_input(swarm, runtime_ctx, input),
        None => PatternContext::new(swarm, runtime_ctx),
    };

    let executor = get_executor(&pattern_ctx.swarm.flow);
    let cancel = CancellationToken::new();

    let start_time = Instant::now();
    let result = execute_with_timeout(&*executor, &pattern_ctx, runtime, &cancel).await?;
    let duration_ms = start_time.elapsed().as_millis() as u64;

    // Print adaptive report if enabled
    if let Some(ref m) = monitor {
        m.record_completion(result.status == bzzz_core::RunStatus::Completed, duration_ms).await;
        m.print_report(output_format).await;
    }

    if output_format == OutputFormat::Json {
        let out = RunOutput {
            run_id: result.run_id.as_str().to_string(),
            status: format!("{:?}", result.status),
            output: result.output,
            error: result.error.map(|e| format!("{:?}", e)),
            duration_ms: result.metrics.wall_time_ms,
            artifacts_count: result.artifacts.len(),
        };
        println!("{}", serde_json::to_string(&out)?);
    } else {
        println!("  Run ID: {}", result.run_id.as_str());
        println!("  Status: {:?}", result.status);

        if let Some(error) = result.error {
            println!("  Error: {:?}", error);
        }

        println!("  Duration: {}ms", result.metrics.wall_time_ms);

        if let Some(output) = result.output {
            println!("  Output:");
            println!("{}", serde_json::to_string_pretty(&output)?);
        }
    }

    Ok(())
}