agent-first-data 0.41.0

Self-describing data and structured CLI contracts for AI agents — field-name suffixes for units and secrets, the afdata CLI for rendering, validation, path guards, and reading or editing structured documents (JSON, TOML, YAML, dotenv, INI, Markdown), plus libraries for Rust, Go, Python, TypeScript, and Bash.
Documentation
//! Canonical closed-world AFDATA CLI example.
//!
//! Run:
//! `cargo run --example agent_cli -- --help`
//! `cargo run --example agent_cli -- echo hello --dry-run`
//! `cargo run --example agent_cli -- ping --host example.com`

use agent_first_data::{
    ArgSpec, CliHandler, CliMain, CliSpec, CliStop, Combination, CommandSpec, OutputSpec,
    ProcessEmitter, ResolvedInvocation, json_result,
};
use serde_json::{Value, json};
use std::process::ExitCode;

fn output() -> OutputSpec {
    OutputSpec::protocol_finite(
        ["json", "yaml", "plain"],
        ["split", "stdout", "stderr"],
        "json",
        "split",
    )
}

fn cli_spec() -> Result<agent_first_data::BuiltCliSpec, agent_first_data::CliSpecError> {
    CliSpec::new("agent-cli", env!("CARGO_PKG_VERSION"))
        .about("Canonical closed-world AFDATA CLI example")
        .lifecycle_output(output())
        .command(CommandSpec::root())
        .command(
            CommandSpec::new(["echo"])
                .about("Echo one message")
                .arg(ArgSpec::positional("message", 0, "MESSAGE").about("Message to echo"))
                .arg(ArgSpec::flag("--dry-run").about("Preview without executing"))
                .combination(
                    Combination::new("echo")
                        .action("echo")
                        .about("Echo one message")
                        .required(["message"])
                        .optional(["dry_run"])
                        .output(output()),
                ),
        )
        .command(
            CommandSpec::new(["ping"])
                .about("Describe a ping request")
                .arg(ArgSpec::option("--host", "HOST").about("Target host"))
                .combination(
                    Combination::new("ping")
                        .action("ping")
                        .about("Describe a ping request")
                        .required(["host"])
                        .output(output()),
                ),
        )
        // Here so it stays proven: AFDATA answers `--version` at the root, but
        // the name past the command path belongs to the application — this one
        // is the release's version, not a request for agent-cli's.
        .command(
            CommandSpec::new(["release"])
                .about("Describe a release request")
                .arg(ArgSpec::option("--version", "VERSION").about("Version to release"))
                .combination(
                    Combination::new("release")
                        .action("release")
                        .about("Describe a release request")
                        .required(["version"])
                        .output(output()),
                ),
        )
        .build()
}

// Each handler is a pure projection of the invocation into the result
// payload, run before any output sink opens. A read the matched combination
// does not declare is a defect in this program, reported as
// `cli_invocation_invalid` — never a silent `false` or empty string.
fn echo(invocation: &ResolvedInvocation) -> Result<Value, CliStop> {
    Ok(json!({
        "code": "echo",
        "message": invocation.text("message")?,
        "dry_run": invocation.flag("dry_run")?,
    }))
}

fn ping(invocation: &ResolvedInvocation) -> Result<Value, CliStop> {
    Ok(json!({
        "code": "ping",
        "host": invocation.text("host")?,
    }))
}

fn release(invocation: &ResolvedInvocation) -> Result<Value, CliStop> {
    Ok(json!({
        "code": "release",
        "version": invocation.text("version")?,
    }))
}

fn main() -> ExitCode {
    // `CliMain` owns the lifecycle: registry and binding errors, argv errors,
    // file sinks, help/version/docs, and the exit code of a failed write.
    CliMain::new(cli_spec(), |_| {
        [
            ("echo", echo as CliHandler<Value>),
            ("ping", ping as CliHandler<Value>),
            ("release", release as CliHandler<Value>),
        ]
    })
    .run(
        std::env::args_os(),
        |payload, _invocation, emitter: &mut ProcessEmitter| {
            Ok(emitter.finish(json_result(payload).build(), 0))
        },
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use agent_first_data::CliOutcome;

    #[test]
    fn help_comes_from_registered_combinations() {
        let cli = cli_spec().unwrap();
        let CliOutcome::Help(help) = cli.resolve_from(["agent-cli", "echo", "--help"]).unwrap()
        else {
            panic!("expected help");
        };
        let [shape] = help.model().shapes.as_slice() else {
            panic!("expected one shape");
        };
        assert_eq!(shape.id, "echo");
        // One round trip, so the optional argument is in the answer rather
        // than behind a second call the caller might never make.
        assert!(shape.usage.contains("[--dry-run]"), "{}", shape.usage);
    }

    #[test]
    fn a_subcommand_owns_the_version_name_the_root_answers() {
        let cli = cli_spec().unwrap();
        let CliOutcome::Run(invocation) = cli
            .resolve_from(["agent-cli", "release", "--version", "1.2.0"])
            .unwrap()
        else {
            panic!("expected a run outcome");
        };
        assert_eq!(invocation.text("version").unwrap(), "1.2.0");

        let CliOutcome::Version(version) = cli.resolve_from(["agent-cli", "--version"]).unwrap()
        else {
            panic!("expected version");
        };
        assert_eq!(version.name(), "agent-cli");
    }

    #[test]
    fn known_but_unregistered_mix_is_rejected() {
        let cli = cli_spec().unwrap();
        let error = cli
            .resolve_from(["agent-cli", "ping", "--host", "example.com", "--dry-run"])
            .unwrap_err();
        assert_eq!(error.rule, agent_first_data::CliErrorRule::UnknownArgument);
    }
}