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
// Copyright (c) 2026 100monkeys.ai
// SPDX-License-Identifier: AGPL-3.0
//! Node command implementations for AEGIS CLI
//!
//! # Architecture
//!
//! - **Layer:** Interface / Presentation Layer
//! - **Purpose:** Implements node-related commands (clustering, registration)

use anyhow::{Context, Result};
use clap::Subcommand;
use colored::Colorize;
use ed25519_dalek::{Signer, SigningKey};
use rand::rngs::OsRng;
use serde::Serialize;
use std::fs;
use std::path::PathBuf;
use tonic::Request;

use crate::output::{render_serialized, OutputFormat};
use aegis_orchestrator_core::domain::node_config::NodeConfigManifest;
use aegis_orchestrator_core::infrastructure::aegis_cluster_proto::{
    node_cluster_service_client::NodeClusterServiceClient, AttestNodeRequest, ChallengeNodeRequest,
    ListPeersRequest, NodeCapabilities, NodeRole,
};

#[derive(Subcommand)]
pub enum NodeCommand {
    /// Generates Ed25519 keypairs for node identity
    Init {
        /// Use development defaults
        #[arg(long)]
        dev: bool,
    },
    /// Runs the two-step attestation/registration handshake with a controller
    Join {
        /// Controller gRPC endpoint (e.g., https://controller:50056)
        endpoint: String,
    },
    /// Graceful deregistration from the cluster
    Leave,
    /// Queries the controller for the list of registered cluster peers
    Peers,
}

pub async fn handle_command(
    command: NodeCommand,
    config_path: Option<PathBuf>,
    _host: &str,
    _port: u16,
    output_format: OutputFormat,
) -> Result<()> {
    let config = NodeConfigManifest::load_or_default(config_path)?;

    match command {
        NodeCommand::Init { dev: _ } => init_node(&config, output_format).await,
        NodeCommand::Join { endpoint } => join_cluster(&config, endpoint, output_format).await,
        NodeCommand::Peers => list_peers(&config, output_format).await,
        NodeCommand::Leave => {
            anyhow::bail!("Node leave is unavailable in the single-node baseline protocol")
        }
    }
}

#[derive(Serialize)]
struct NodeInitOutput {
    created: bool,
    path: String,
}

#[derive(Serialize)]
struct NodeJoinOutput {
    endpoint: String,
    node_id: String,
    token_issued: bool,
}

#[derive(Serialize)]
struct NodePeerOutput {
    node_id: String,
    role: String,
    status: String,
    grpc_address: String,
}

#[derive(Serialize)]
struct NodePeersOutput {
    controller_endpoint: String,
    peers: Vec<NodePeerOutput>,
}

async fn init_node(config: &NodeConfigManifest, output_format: OutputFormat) -> Result<()> {
    let path = config
        .spec
        .cluster
        .as_ref()
        .map(|c| c.node_keypair_path.clone())
        .unwrap_or_else(|| PathBuf::from("~/.aegis/node_keypair.pem"));

    // Resolve home directory if needed
    let path = if path.to_string_lossy().starts_with('~') {
        if let Some(home) = dirs_next::home_dir() {
            home.join(
                path.to_string_lossy()
                    .trim_start_matches("~/")
                    .trim_start_matches('~'),
            )
        } else {
            path
        }
    } else {
        path
    };

    if path.exists() {
        if output_format.is_structured() {
            return render_serialized(
                output_format,
                &NodeInitOutput {
                    created: false,
                    path: path.display().to_string(),
                },
            );
        }
        println!(
            "{} Node identity keypair already exists at {}",
            "".blue(),
            path.display().to_string().cyan()
        );
        return Ok(());
    }

    let mut csprng = OsRng;
    let signing_key = SigningKey::generate(&mut csprng);
    let bytes = signing_key.to_bytes();

    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&path, bytes).context("Failed to write node keypair")?;

    if output_format.is_structured() {
        return render_serialized(
            output_format,
            &NodeInitOutput {
                created: true,
                path: path.display().to_string(),
            },
        );
    }

    println!(
        "{} Generated new node identity keypair at {}",
        "".green(),
        path.display().to_string().cyan()
    );
    Ok(())
}

async fn join_cluster(
    config: &NodeConfigManifest,
    endpoint: String,
    output_format: OutputFormat,
) -> Result<()> {
    if !output_format.is_structured() {
        println!(
            "{} Attempting to join cluster at {}...",
            "".yellow(),
            endpoint.cyan()
        );
    }

    let mut client = NodeClusterServiceClient::connect(endpoint.clone())
        .await
        .context("Failed to connect to cluster controller")?;

    // Load Identity Keypair
    let key_path = config
        .spec
        .cluster
        .as_ref()
        .map(|c| &c.node_keypair_path)
        .context("Cluster configuration (spec.cluster) is missing in aegis-config.yaml")?;

    // Resolve home directory if needed
    let key_path = if key_path.to_string_lossy().starts_with('~') {
        if let Some(home) = dirs_next::home_dir() {
            home.join(
                key_path
                    .to_string_lossy()
                    .trim_start_matches("~/")
                    .trim_start_matches('~'),
            )
        } else {
            key_path.clone()
        }
    } else {
        key_path.clone()
    };

    let key_bytes = fs::read(&key_path).context(format!(
        "Failed to read node identity keypair at {}. Run 'aegis node init' first.",
        key_path.display()
    ))?;

    let signing_key = SigningKey::from_bytes(
        key_bytes
            .as_slice()
            .try_into()
            .map_err(|_| anyhow::anyhow!("Invalid keypair format"))?,
    );

    // 1. Step 1: AttestNode (Identity Presentation)
    let attest_req = AttestNodeRequest {
        node_id: config.spec.node.id.clone(),
        role: match config
            .spec
            .cluster
            .as_ref()
            .map(|c| c.role)
            .unwrap_or_default()
        {
            aegis_orchestrator_core::domain::node_config::NodeRole::Controller => {
                NodeRole::Controller.into()
            }
            aegis_orchestrator_core::domain::node_config::NodeRole::Worker => {
                NodeRole::Worker.into()
            }
            aegis_orchestrator_core::domain::node_config::NodeRole::Hybrid => {
                NodeRole::Hybrid.into()
            }
        },
        public_key: signing_key.verifying_key().to_bytes().to_vec(),
        capabilities: Some(NodeCapabilities {
            gpu_count: config
                .spec
                .node
                .resources
                .as_ref()
                .map(|r| r.gpu_count)
                .unwrap_or(0),
            vram_gb: config
                .spec
                .node
                .resources
                .as_ref()
                .map(|r| r.vram_gb)
                .unwrap_or(0),
            cpu_cores: config
                .spec
                .node
                .resources
                .as_ref()
                .map(|r| r.cpu_cores)
                .unwrap_or(0),
            available_memory_gb: config
                .spec
                .node
                .resources
                .as_ref()
                .map(|r| r.memory_gb)
                .unwrap_or(0),
            supported_runtimes: vec!["docker".to_string()], // Single-node baseline runtime
            tags: config.spec.node.tags.clone(),
        }),
        grpc_address: config
            .spec
            .network
            .as_ref()
            .map(|n| format!("localhost:{}", n.grpc_port))
            .unwrap_or_else(|| "localhost:50051".to_string()),
    };

    if !output_format.is_structured() {
        println!("{} Sending AttestNodeRequest (Step 1)...", "".blue());
    }
    let attest_resp = client
        .attest_node(Request::new(attest_req))
        .await
        .context("Attestation failed at Step 1 (AttestNode)")?
        .into_inner();

    // 2. Step 2: ChallengeNode (Proof of Possession)
    if !output_format.is_structured() {
        println!("{} Solving challenge nonce (Step 2)...", "".blue());
    }
    let signature = signing_key.sign(&attest_resp.challenge_nonce);
    let challenge_req = ChallengeNodeRequest {
        challenge_id: attest_resp.challenge_id,
        node_id: config.spec.node.id.clone(),
        challenge_signature: signature.to_bytes().to_vec(),
    };

    let _challenge_resp = client
        .challenge_node(Request::new(challenge_req))
        .await
        .context("Attestation failed at Step 2 (ChallengeNode)")?
        .into_inner();

    if output_format.is_structured() {
        return render_serialized(
            output_format,
            &NodeJoinOutput {
                endpoint,
                node_id: config.spec.node.id.clone(),
                token_issued: true,
            },
        );
    }

    println!("{} Successfully joined cluster!", "".green());
    println!("{} NodeSecurityToken issued (expires in 1h)", "".blue());

    // Persisting or forwarding the issued token belongs to the daemon/runtime
    // integration path. This CLI command stops after the registration handshake.

    Ok(())
}

async fn list_peers(config: &NodeConfigManifest, output_format: OutputFormat) -> Result<()> {
    let cluster_config = config
        .spec
        .cluster
        .as_ref()
        .context("Cluster configuration (spec.cluster) is missing in aegis-config.yaml")?;

    let endpoint = cluster_config
        .controller
        .as_ref()
        .map(|c| c.endpoint.clone())
        .context("Controller endpoint not configured in spec.cluster.controller.endpoint")?;

    if !output_format.is_structured() {
        println!(
            "{} Querying cluster peers from {}...",
            "".yellow(),
            endpoint.cyan()
        );
    }

    let mut client = NodeClusterServiceClient::connect(endpoint.clone())
        .await
        .context("Failed to connect to cluster controller")?;

    let resp = client
        .list_peers(Request::new(ListPeersRequest::default()))
        .await
        .context("Failed to list peers")?
        .into_inner();

    let peers = resp
        .nodes
        .into_iter()
        .map(|node| {
            let role = format!("{:?}", node.role());
            let status = format!("{:?}", node.status()).to_ascii_lowercase();
            let node_id = node.node_id;
            let grpc_address = node.grpc_address;
            NodePeerOutput {
                node_id,
                role,
                status,
                grpc_address,
            }
        })
        .collect::<Vec<_>>();

    if output_format.is_structured() {
        return render_serialized(
            output_format,
            &NodePeersOutput {
                controller_endpoint: endpoint,
                peers,
            },
        );
    }

    println!(
        "\n{:<36} {:<12} {:<10} {:<15}",
        "NODE ID".bold(),
        "ROLE".bold(),
        "STATUS".bold(),
        "GRPC ADDRESS".bold()
    );
    println!("{}", "-".repeat(85));

    for node in peers {
        let status_color = match node.status.as_str() {
            "active" => "green",
            "draining" => "yellow",
            "unhealthy" => "red",
            _ => "white",
        };

        println!(
            "{:<36} {:<12} {:<10} {:<15}",
            node.node_id.dimmed(),
            node.role,
            node.status.color(status_color),
            node.grpc_address.cyan()
        );
    }
    println!();

    Ok(())
}