aegis-orchestrator 0.15.0-pre-alpha

100monkeys.ai AEGIS orchestrator CLI and daemon
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
// Copyright (c) 2026 100monkeys.ai
// SPDX-License-Identifier: AGPL-3.0
//! Agent
//!
//! Provides agent functionality for the system.
//! Includes list/deploy/show/remove/logs and generate operations.
//!
//! # Architecture
//!
//! - **Layer:** Interface / Presentation Layer
//! - **Purpose:** Implements agent

use anyhow::{Context, Result};
use clap::Subcommand;
use colored::Colorize;
use serde::Serialize;
use std::path::PathBuf;
use uuid::Uuid;

use crate::commands::builtins;
use crate::daemon::{check_daemon_running, DaemonClient, DaemonStatus};
use crate::output::{render_serialized, structured_output_unsupported, OutputFormat};

const AGENT_GENERATOR_NAME: &str = builtins::AGENT_GENERATOR_AGENT_NAME;

#[derive(Subcommand)]
pub enum AgentCommand {
    /// List deployed agents
    List,

    /// Deploy an agent from manifest file
    Deploy {
        /// Path to agent manifest YAML file
        #[arg(value_name = "MANIFEST")]
        manifest: PathBuf,

        /// Validate manifest without deploying
        #[arg(long)]
        validate_only: bool,

        /// Overwrite an existing agent that has the same name and version.
        /// Without this flag the command fails if an agent with the same name
        /// and version is already deployed.
        #[arg(long)]
        force: bool,
    },

    /// Show agent configuration (YAML)
    Show {
        /// Agent ID
        #[arg(value_name = "AGENT_ID")]
        agent_id: Uuid,
    },

    /// Remove a deployed agent
    Remove {
        /// Agent ID
        #[arg(value_name = "AGENT_ID")]
        agent_id: Uuid,
    },

    /// Stream logs for an agent
    Logs {
        /// Agent ID or Name
        #[arg(value_name = "AGENT_ID")]
        agent_id: String,

        /// Follow log output
        #[arg(short, long)]
        follow: bool,

        /// Show errors only
        #[arg(short, long)]
        errors: bool,

        /// Show verbose output (e.g. LLM prompts)
        #[arg(short, long)]
        verbose: bool,
    },

    /// Execute an agent directly
    Run {
        /// Agent UUID or name
        #[arg(value_name = "AGENT")]
        agent: String,

        /// Natural-language steering for this execution
        #[arg(long, value_name = "TEXT")]
        intent: Option<String>,

        /// Structured input (JSON string)
        #[arg(long, short = 'i', value_name = "JSON")]
        input: Option<String>,

        /// Individual parameters (key=value)
        #[arg(long = "param", short = 'p', value_name = "KEY=VALUE")]
        params: Vec<String>,

        /// Target a specific agent version
        #[arg(long, value_name = "VERSION")]
        version: Option<String>,

        /// Follow execution logs
        #[arg(long, short = 'f')]
        follow: bool,

        /// Wait for completion
        #[arg(long, short = 'w')]
        wait: bool,
    },

    /// Generate an agent from natural-language input
    Generate {
        /// Natural-language intent for the agent to create
        #[arg(long, short = 'i', value_name = "INPUT")]
        input: String,

        /// Follow generator execution logs
        #[arg(short, long)]
        follow: bool,
    },
}

pub async fn handle_command(
    command: AgentCommand,
    config_path: Option<PathBuf>,
    host: &str,
    port: u16,
    output_format: OutputFormat,
) -> Result<()> {
    // Agents are currently managed via the daemon.
    // Embedded mode may later support direct repository access.

    let daemon_status = check_daemon_running(host, port).await;
    match daemon_status {
        Ok(DaemonStatus::Running { .. }) => {}
        Ok(DaemonStatus::Unhealthy { pid, error }) => {
            println!(
                "{}",
                format!("⚠ Daemon is running (PID: {pid}) but unhealthy: {error}").yellow()
            );
            println!("Run 'aegis daemon status' for more info.");
            return Ok(());
        }
        _ => {
            println!(
                "{}",
                "Agent management requires the daemon to be running.".red()
            );
            println!("Run 'aegis daemon start' to start the daemon.");
            return Ok(());
        }
    }

    let auth_key = crate::auth::require_key().await?;
    let client = DaemonClient::new(host, port)?.with_auth(auth_key);

    match command {
        AgentCommand::List => list_agents(client, output_format).await,
        AgentCommand::Deploy {
            manifest,
            validate_only,
            force,
        } => deploy_agent(manifest, validate_only, force, client, output_format).await,
        AgentCommand::Show { agent_id } => show_agent(agent_id, client, output_format).await,
        AgentCommand::Remove { agent_id } => remove_agent(agent_id, client, output_format).await,
        AgentCommand::Logs {
            agent_id,
            follow,
            errors,
            verbose,
        } => {
            if output_format.is_structured() {
                structured_output_unsupported("aegis agent logs", output_format)
            } else {
                logs_agent(agent_id, follow, errors, verbose, client).await
            }
        }
        AgentCommand::Run {
            agent,
            intent,
            input,
            params,
            version,
            follow,
            wait,
        } => {
            run_agent(
                agent,
                intent,
                input,
                params,
                version,
                follow,
                wait,
                client,
                output_format,
            )
            .await
        }
        AgentCommand::Generate { input, follow } => {
            generate_agent(input, follow, client, config_path.as_ref(), output_format).await
        }
    }
}

#[derive(Serialize)]
struct AgentListOutput {
    count: usize,
    agents: Vec<crate::daemon::client::AgentInfo>,
}

#[derive(Serialize)]
struct AgentDeployOutput {
    #[serde(skip_serializing_if = "Option::is_none")]
    agent_id: Option<Uuid>,
    name: String,
    version: String,
    validate_only: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    runtime: Option<String>,
}

#[derive(Serialize)]
struct AgentMutationOutput {
    agent_id: Uuid,
    status: &'static str,
}

#[derive(Serialize)]
struct AgentGenerateOutput {
    generator_agent_id: Uuid,
    execution_id: Uuid,
    follow: bool,
    generated_agents_root: String,
}

async fn show_agent(
    agent_id: Uuid,
    client: DaemonClient,
    output_format: OutputFormat,
) -> Result<()> {
    let manifest = client.get_agent(agent_id).await?;

    if output_format.is_structured() {
        return render_serialized(output_format, &manifest);
    }

    let yaml = serde_yaml::to_string(&manifest).context("Failed to serialize manifest to YAML")?;
    print!("{yaml}");

    Ok(())
}

async fn list_agents(client: DaemonClient, output_format: OutputFormat) -> Result<()> {
    let agents = client.list_agents().await?;

    if output_format.is_structured() {
        return render_serialized(
            output_format,
            &AgentListOutput {
                count: agents.len(),
                agents,
            },
        );
    }

    if agents.is_empty() {
        println!("{}", "No agents found".yellow());
        return Ok(());
    }

    println!("{} agents found:", agents.len());
    println!("{:<38} {:<20} {:<10} STATUS", "ID", "NAME", "VERSION");

    for agent in agents {
        println!(
            "{:<38} {:<20} {:<10} {}",
            agent.id,
            agent.name.bold(),
            agent.version,
            agent.status
        );
    }

    Ok(())
}

async fn remove_agent(
    agent_id: Uuid,
    client: DaemonClient,
    output_format: OutputFormat,
) -> Result<()> {
    client.delete_agent(agent_id).await?;
    if output_format.is_structured() {
        return render_serialized(
            output_format,
            &AgentMutationOutput {
                agent_id,
                status: "removed",
            },
        );
    }
    println!("{}", format!("✓ Agent {agent_id} removed").green());
    Ok(())
}

async fn deploy_agent(
    manifest: PathBuf,
    validate_only: bool,
    force: bool,
    client: DaemonClient,
    output_format: OutputFormat,
) -> Result<()> {
    let manifest_content = tokio::fs::read_to_string(&manifest)
        .await
        .with_context(|| format!("Failed to read manifest: {manifest:?}"))?;

    // Parse with SDK types (now using core domain re-exports)
    let agent_manifest: aegis_orchestrator_sdk::AgentManifest =
        serde_yaml::from_str(&manifest_content).context("Failed to parse manifest YAML")?;

    // Use domain validation (comprehensive checks including DNS labels, timeouts, etc.)
    agent_manifest
        .validate()
        .map_err(|e| anyhow::anyhow!("Manifest validation failed: {e}"))?;

    if validate_only {
        let runtime = format!(
            "{}:{}",
            agent_manifest
                .spec
                .runtime
                .language
                .as_deref()
                .unwrap_or("unknown"),
            agent_manifest
                .spec
                .runtime
                .version
                .as_deref()
                .unwrap_or("unknown")
        );
        if output_format.is_structured() {
            return render_serialized(
                output_format,
                &AgentDeployOutput {
                    agent_id: None,
                    name: agent_manifest.metadata.name.clone(),
                    version: agent_manifest.metadata.version.clone(),
                    validate_only: true,
                    runtime: Some(runtime.clone()),
                },
            );
        }

        println!(
            "{}",
            format!("✓ Manifest is valid: {}", agent_manifest.metadata.name).green()
        );
        println!("  API Version: {}", agent_manifest.api_version);
        println!("  Kind: {}", agent_manifest.kind);
        println!("  Name: {}", agent_manifest.metadata.name);
        println!("  Version: {}", agent_manifest.metadata.version);
        println!("  Runtime: {runtime}");
        return Ok(());
    }

    if !output_format.is_structured() {
        println!("Deploying agent: {}", agent_manifest.metadata.name.bold());
    }

    let name = agent_manifest.metadata.name.clone();
    let version = agent_manifest.metadata.version.clone();
    let runtime = Some(format!(
        "{}:{}",
        agent_manifest
            .spec
            .runtime
            .language
            .as_deref()
            .unwrap_or("unknown"),
        agent_manifest
            .spec
            .runtime
            .version
            .as_deref()
            .unwrap_or("unknown")
    ));
    let agent_id = client.deploy_agent(agent_manifest, force, None).await?;

    if output_format.is_structured() {
        return render_serialized(
            output_format,
            &AgentDeployOutput {
                agent_id: Some(agent_id),
                name,
                version,
                validate_only: false,
                runtime,
            },
        );
    }

    println!("{}", format!("✓ Agent deployed: {agent_id}").green());

    Ok(())
}

async fn logs_agent(
    agent_id_str: String,
    follow: bool,
    errors_only: bool,
    verbose: bool,
    client: DaemonClient,
) -> Result<()> {
    // Resolve ID if it's a name
    let agent_id = if let Ok(uuid) = Uuid::parse_str(&agent_id_str) {
        uuid
    } else {
        // Look up by name
        println!(
            "{}",
            format!("Looking up agent '{agent_id_str}'...").dimmed()
        );
        match client.lookup_agent(&agent_id_str).await? {
            Some(id) => id,
            None => {
                anyhow::bail!("Agent '{agent_id_str}' not found");
            }
        }
    };

    println!(
        "{}",
        format!("Streaming logs for agent {agent_id}...").dimmed()
    );
    client
        .stream_agent_logs(agent_id, follow, errors_only, verbose)
        .await?;

    Ok(())
}

/// Output struct for structured `agent run` results.
#[derive(Serialize)]
struct AgentRunOutput {
    agent_id: Uuid,
    execution_id: Uuid,
    intent: Option<String>,
    follow: bool,
    wait: bool,
}

#[allow(clippy::too_many_arguments)]
async fn run_agent(
    agent: String,
    intent: Option<String>,
    input_json: Option<String>,
    params: Vec<String>,
    version: Option<String>,
    follow: bool,
    wait: bool,
    client: DaemonClient,
    output_format: OutputFormat,
) -> Result<()> {
    if output_format.is_structured() && follow {
        return structured_output_unsupported("aegis agent run --follow", output_format);
    }

    // Parse structured input
    let mut input_map = serde_json::Map::new();
    if let Some(json_str) = input_json {
        let parsed: serde_json::Value = serde_json::from_str(&json_str)
            .or_else(|_| serde_yaml::from_str(&json_str))
            .context("--input must be valid JSON or YAML")?;
        if let Some(obj) = parsed.as_object() {
            input_map.extend(obj.clone());
        } else {
            anyhow::bail!("Agent --input must be a JSON object");
        }
    }
    for param in params {
        let parts: Vec<&str> = param.splitn(2, '=').collect();
        if parts.len() != 2 {
            anyhow::bail!("Invalid --param format: '{param}'. Expected 'key=value'");
        }
        let key = parts[0].to_string();
        let value = parts[1].to_string();
        let json_value = serde_json::from_str(&value).unwrap_or(serde_json::Value::String(value));
        input_map.insert(key, json_value);
    }

    // Resolve agent UUID: parse directly if UUID, else look up by name
    let agent_id = if let Ok(uuid) = Uuid::parse_str(&agent) {
        uuid
    } else {
        match client.lookup_agent(&agent).await? {
            Some(id) => id,
            None => anyhow::bail!("Agent '{agent}' not found"),
        }
    };

    if !output_format.is_structured() {
        println!("{}", "🚀 Starting agent execution...".cyan());
        println!("   Agent: {agent_id}");
        if let Some(ref i) = intent {
            println!("   Intent: {i}");
        }
        if !input_map.is_empty() {
            println!("   Input: {}", serde_json::to_string(&input_map).unwrap());
        }
        println!();
    }

    let execution_id = client
        .execute_agent(
            agent_id,
            serde_json::Value::Object(input_map),
            intent.clone(),
            None,
            version.as_deref(),
        )
        .await
        .context("Failed to start agent execution")?;

    if output_format.is_structured() {
        return render_serialized(
            output_format,
            &AgentRunOutput {
                agent_id,
                execution_id,
                intent,
                follow,
                wait,
            },
        );
    }

    println!(
        "{}",
        format!("✓ Agent execution started: {execution_id}").green()
    );

    if follow {
        println!("{}", "📡 Streaming logs...".cyan());
        println!();
        client
            .stream_logs(execution_id, true, false, false)
            .await
            .context("Failed to stream agent logs")?;
    } else if wait {
        println!("Waiting for completion...");
        loop {
            tokio::time::sleep(std::time::Duration::from_secs(2)).await;
            match client.get_execution(execution_id).await {
                Ok(info) => match info.status.as_str() {
                    "completed" | "succeeded" => {
                        println!(
                            "{}",
                            format!("✓ Execution {execution_id} completed").green()
                        );
                        break;
                    }
                    "failed" | "error" => {
                        println!("{}", format!("✗ Execution {execution_id} failed").red());
                        break;
                    }
                    _ => {}
                },
                Err(e) => {
                    println!(
                        "{}",
                        format!("Warning: failed to poll execution: {e}").yellow()
                    );
                }
            }
        }
    } else {
        println!("Follow agent logs with:\n  aegis agent logs {execution_id} --follow");
    }

    Ok(())
}

async fn generate_agent(
    input: String,
    follow: bool,
    client: DaemonClient,
    config_path: Option<&PathBuf>,
    output_format: OutputFormat,
) -> Result<()> {
    let templates_root = builtins::resolve_templates_root(config_path);
    let generated_root = builtins::resolve_generated_root(config_path).join("agents");
    builtins::sync_generator_templates_to_disk(&templates_root)?;

    // Ensure built-ins are deployed (but don't force overwrite unless it's an update)
    builtins::deploy_all_builtins(&client, false).await?;

    if output_format.is_structured() && follow {
        return structured_output_unsupported("aegis agent generate --follow", output_format);
    }

    let generator_id = client
        .lookup_agent(AGENT_GENERATOR_NAME)
        .await?
        .context("Generator agent not found even after deployment attempt")?;

    if !output_format.is_structured() {
        println!(
            "{}",
            format!("Generating agent via '{AGENT_GENERATOR_NAME}' (id: {generator_id})...").cyan()
        );
    }
    let execution_id = client
        .execute_agent(
            generator_id,
            serde_json::Value::String(input),
            None,
            None,
            None,
        )
        .await
        .context("Failed to start agent generation execution")?;

    if output_format.is_structured() {
        return render_serialized(
            output_format,
            &AgentGenerateOutput {
                generator_agent_id: generator_id,
                execution_id,
                follow,
                generated_agents_root: generated_root.display().to_string(),
            },
        );
    }

    println!(
        "{}",
        format!("✓ Agent generation execution started: {execution_id}").green()
    );
    println!("Generated manifests will be persisted under:");
    println!("  {}", generated_root.display());

    if follow {
        client.stream_logs(execution_id, true, false, false).await?;
    } else {
        println!("Follow generator agent logs with:\n  aegis agent logs {execution_id} --follow");
    }

    Ok(())
}