anda_cli 0.14.5

The command line interface for Anda engine server.
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
//! Command-line client for interacting with Anda engine servers.
//!
//! The binary can generate random material, make signed RPC calls, run agents,
//! and call tools against an `anda_engine_server` endpoint.

use anda_core::{AgentInput, AgentOutput, BoxError, HttpFeatures, ToolInput, ToolOutput};
use anda_web3_client::client::{Client as Web3Client, load_identity};
use base64::{Engine, prelude::BASE64_URL_SAFE};
use cbor2::Value;
use clap::{Parser, Subcommand};
use ic_cose_types::cose::ed25519::{SigningKey, VerifyingKey};
use rand::Rng;
use std::sync::Arc;

#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
    #[clap(long, default_value = "https://icp-api.io")]
    host: String,

    /// Path to ICP identity pem file or 32 bytes identity secret in hex.
    #[arg(long, env = "ID_SECRET", default_value = "Anonymous")]
    id: String,

    /// Allow plain `http://` endpoints on non-loopback hosts.
    ///
    /// Requests are signed with your identity, so over plain HTTP both the payload and the
    /// authorization envelope are readable — and replayable — by anyone on the path. Loopback
    /// endpoints are allowed without this flag so local development works out of the box.
    #[arg(long, global = true)]
    allow_http: bool,

    #[command(subcommand)]
    command: Option<Commands>,
}

/// Whether the client may use plain HTTP for `endpoint`.
///
/// Defaults to loopback-only: the built-in endpoint default is `http://127.0.0.1:8042`, so
/// local use needs no flag, while a remote `http://` target requires opting in explicitly
/// rather than silently transmitting a signed envelope in the clear.
fn allow_http_for(endpoint: &str, forced: bool) -> bool {
    if forced {
        return true;
    }

    // Only the `http` scheme needs a decision; anything else is left to the client's own
    // scheme validation.
    let Some(rest) = endpoint.strip_prefix("http://") else {
        return false;
    };

    // Authority runs up to the first `/`, `?`, or `#`; drop any userinfo and port.
    let authority = rest
        .split(['/', '?', '#'])
        .next()
        .unwrap_or_default()
        .rsplit('@')
        .next()
        .unwrap_or_default();
    let host = match authority.strip_prefix('[') {
        // IPv6 literal: `[::1]:8042`.
        Some(v6) => v6.split(']').next().unwrap_or_default(),
        None => authority.split(':').next().unwrap_or_default(),
    };

    host.eq_ignore_ascii_case("localhost")
        || host == "::1"
        || host
            .parse::<std::net::IpAddr>()
            .is_ok_and(|ip| ip.is_loopback())
}

/// CLI subcommands supported by `anda`.
#[derive(Subcommand)]
pub enum Commands {
    /// Generate random bytes with the given length and format
    RandBytes {
        /// Length of the random bytes, default is 32
        #[arg(short, long, default_value = "32")]
        len: usize,
        /// Output format: hex or base64, default is hex
        #[arg(short, long, default_value = "hex")]
        format: String,

        /// Whether to generate an ed25519 key pair, if true, the len will be ignored.
        #[arg(long)]
        ed25519: bool,
    },

    /// make an signed RPC call to the endpoint with the given ICP identity, method and args.
    /// The RPC response from the endpoint should be string.
    /// Example: `anda_engine_cli rpc -i ./identity.pem -e 'https://andaicp.anda.bot/proposal'  -m start_x_bot`
    Rpc {
        /// Signed RPC endpoint URL.
        #[arg(short, long, default_value = "http://127.0.0.1:8042/default")]
        endpoint: String,

        /// RPC method name
        #[arg(short, long)]
        method: String,

        /// RPC arguments in JSON string, default is [], means no arguments.
        #[arg(short, long, default_value = "[]")]
        data: String,
    },

    /// Run an AI agent with the given prompt and name on the endpoint.
    AgentRun {
        /// Engine endpoint URL.
        #[arg(short, long, default_value = "http://127.0.0.1:8042/default")]
        endpoint: String,

        /// Prompt to send to the agent.
        #[arg(short, long)]
        prompt: String,

        /// Optional agent name. Empty means the server default.
        #[arg(short, long)]
        name: Option<String>,
    },

    /// Call a tool with the given name and args on the endpoint.
    ToolCall {
        /// Engine endpoint URL.
        #[arg(short, long, default_value = "http://127.0.0.1:8042/default")]
        endpoint: String,

        /// Tool name to call.
        #[arg(short, long)]
        name: String,

        /// Tool arguments as a JSON string.
        #[arg(short, long)]
        args: String,
    },
}

fn normalize_rpc_data(data: &str) -> Result<serde_json::Value, serde_json::Error> {
    let args: serde_json::Value = serde_json::from_str(data)?;
    Ok(if args.is_array() {
        args
    } else {
        serde_json::json!(vec![args])
    })
}

fn agent_input(name: &Option<String>, prompt: &str) -> AgentInput {
    AgentInput {
        name: name.clone().unwrap_or_default(),
        prompt: prompt.to_string(),
        ..Default::default()
    }
}

fn tool_input(name: &str, args: &str) -> Result<ToolInput<serde_json::Value>, serde_json::Error> {
    Ok(ToolInput {
        name: name.to_string(),
        args: serde_json::from_str(args)?,
        ..Default::default()
    })
}

fn bounded_rand_len(len: usize) -> usize {
    len.min(1024)
}

fn format_bytes(bytes: &[u8], format: &str) -> String {
    match format {
        "hex" => hex::encode(bytes),
        "base64" => BASE64_URL_SAFE.encode(bytes),
        _ => format!("{bytes:?}"),
    }
}

fn format_ed25519_key_pair(bytes: [u8; 32], format: &str) -> (String, String) {
    let signing_key = SigningKey::from_bytes(&bytes);
    let verifying_key = VerifyingKey::from(&signing_key);
    match format {
        "hex" => (hex::encode(bytes), hex::encode(verifying_key.to_bytes())),
        _ => (
            BASE64_URL_SAFE.encode(bytes),
            BASE64_URL_SAFE.encode(verifying_key.to_bytes()),
        ),
    }
}

#[tokio::main]
async fn main() -> Result<(), BoxError> {
    dotenv::dotenv().ok();
    let cli = Cli::parse();
    let identity = load_identity(&cli.id)?;
    println!("principal: {}", identity.sender()?);

    match &cli.command {
        Some(Commands::RandBytes {
            len,
            format,
            ed25519,
        }) => {
            let mut rng = rand::rng();

            if *ed25519 {
                let mut bytes = [0u8; 32];
                rng.fill_bytes(&mut bytes);
                let (secret_key, public_key) = format_ed25519_key_pair(bytes, format);
                println!("Secret Key: {secret_key}");
                println!("Public Key: {public_key}");
            } else {
                let mut bytes = vec![0u8; bounded_rand_len(*len)];
                rng.fill_bytes(&mut bytes);
                println!("{}", format_bytes(&bytes, format));
            }
        }

        Some(Commands::Rpc {
            endpoint,
            method,
            data,
        }) => {
            let web3 = Web3Client::builder()
                .with_ic_host(&cli.host)
                .with_identity(Arc::new(identity))
                .with_allow_http(allow_http_for(endpoint, cli.allow_http))
                .build()
                .await?;

            println!("principal: {}", web3.get_principal());
            let args = normalize_rpc_data(data)?;

            let res: Value = web3.https_signed_rpc(endpoint, method, &args).await?;
            println!("{:?}", res);
        }

        Some(Commands::AgentRun {
            endpoint,
            name,
            prompt,
        }) => {
            let web3 = Web3Client::builder()
                .with_ic_host(&cli.host)
                .with_identity(Arc::new(identity))
                .with_allow_http(allow_http_for(endpoint, cli.allow_http))
                .build()
                .await?;

            println!("principal: {}", web3.get_principal());

            let res: AgentOutput = web3
                .https_signed_rpc(endpoint, "agent_run", &(&agent_input(name, prompt),))
                .await?;
            println!("{:?}", res);
        }

        Some(Commands::ToolCall {
            endpoint,
            name,
            args,
        }) => {
            let web3 = Web3Client::builder()
                .with_ic_host(&cli.host)
                .with_identity(Arc::new(identity))
                .with_allow_http(allow_http_for(endpoint, cli.allow_http))
                .build()
                .await?;

            println!("principal: {}", web3.get_principal());
            let input = tool_input(name, args)?;

            let res: ToolOutput<serde_json::Value> = web3
                .https_signed_rpc(endpoint, "tool_call", &(&input,))
                .await?;
            println!("{}", serde_json::to_string_pretty(&res)?);
        }

        None => {
            println!("no command");
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::CommandFactory;

    #[test]
    fn cli_parses_defaults_and_all_subcommands() {
        Cli::command().debug_assert();

        let cli = Cli::parse_from(["anda"]);
        assert_eq!(cli.host, "https://icp-api.io");
        assert_eq!(cli.id, "Anonymous");
        assert!(cli.command.is_none());

        let cli = Cli::parse_from(["anda", "rand-bytes", "--len", "8", "--format", "base64"]);
        match cli.command.unwrap() {
            Commands::RandBytes {
                len,
                format,
                ed25519,
            } => {
                assert_eq!(len, 8);
                assert_eq!(format, "base64");
                assert!(!ed25519);
            }
            _ => panic!("expected rand-bytes"),
        }

        let cli = Cli::parse_from([
            "anda",
            "--host",
            "http://localhost",
            "--id",
            "Anonymous",
            "rpc",
            "--endpoint",
            "http://127.0.0.1:8042/default",
            "--method",
            "status",
            "--data",
            "{\"ok\":true}",
        ]);
        assert_eq!(cli.host, "http://localhost");
        match cli.command.unwrap() {
            Commands::Rpc {
                endpoint,
                method,
                data,
            } => {
                assert!(endpoint.ends_with("/default"));
                assert_eq!(method, "status");
                assert_eq!(data, "{\"ok\":true}");
            }
            _ => panic!("expected rpc"),
        }

        let cli = Cli::parse_from(["anda", "agent-run", "-p", "hello", "-n", "writer"]);
        match cli.command.unwrap() {
            Commands::AgentRun {
                endpoint,
                prompt,
                name,
            } => {
                assert!(endpoint.contains("127.0.0.1"));
                assert_eq!(prompt, "hello");
                assert_eq!(name.as_deref(), Some("writer"));
            }
            _ => panic!("expected agent-run"),
        }

        let cli = Cli::parse_from([
            "anda",
            "tool-call",
            "-n",
            "lookup",
            "-a",
            "{\"q\":\"anda\"}",
        ]);
        match cli.command.unwrap() {
            Commands::ToolCall {
                endpoint,
                name,
                args,
            } => {
                assert!(endpoint.contains("127.0.0.1"));
                assert_eq!(name, "lookup");
                assert_eq!(args, "{\"q\":\"anda\"}");
            }
            _ => panic!("expected tool-call"),
        }
    }

    #[test]
    fn pure_command_helpers_prepare_outputs_and_inputs() {
        assert_eq!(bounded_rand_len(8), 8);
        assert_eq!(bounded_rand_len(2048), 1024);
        assert_eq!(format_bytes(&[0, 15, 255], "hex"), "000fff");
        assert_eq!(format_bytes(&[1, 2, 3], "base64"), "AQID");
        assert_eq!(format_bytes(&[1, 2], "debug"), "[1, 2]");

        let (secret_hex, public_hex) = format_ed25519_key_pair([7_u8; 32], "hex");
        assert_eq!(secret_hex.len(), 64);
        assert_eq!(public_hex.len(), 64);
        let (secret_b64, public_b64) = format_ed25519_key_pair([7_u8; 32], "base64");
        assert!(!secret_b64.is_empty());
        assert!(!public_b64.is_empty());
        assert_ne!(secret_hex, secret_b64);

        assert_eq!(
            normalize_rpc_data("[1,2]").unwrap(),
            serde_json::json!([1, 2])
        );
        assert_eq!(
            normalize_rpc_data("{\"ok\":true}").unwrap(),
            serde_json::json!([{"ok": true}])
        );
        assert!(normalize_rpc_data("not json").is_err());

        let input = agent_input(&Some("writer".to_string()), "draft");
        assert_eq!(input.name, "writer");
        assert_eq!(input.prompt, "draft");
        let input = agent_input(&None, "draft");
        assert_eq!(input.name, "");

        let input = tool_input("lookup", "{\"q\":\"anda\"}").unwrap();
        assert_eq!(input.name, "lookup");
        assert_eq!(input.args["q"], "anda");
        assert!(tool_input("lookup", "bad json").is_err());
    }

    #[test]
    fn plain_http_is_allowed_only_for_loopback_or_an_explicit_opt_in() {
        // Requests are signed with the user's identity, so plain HTTP to a remote host
        // exposes a replayable authorization envelope. Local development still works
        // unflagged because the built-in endpoint defaults are loopback.
        for endpoint in [
            "http://127.0.0.1:8042/default",
            "http://localhost:8042/default",
            "http://LOCALHOST:8042/default",
            "http://[::1]:8042/default",
            "http://127.0.0.1",
        ] {
            assert!(
                allow_http_for(endpoint, false),
                "{endpoint} is loopback and must be allowed"
            );
        }

        for endpoint in [
            "http://engine.example/default",
            "http://169.254.169.254/latest",
            // Userinfo must not be mistaken for the host.
            "http://127.0.0.1@evil.example/default",
            "not-a-url",
        ] {
            assert!(
                !allow_http_for(endpoint, false),
                "{endpoint} is not loopback and must require --allow-http"
            );
            assert!(
                allow_http_for(endpoint, true),
                "{endpoint} must be allowed once --allow-http is passed"
            );
        }

        // https endpoints never need the plain-http allowance.
        assert!(!allow_http_for("https://engine.example/default", false));
    }
}