#![allow(clippy::print_stdout, clippy::print_stderr)]
mod advisories;
mod guard;
#[path = "../../rust/src/lint_input.rs"]
mod lint_input;
#[path = "../../rust/src/suffix.rs"]
mod suffix;
use agent_first_data::document::{
Addressing, ArrayRule, BareOverwrite, Document, DocumentError, DocumentFile,
Format as DocumentFormat, MatchKind, MissingContainer, SymlinkPolicy, Value as DocumentValue,
ValueType, expand_path_pattern, get_path, guard_bare_overwrite, join_path, locate,
locate_with_route, parse_path, read_capped_file, value_from_type,
};
use agent_first_data::value_source::MAX_FILE_BYTES;
use agent_first_data::{
ArgSpec, CliHandler, CliMain, CliSpec, CliStop, Combination, CommandSpec, ErrorBuilder, Event,
LintOptions, OutputFormat, OutputOptions, OutputSpec, PlainStyle, ProcessEmitter,
ProtocolViolation, Redactor, ResolvedInvocation, SourceScheme, SourceSet, ValueSource,
build_afdata_cli, build_cli_error, cli_invocation_invalid_event, json_error, json_log,
json_result, lint_value as lint_serialized_value, render, validate_protocol_event,
validate_protocol_stream,
};
use serde_json::{Value, json};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
enum ParsedInput {
Single(Value),
Lines(Vec<Value>),
}
struct ParseError {
code: &'static str,
message: String,
hint: Option<String>,
line: Option<usize>,
}
fn protocol_output() -> OutputSpec {
OutputSpec::protocol_finite(
["json", "yaml", "plain"],
["split", "stdout", "stderr"],
"json",
"split",
)
.file_sinks(stream_file_sinks())
}
fn raw_output() -> OutputSpec {
OutputSpec::raw().file_sinks(stream_file_sinks())
}
fn stream_file_sinks() -> Vec<&'static str> {
#[cfg(feature = "stream-redirect")]
{
vec!["stdout", "stderr"]
}
#[cfg(not(feature = "stream-redirect"))]
{
Vec::new()
}
}
fn positional(id: &str, index: usize, value_name: &str, about: &str) -> ArgSpec {
ArgSpec::positional(id, index, value_name).about(about)
}
fn input_format_arg() -> ArgSpec {
ArgSpec::option_enum(
"--input-format",
[
"json",
"toml",
"yaml",
"yml",
"dotenv",
"env",
"ini",
"toml-frontmatter",
"yaml-frontmatter",
"markdown",
"plist",
],
)
.value_name("FORMAT")
.about("Document format override")
}
fn authored_input_format_arg() -> ArgSpec {
ArgSpec::option_enum(
"--input-format",
[
"json",
"toml",
"yaml",
"yml",
"dotenv",
"env",
"ini",
"toml-frontmatter",
"yaml-frontmatter",
],
)
.value_name("FORMAT")
.about("Document format override")
}
fn lint_input_format_arg() -> ArgSpec {
ArgSpec::option_enum(
"--input-format",
[
"json",
"toml",
"yaml",
"yml",
"dotenv",
"env",
"ini",
"toml-frontmatter",
"yaml-frontmatter",
"plist",
],
)
.value_name("FORMAT")
.about("Document format override")
}
fn read_slug_field_arg() -> ArgSpec {
ArgSpec::option("--slug-field", "FIELD")
.about("Field naming each element of an array on the path")
}
fn max_file_bytes_arg() -> ArgSpec {
ArgSpec::option_i64("--max-file-bytes", "BYTES")
.range(1, i64::MAX)
.default_i64(MAX_FILE_BYTES as i64)
.about("Largest document to read from a file or stdin, in bytes")
}
fn secret_name_arg() -> ArgSpec {
ArgSpec::option("--secret-name", "FIELD")
.repeatable()
.about("Extra exact field name to redact")
}
fn afdata_cli_spec() -> Result<agent_first_data::BuiltCliSpec, agent_first_data::CliSpecError> {
let protocol = protocol_output();
let raw = raw_output();
let mut spec = CliSpec::new("afdata", env!("CARGO_PKG_VERSION"))
.about(env!("CARGO_PKG_DESCRIPTION"))
.display_name(env!("DISPLAY_NAME"))
.build_id(match env!("GIT_SHA") {
"unknown" => "",
sha => sha,
})
.lifecycle_output(protocol.clone())
.command(CommandSpec::root())
.command(
CommandSpec::new(["lint"])
.about("Check AFDATA contracts and suggest naming or value improvements")
.arg(positional(
"input",
0,
"INPUT",
"Input file, or - for stdin",
))
.arg(lint_input_format_arg())
.arg(max_file_bytes_arg())
.arg(ArgSpec::flag("--violations-only").about("Check contracts and skip advisory analysis"))
.arg(ArgSpec::flag("--schema").about("Interpret schema property declarations in the input"))
.combination(
Combination::new("lint")
.action("lint")
.required(["input"])
.optional(["input_format", "max_file_bytes", "violations_only", "schema"])
.output(protocol.clone()),
),
)
.command(
CommandSpec::new(["validate"])
.about("Validate protocol-v1 events or a finite event stream")
.arg(positional(
"input",
0,
"INPUT",
"Input file, or - for stdin",
))
.arg(ArgSpec::flag("--strict").about("Enforce the strict protocol profile"))
.arg(
ArgSpec::flag("--per-event")
.about("Validate values independently without stream lifecycle rules"),
)
.arg(max_file_bytes_arg())
.combination(
Combination::new("validate")
.action("validate")
.required(["input"])
.optional(["strict", "per_event", "max_file_bytes"])
.output(protocol.clone()),
),
)
.command(
CommandSpec::new(["render"])
.about("Render JSON or JSONL through AFDATA redaction and formatting")
.reference_note("**Output:** Rendered input values or JSONL, without a `result` envelope. A single value has no final newline. Multi-value JSONL input produces newline-terminated values, separated by YAML document markers in YAML mode. Successful values follow `--output-to`; `split` writes them to stdout.")
.arg(positional(
"input",
0,
"INPUT",
"Input file, or - for stdin",
))
.arg(secret_name_arg())
.arg(max_file_bytes_arg())
.combination(
Combination::new("render")
.action("render")
.required(["input"])
.optional(["secret_name", "max_file_bytes"])
.output(protocol.clone()),
),
)
.command(CommandSpec::new(["emit"]).about("Emit one AFDATA event"))
.command(
CommandSpec::new(["emit", "log"])
.about("Emit a diagnostic log event")
.arg(
ArgSpec::positional_enum(
"level",
0,
"LEVEL",
["debug", "info", "warn", "error"],
)
.about("debug, info, warn, or error"),
)
.arg(positional(
"message",
1,
"MESSAGE",
"Human-readable message",
))
.combination(
Combination::new("emit-log")
.action("emit_log")
.required(["level", "message"])
.output(protocol.clone()),
),
)
.command(
CommandSpec::new(["emit", "result"])
.about("Emit a terminal result event")
.arg(positional("message", 0, "MESSAGE", "Result message"))
.arg(
ArgSpec::option_json("--json", "JSON")
.about("Structured result payload; redaction applies"),
)
.combination(
Combination::new("emit-result-json")
.about("Emit a structured JSON payload")
.action("emit_result_json")
.required(["json"])
.output(protocol.clone()),
)
.combination(
Combination::new("emit-result")
.about("Emit a text message")
.action("emit_result")
.required(["message"])
.output(protocol.clone()),
),
)
.command(
CommandSpec::new(["emit", "error"])
.about("Emit a terminal error event")
.arg(positional("code", 0, "CODE", "Stable error code"))
.arg(positional("message", 1, "MESSAGE", "Error message"))
.arg(ArgSpec::option("--hint", "HINT").about("Suggested corrective action"))
.arg(ArgSpec::flag("--retryable").about("Mark the failure safe to retry"))
.combination(
Combination::new("emit-error")
.action("emit_error")
.required(["code", "message"])
.optional(["hint", "retryable"])
.output(protocol.clone()),
),
)
.command(CommandSpec::new(["shell"]).about("Export a shell authoring kit"))
.command(
CommandSpec::new(["shell", "bash"])
.about("Print the sourceable Bash authoring kit")
.combination(
Combination::new("shell-bash")
.action("shell_bash")
.output(raw.clone()),
),
)
.command(
CommandSpec::new(["get"])
.about("Read a document or one value as an AFDATA result")
.arg(positional(
"file",
0,
"FILE",
"Document file, or - for stdin (read as JSON unless --input-format is given)",
))
.arg(positional("key", 1, "KEY", "Optional dot-path"))
.arg(input_format_arg())
.arg(max_file_bytes_arg())
.arg(read_slug_field_arg())
.arg(secret_name_arg())
.combination(
Combination::new("get-document")
.action("get")
.about("Read the entire document")
.required(["file"])
.optional(["input_format", "max_file_bytes", "secret_name"])
.output(protocol.clone()),
)
.combination(
Combination::new("get-value")
.action("get")
.about("Read one value at KEY")
.required(["file", "key"])
.optional(["input_format", "max_file_bytes", "slug_field", "secret_name"])
.output(protocol.clone()),
),
)
.command(
CommandSpec::new(["value"])
.about(
"Read one scalar as raw stdout bytes: exact bytes, no trailing newline; \
for one value per line use values",
)
.arg(positional(
"file",
0,
"FILE",
"Document file, or - for stdin (read as JSON unless --input-format is given)",
))
.arg(positional("key", 1, "KEY", "Dot-path to one scalar"))
.arg(ArgSpec::flag("--reveal-secret").about("Allow secret values and URL credentials"))
.arg(ArgSpec::option("--default", "VALUE").about("Fallback when the path leads to no value (missing, through a scalar, or null)"))
.arg(input_format_arg())
.arg(max_file_bytes_arg())
.arg(read_slug_field_arg())
.arg(secret_name_arg())
.combination(
Combination::new("value")
.action("value")
.required(["file", "key"])
.optional([
"reveal_secret",
"default",
"input_format",
"max_file_bytes",
"slug_field",
"secret_name",
])
.output(raw.clone()),
),
)
.command(
CommandSpec::new(["values"])
.about("Read many scalars as raw lines, from one parse of the document")
.arg(positional(
"file",
0,
"FILE",
"Document file, or - for stdin (read as JSON unless --input-format is given)",
))
.arg(
ArgSpec::positional("key", 1, "KEY")
.repeatable()
.about(
"Dot-path to one scalar; repeat for each value wanted. A `*` \
segment expands to every child in index or key order, so \
`items.*.name` yields one line per element; with --default a \
missing or null field gives an empty line and the line count \
stays aligned",
),
)
.arg(ArgSpec::flag("--reveal-secret").about("Allow secret values and URL credentials"))
.arg(ArgSpec::option("--default", "VALUE").about("Fallback when the path leads to no value (missing, through a scalar, or null)"))
.arg(ArgSpec::flag("--missing-ok").about(
"A KEY whose `*` container, or any segment before it, is missing \
contributes no records; a missing leaf is still governed by --default",
))
.arg(ArgSpec::flag("--null").about(
"Use NUL separators, so values containing newlines are framed intact",
))
.arg(input_format_arg())
.arg(max_file_bytes_arg())
.arg(read_slug_field_arg())
.arg(secret_name_arg())
.combination(
Combination::new("values")
.action("values")
.required(["file", "key"])
.optional([
"reveal_secret",
"default",
"missing_ok",
"null",
"input_format",
"max_file_bytes",
"slug_field",
"secret_name",
])
.output(raw.clone()),
),
)
.command(
CommandSpec::new(["json"])
.about(
"Read a document or subtree as one line of compact JSON with a trailing \
newline, no envelope; secrets are redacted as in get",
)
.arg(positional(
"file",
0,
"FILE",
"Document file, or - for stdin (read as JSON unless --input-format is given)",
))
.arg(positional("key", 1, "KEY", "Optional dot-path; omitted means the whole document"))
.arg(ArgSpec::flag("--reveal-secret").about("Allow secret values and URL credentials"))
.arg(ArgSpec::option("--default", "JSON").about(
"Fallback JSON text, printed as compact JSON, when the path leads to no value (missing, through a scalar, or null)",
))
.arg(input_format_arg())
.arg(max_file_bytes_arg())
.arg(read_slug_field_arg())
.arg(secret_name_arg())
.combination(
Combination::new("json-document")
.action("json")
.about("Read the entire document")
.required(["file"])
.optional([
"reveal_secret",
"input_format",
"max_file_bytes",
"secret_name",
])
.output(raw.clone()),
)
.combination(
Combination::new("json-value")
.action("json")
.about("Read the subtree at KEY")
.required(["file", "key"])
.optional([
"reveal_secret",
"default",
"input_format",
"max_file_bytes",
"slug_field",
"secret_name",
])
.output(raw.clone()),
),
)
.command(
CommandSpec::new(["path"])
.about(
"Join literal key segments into one dot-path, escaping backslash, `.` and \
`*`; raw stdout bytes with no trailing newline",
)
.arg(
ArgSpec::positional("segment", 0, "SEGMENT")
.repeatable()
.about("One literal key or index. Empty keys are allowed in a multi-segment path"),
)
.combination(
Combination::new("path")
.action("path")
.required(["segment"])
.output(raw.clone()),
),
)
.command(
CommandSpec::new(["has"])
.about(
"Print true or false, with no trailing newline, for whether KEY exists; \
null counts as present",
)
.arg(positional(
"file",
0,
"FILE",
"Document file, or - for stdin (read as JSON unless --input-format is given)",
))
.arg(positional("key", 1, "KEY", "Dot-path to test"))
.arg(input_format_arg())
.arg(max_file_bytes_arg())
.arg(read_slug_field_arg())
.combination(
Combination::new("has")
.action("has")
.required(["file", "key"])
.optional(["input_format", "max_file_bytes", "slug_field"])
.output(raw.clone()),
),
)
.command(
CommandSpec::new(["count"])
.about(
"Print how many direct children the container at KEY has, as a decimal \
integer with no trailing newline",
)
.arg(positional(
"file",
0,
"FILE",
"Document file, or - for stdin (read as JSON unless --input-format is given)",
))
.arg(positional("key", 1, "KEY", "Optional dot-path to an object or array; omitted means the document root"))
.arg(ArgSpec::flag("--missing-ok").about(
"Print 0 when the path leads to no container (missing, through a scalar, or null)",
))
.arg(input_format_arg())
.arg(max_file_bytes_arg())
.arg(read_slug_field_arg())
.combination(
Combination::new("count-root")
.action("count")
.about("Count the document root's immediate children")
.required(["file"])
.optional(["input_format", "max_file_bytes"])
.output(raw.clone()),
)
.combination(
Combination::new("count-container")
.action("count")
.about("Count one addressed container's immediate children")
.required(["file", "key"])
.optional(["missing_ok", "input_format", "max_file_bytes", "slug_field"])
.output(raw.clone()),
),
)
.command(
CommandSpec::new(["object"])
.about(
"Build one JSON object from arguments, as one line of compact JSON with a \
trailing newline",
)
.arg(
ArgSpec::positional("fields", 0, "FIELD=VALUE")
.key_value()
.repeatable()
.about("String field; the key is literal and split at the first ="),
)
.arg(
ArgSpec::option("--json", "FIELD=JSON")
.key_value()
.repeatable()
.about("Field whose value is embedded JSON text (number, bool, null, array, object)"),
)
.combination(
Combination::new("object")
.action("object")
.optional(["fields", "json"])
.output(raw.clone()),
),
)
.command(
CommandSpec::new(["array"])
.about(
"Build one JSON array from arguments, as one line of compact JSON with a \
trailing newline",
)
.arg(
ArgSpec::positional("values", 0, "VALUE")
.repeatable()
.about("Element; a string unless --json is given"),
)
.arg(ArgSpec::flag("--json").about("Parse every VALUE as JSON text"))
.combination(
Combination::new("array")
.action("array")
.optional(["values", "json"])
.output(raw.clone()),
),
)
.command(
CommandSpec::new(["guard"])
.about(
"Validate a value against a destructive-verb operand type and print its \
normalized absolute path as raw stdout bytes",
)
.arg(
ArgSpec::positional_enum("type", 0, "TYPE", ["path", "tmp_path", "cwd_path"])
.about(
"path: no containment beyond the shared reject set; tmp_path: must \
sit strictly under the system temp area; cwd_path: must sit \
strictly under the current directory",
),
)
.arg(positional(
"value",
1,
"VALUE",
"Value to validate, e.g. the contents of a shell variable",
))
.arg(ArgSpec::option("--under", "ROOT").about(
"Additional containment root VALUE must sit strictly under, for a target \
anchored to a directory the caller knows and the TYPE vocabulary cannot \
name",
))
.combination(
Combination::new("guard")
.action("guard")
.required(["type", "value"])
.optional(["under"])
.output(raw.clone()),
),
)
.command(enumerate_command(
"paths",
"paths",
"List each child's full dot-path as raw lines",
&raw,
))
.command(enumerate_command(
"keys",
"keys",
"List child names as raw lines, without their parent path",
&raw,
))
.command(
CommandSpec::new(["set"])
.about("Set a value at a dot-path, creating missing object parents")
.arg(positional("file", 0, "FILE", "Document file to mutate"))
.arg(positional("key", 1, "KEY", "Dot-path to set"))
.arg(positional("value", 2, "VALUE", "Value to write"))
.arg(
ArgSpec::option_enum(
"--value-type",
["string", "number", "bool", "null", "json"],
)
.value_name("TYPE")
.default("string")
.about("Exact VALUE type"),
)
.arg(
ArgSpec::option("--secret-from", "SOURCE")
.about("Read a secret string from stdin, prompt, fd:N, or env:VAR"),
)
.arg(authored_input_format_arg())
.arg(max_file_bytes_arg())
.arg(read_slug_field_arg())
.combination(
Combination::new("set-value")
.action("set")
.about("Set one typed scalar or JSON value")
.fixed_one_of("value_type", ["string", "number", "bool", "json"])
.required(["file", "key", "value"])
.optional(["input_format", "max_file_bytes", "slug_field"])
.output(protocol.clone()),
)
.combination(
Combination::new("set-null")
.action("set")
.about("Set the key to null; takes no VALUE")
.fixed("value_type", "null")
.required(["file", "key"])
.optional(["input_format", "max_file_bytes", "slug_field"])
.output(protocol.clone()),
)
.combination(
Combination::new("set-secret")
.action("set")
.about("Set the key from a secret source, never from argv")
.required(["file", "key", "secret_from"])
.optional(["input_format", "max_file_bytes", "slug_field"])
.output(protocol.clone()),
),
)
.command(
CommandSpec::new(["unset"])
.about("Remove one document entry")
.arg(positional("file", 0, "FILE", "Document file to mutate"))
.arg(positional("key", 1, "KEY", "Dot-path to remove"))
.arg(authored_input_format_arg())
.arg(max_file_bytes_arg())
.arg(read_slug_field_arg())
.combination(
Combination::new("unset")
.action("unset")
.required(["file", "key"])
.optional(["input_format", "max_file_bytes", "slug_field"])
.output(protocol.clone()),
),
)
.command(
CommandSpec::new(["add"])
.about("Add an element to a keyed list")
.arg(positional("file", 0, "FILE", "Document file to mutate"))
.arg(positional("key", 1, "KEY", "Dot-path to the keyed list"))
.arg(positional("slug", 2, "SLUG", "New element slug"))
.arg(
ArgSpec::positional("fields", 3, "FIELD=VALUE")
.key_value()
.repeatable()
.about("Additional string fields"),
)
.arg(
ArgSpec::option("--slug-field", "FIELD")
.about("Field that identifies each list element"),
)
.arg(authored_input_format_arg())
.arg(max_file_bytes_arg())
.combination(
Combination::new("add")
.action("add")
.required(["file", "key", "slug", "slug_field"])
.optional(["fields", "input_format", "max_file_bytes"])
.output(protocol.clone()),
),
)
.command(
CommandSpec::new(["remove"])
.about("Remove a keyed-list element by slug")
.arg(positional("file", 0, "FILE", "Document file to mutate"))
.arg(positional("key", 1, "KEY", "Dot-path to the keyed list"))
.arg(positional("slug", 2, "SLUG", "Element slug"))
.arg(
ArgSpec::option("--slug-field", "FIELD")
.about("Field that identifies each list element"),
)
.arg(authored_input_format_arg())
.arg(max_file_bytes_arg())
.combination(
Combination::new("remove")
.action("remove")
.required(["file", "key", "slug", "slug_field"])
.optional(["input_format", "max_file_bytes"])
.output(protocol.clone()),
),
);
#[cfg(feature = "skill-admin")]
for command in agent_first_data::skill::skill_cli_commands(&SKILL_SPEC, &protocol) {
spec = spec.command(command);
}
#[cfg(all(feature = "skill", not(feature = "skill-admin")))]
{
spec = spec.command(CommandSpec::new(["skill"]).about("Validate an Agent Skill"));
}
#[cfg(feature = "skill")]
{
spec = spec.command(
CommandSpec::new(["skill", "validate"])
.about("Validate an Agent Skill")
.arg(positional(
"input",
0,
"INPUT",
"SKILL.md file, directory, or - for stdin",
))
.arg(max_file_bytes_arg())
.combination(
Combination::new("skill-validate")
.action("skill_validate")
.required(["input"])
.optional(["max_file_bytes"])
.output(protocol.clone()),
),
);
}
build_afdata_cli(spec)
}
fn enumerate_command(name: &str, action: &str, about: &str, output: &OutputSpec) -> CommandSpec {
CommandSpec::new([name])
.about(about)
.arg(positional(
"file",
0,
"FILE",
"Document file, or - for stdin (read as JSON unless --input-format is given)",
))
.arg(positional("key", 1, "KEY", "Optional container dot-path"))
.arg(input_format_arg())
.arg(max_file_bytes_arg())
.arg(read_slug_field_arg())
.arg(ArgSpec::flag("--missing-ok").about(
"Print nothing and succeed when the path leads to no container (missing, through a scalar, or null)",
))
.arg(ArgSpec::flag("--slugs").about(
"When KEY is an array, list each element's --slug-field value instead of its index",
))
.arg(ArgSpec::flag("--null").about("Use NUL separators"))
.combination(
Combination::new(format!("{name}-root"))
.action(action)
.about("List the document root's immediate children")
.required(["file"])
.optional(["input_format", "max_file_bytes", "null"])
.output(output.clone()),
)
.combination(
Combination::new(format!("{name}-container"))
.action(action)
.about("List one addressed container's immediate children")
.required(["file", "key"])
.optional([
"input_format",
"max_file_bytes",
"slug_field",
"missing_ok",
"null",
])
.output(output.clone()),
)
.combination(
Combination::new(format!("{name}-slugs"))
.action(action)
.about("List one addressed array's elements by their --slug-field value")
.required(["file", "key", "slug_field", "slugs"])
.optional(["input_format", "max_file_bytes", "missing_ok", "null"])
.output(output.clone()),
)
}
#[cfg(feature = "skill-admin")]
const SKILL_SPEC: agent_first_data::skill::SkillSpec = agent_first_data::skill::SkillSpec {
name: "agent-first-data",
source: include_str!("../../skills/agent-first-data/SKILL.md"),
title: "Agent-First Data",
marker_slug: "afdata",
assets: &[
agent_first_data::skill::SkillAsset {
path: "references/bash.md",
contents: include_str!("../../skills/agent-first-data/references/bash.md"),
},
agent_first_data::skill::SkillAsset {
path: "references/cli-protocol.md",
contents: include_str!("../../skills/agent-first-data/references/cli-protocol.md"),
},
agent_first_data::skill::SkillAsset {
path: "references/documents.md",
contents: include_str!("../../skills/agent-first-data/references/documents.md"),
},
agent_first_data::skill::SkillAsset {
path: "references/naming-output.md",
contents: include_str!("../../skills/agent-first-data/references/naming-output.md"),
},
agent_first_data::skill::SkillAsset {
path: "references/registry.json",
contents: include_str!("../../skills/agent-first-data/references/registry.json"),
},
agent_first_data::skill::SkillAsset {
path: "references/protocol-v1.schema.json",
contents: include_str!(
"../../skills/agent-first-data/references/protocol-v1.schema.json"
),
},
agent_first_data::skill::SkillAsset {
path: "references/cli-help-v2.schema.json",
contents: include_str!(
"../../skills/agent-first-data/references/cli-help-v2.schema.json"
),
},
agent_first_data::skill::SkillAsset {
path: "references/cli-spec-v1.schema.json",
contents: include_str!(
"../../skills/agent-first-data/references/cli-spec-v1.schema.json"
),
},
],
};
fn main() -> ExitCode {
CliMain::new(afdata_cli_spec(), |_| action_handlers()).run(std::env::args_os(), execute)
}
fn action_handlers() -> Vec<(&'static str, CliHandler<Command>)> {
#[allow(unused_mut)]
let mut handlers: Vec<(&'static str, CliHandler<Command>)> = vec![
("lint", project_lint),
("validate", project_validate),
("render", project_render),
("emit_log", project_emit_log),
("emit_result", project_emit_result),
("emit_result_json", project_emit_result_json),
("emit_error", project_emit_error),
("shell_bash", |_| Ok(Command::ShellBash)),
("get", project_get),
("value", project_value),
("values", project_values),
("guard", project_guard),
("json", project_json),
("has", project_has),
("count", project_count),
("path", project_path),
("object", project_object),
("array", project_array),
("paths", project_enumerate),
("keys", project_enumerate),
("set", project_set),
("unset", project_unset),
("add", project_add),
("remove", project_remove),
];
#[cfg(feature = "skill")]
handlers.push(("skill_validate", |invocation| {
Ok(Command::SkillValidate {
input: PathBuf::from(invocation.text("input")?),
max_bytes: read_max_bytes(invocation)?,
})
}));
#[cfg(feature = "skill-admin")]
handlers.extend(
agent_first_data::skill::SKILL_CLI_ACTIONS
.map(|action| (action, project_skill_admin as CliHandler<Command>)),
);
handlers
}
enum Command {
Lint {
input: PathBuf,
input_format: Option<DocumentFormat>,
schema: bool,
violations_only: bool,
max_bytes: u64,
},
Validate {
input: PathBuf,
max_bytes: u64,
strict: bool,
per_event: bool,
},
Render {
input: PathBuf,
max_bytes: u64,
secret_names: Vec<String>,
},
Emit {
event: Event,
exit_code: u8,
},
ShellBash,
#[cfg(feature = "skill")]
SkillValidate {
input: PathBuf,
max_bytes: u64,
},
#[cfg(feature = "skill-admin")]
SkillAdmin(agent_first_data::skill::SkillCliRequest),
Raw(Vec<u8>),
Guard {
guard_type: guard::GuardType,
value: String,
under: Option<String>,
},
Get {
file: PathBuf,
key: Option<String>,
ctx: DocumentContext,
},
Value {
file: PathBuf,
key: String,
reveal_secret: bool,
default: Option<String>,
ctx: DocumentContext,
},
Values {
file: PathBuf,
keys: Vec<String>,
reveal_secret: bool,
default: Option<String>,
missing_ok: bool,
null_separated: bool,
ctx: DocumentContext,
},
Json {
file: PathBuf,
key: Option<String>,
reveal_secret: bool,
default: Option<Value>,
ctx: DocumentContext,
},
Has {
file: PathBuf,
key: String,
ctx: DocumentContext,
},
Count {
file: PathBuf,
key: Option<String>,
missing_ok: bool,
ctx: DocumentContext,
},
Enumerate {
file: PathBuf,
key: Option<String>,
missing_ok: bool,
null_separated: bool,
mode: EnumerateMode,
ctx: DocumentContext,
},
Set {
file: PathBuf,
key: String,
value: SetValue,
ctx: DocumentContext,
},
Unset {
file: PathBuf,
key: String,
ctx: DocumentContext,
},
Add {
file: PathBuf,
key: String,
slug: String,
slug_field: String,
fields: Vec<(String, DocumentValue)>,
ctx: DocumentContext,
},
Remove {
file: PathBuf,
key: String,
slug: String,
slug_field: String,
ctx: DocumentContext,
},
}
enum SetValue {
Bare(String),
Typed(DocumentValue),
Secret(ValueSource),
}
fn execute(
command: Command,
_invocation: &ResolvedInvocation,
emitter: &mut ProcessEmitter,
) -> Result<u8, CliStop> {
Ok(match command {
Command::Lint {
input,
input_format,
schema,
violations_only,
max_bytes,
} => run_lint(
&input,
input_format,
schema,
violations_only,
max_bytes,
emitter,
),
Command::Validate {
input,
strict,
per_event,
max_bytes,
} => run_validate(&input, strict, per_event, max_bytes, emitter),
Command::Render {
input,
secret_names,
max_bytes,
} => run_render(&input, &secret_names, max_bytes, emitter),
Command::Emit { event, exit_code } => emitter.finish(event, exit_code),
Command::ShellBash => {
const BASH_SOURCE: &str = include_str!("../../bash/afdata.sh");
write_raw(emitter, BASH_SOURCE.as_bytes())
}
#[cfg(feature = "skill")]
Command::SkillValidate { input, max_bytes } => {
run_skill_validate(&input, max_bytes, emitter)
}
#[cfg(feature = "skill-admin")]
Command::SkillAdmin(request) => request.run(&SKILL_SPEC, emitter),
Command::Raw(bytes) => write_raw(emitter, &bytes),
Command::Guard {
guard_type,
value,
under,
} => finish_guard(
guard::guard_from_environment(guard_type, &value, under.as_deref()),
emitter,
),
Command::Get { file, key, ctx } => {
let result = compute_get(&file, key.as_deref(), &ctx);
emitter.set_options(document_output_options(&ctx));
let result = result.and_then(|payload| {
emitter.finish_document_result(payload).map_err(|error| {
let error = match error {
DocumentError::NonFiniteNumber { path } => {
let path = path.strip_prefix("value.").unwrap_or("");
DocumentError::NonFiniteNumber {
path: document_relative_path(key.as_deref(), path),
}
}
error => error,
};
CliDocError::from(error)
})
});
match result {
Ok(code) => code,
Err(error) => {
let (event, code) = document_error_event(&error);
emitter.finish(event, code)
}
}
}
Command::Value {
file,
key,
reveal_secret,
default,
ctx,
} => finish_raw(
compute_value(&file, &key, reveal_secret, default.as_deref(), &ctx),
&ctx,
emitter,
),
Command::Values {
file,
keys,
reveal_secret,
default,
missing_ok,
null_separated,
ctx,
} => finish_raw(
compute_values(
&file,
&keys,
reveal_secret,
default.as_deref(),
missing_ok,
null_separated,
&ctx,
),
&ctx,
emitter,
),
Command::Json {
file,
key,
reveal_secret,
default,
ctx,
} => finish_raw(
compute_json(&file, key.as_deref(), reveal_secret, default, &ctx),
&ctx,
emitter,
),
Command::Has { file, key, ctx } => {
finish_raw(compute_has(&file, &key, &ctx), &ctx, emitter)
}
Command::Count {
file,
key,
missing_ok,
ctx,
} => finish_raw(
compute_count(&file, key.as_deref(), missing_ok, &ctx),
&ctx,
emitter,
),
Command::Enumerate {
file,
key,
missing_ok,
null_separated,
mode,
ctx,
} => run_enumerate(
&file,
key.as_deref(),
&ctx,
missing_ok,
null_separated,
mode,
emitter,
),
Command::Set {
file,
key,
value,
ctx,
} => finish_document(compute_set(&file, &key, value, &ctx), &ctx, emitter),
Command::Unset { file, key, ctx } => {
finish_document(compute_unset(&file, &key, &ctx), &ctx, emitter)
}
Command::Add {
file,
key,
slug,
slug_field,
fields,
ctx,
} => finish_document(
compute_add(&file, &key, &slug, &slug_field, &fields, &ctx),
&ctx,
emitter,
),
Command::Remove {
file,
key,
slug,
slug_field,
ctx,
} => finish_document(
compute_remove(&file, &key, &slug, &slug_field, &ctx),
&ctx,
emitter,
),
})
}
fn write_raw(emitter: &mut ProcessEmitter, bytes: &[u8]) -> u8 {
let _settled_by_exit_code = emitter.write_raw(bytes);
0
}
fn owned(text: Option<&str>) -> Option<String> {
text.map(str::to_string)
}
fn owned_all(texts: Vec<&str>) -> Vec<String> {
texts.into_iter().map(str::to_string).collect()
}
fn usage_stop(message: impl Into<String>) -> CliStop {
let (event, code) = document_error_event(&CliDocError::Usage(message.into()));
CliStop::new(event, code)
}
fn read_input_format(invocation: &ResolvedInvocation) -> Result<Option<DocumentFormat>, CliStop> {
invocation
.optional_text("input_format")?
.map(parse_document_format)
.transpose()
.map_err(usage_stop)
}
fn read_max_bytes(invocation: &ResolvedInvocation) -> Result<u64, CliStop> {
Ok(invocation.integer::<u64>("max_file_bytes")?)
}
fn document_context(
invocation: &ResolvedInvocation,
slug_field: Option<String>,
secret_names: Vec<String>,
) -> Result<DocumentContext, CliStop> {
Ok(DocumentContext {
input_format: read_input_format(invocation)?,
slug_field,
list_slugs: None,
secret_names,
max_bytes: read_max_bytes(invocation)?,
})
}
fn read_file(invocation: &ResolvedInvocation) -> Result<PathBuf, CliStop> {
Ok(PathBuf::from(invocation.text("file")?))
}
fn nonempty_text<'a>(
invocation: &'a ResolvedInvocation,
id: &str,
message: &str,
hint: &str,
) -> Result<&'a str, CliStop> {
match invocation.text(id)? {
"" => Err(CliStop::invalid_argument(message, hint)),
text => Ok(text),
}
}
fn unique_pairs<'a>(
pairs: impl IntoIterator<Item = (&'a str, &'a str)>,
seen: &mut Vec<String>,
) -> Result<Vec<(String, String)>, CliStop> {
let mut out = Vec::new();
for (name, value) in pairs {
if seen.iter().any(|existing| existing == name) {
return Err(CliStop::invalid_argument(
&format!("field `{name}` is given more than once"),
"give each field once",
));
}
seen.push(name.to_string());
out.push((name.to_string(), value.to_string()));
}
Ok(out)
}
fn project_lint(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
Ok(Command::Lint {
input: PathBuf::from(invocation.text("input")?),
input_format: read_input_format(invocation)?,
schema: invocation.flag("schema")?,
violations_only: invocation.flag("violations_only")?,
max_bytes: read_max_bytes(invocation)?,
})
}
fn project_validate(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
Ok(Command::Validate {
input: PathBuf::from(invocation.text("input")?),
max_bytes: read_max_bytes(invocation)?,
strict: invocation.flag("strict")?,
per_event: invocation.flag("per_event")?,
})
}
fn project_render(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
Ok(Command::Render {
input: PathBuf::from(invocation.text("input")?),
max_bytes: read_max_bytes(invocation)?,
secret_names: owned_all(invocation.texts("secret_name")?),
})
}
fn project_emit_log(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
let message = nonempty_text(
invocation,
"message",
"log MESSAGE must not be empty",
"pass a nonempty MESSAGE; `afdata emit log --help` shows the shape",
)?;
Ok(Command::Emit {
event: json_log(json!({
"level": invocation.text("level")?,
"message": message,
}))
.build(),
exit_code: 0,
})
}
fn project_emit_result(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
let message = nonempty_text(
invocation,
"message",
"result MESSAGE must not be empty",
"pass a nonempty MESSAGE; `afdata emit result --help` shows the shape",
)?;
Ok(Command::Emit {
event: json_result(json!({"message": message})).build(),
exit_code: 0,
})
}
fn project_emit_result_json(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
let payload = serde_json::from_str::<Value>(invocation.json_text("json")?).map_err(|_| {
CliStop::invalid_argument(
"--json must contain valid JSON",
"run `afdata emit result --help`",
)
})?;
Ok(Command::Emit {
event: json_result(payload).build(),
exit_code: 0,
})
}
fn project_emit_error(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
let (code, message) = (invocation.text("code")?, invocation.text("message")?);
if code.is_empty() || message.is_empty() {
return Err(CliStop::invalid_argument(
"error CODE and MESSAGE must not be empty",
"pass a nonempty CODE and MESSAGE; `afdata emit error --help` shows the shape",
));
}
let hint = invocation.optional_text("hint")?;
if hint == Some("") {
return Err(CliStop::invalid_argument(
"--hint must not be empty",
"pass a nonempty hint or omit --hint. Run afdata emit error --help for usage.",
));
}
Ok(Command::Emit {
event: build_error_event(
json_error(code, message)
.hint_if_some(hint)
.retryable_if(invocation.flag("retryable")?),
),
exit_code: 1,
})
}
#[cfg(feature = "skill-admin")]
fn project_skill_admin(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
agent_first_data::skill::SkillCliRequest::from_invocation(invocation).map(Command::SkillAdmin)
}
fn project_get(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
let secret_names = owned_all(invocation.texts("secret_name")?);
let (key, slug_field) = match invocation.combination_id() {
"get-value" => (
Some(invocation.text("key")?.to_string()),
owned(invocation.optional_text("slug_field")?),
),
_ => (None, None),
};
Ok(Command::Get {
file: read_file(invocation)?,
key,
ctx: document_context(invocation, slug_field, secret_names)?,
})
}
fn project_value(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
Ok(Command::Value {
file: read_file(invocation)?,
key: invocation.text("key")?.to_string(),
reveal_secret: invocation.flag("reveal_secret")?,
default: owned(invocation.optional_text("default")?),
ctx: document_context(
invocation,
owned(invocation.optional_text("slug_field")?),
owned_all(invocation.texts("secret_name")?),
)?,
})
}
fn project_values(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
Ok(Command::Values {
file: read_file(invocation)?,
keys: owned_all(invocation.texts("key")?),
reveal_secret: invocation.flag("reveal_secret")?,
default: owned(invocation.optional_text("default")?),
missing_ok: invocation.flag("missing_ok")?,
null_separated: invocation.flag("null")?,
ctx: document_context(
invocation,
owned(invocation.optional_text("slug_field")?),
owned_all(invocation.texts("secret_name")?),
)?,
})
}
fn project_json(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
let (key, default, slug_field) = match invocation.combination_id() {
"json-value" => (
Some(invocation.text("key")?.to_string()),
invocation
.optional_text("default")?
.map(|text| parse_embedded_json(text, "--default"))
.transpose()?,
owned(invocation.optional_text("slug_field")?),
),
_ => (None, None, None),
};
Ok(Command::Json {
file: read_file(invocation)?,
key,
reveal_secret: invocation.flag("reveal_secret")?,
default,
ctx: document_context(
invocation,
slug_field,
owned_all(invocation.texts("secret_name")?),
)?,
})
}
fn project_has(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
Ok(Command::Has {
file: read_file(invocation)?,
key: invocation.text("key")?.to_string(),
ctx: document_context(
invocation,
owned(invocation.optional_text("slug_field")?),
Vec::new(),
)?,
})
}
fn project_count(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
let (key, missing_ok, slug_field) = match invocation.combination_id() {
"count-container" => (
Some(invocation.text("key")?.to_string()),
invocation.flag("missing_ok")?,
owned(invocation.optional_text("slug_field")?),
),
_ => (None, false, None),
};
Ok(Command::Count {
file: read_file(invocation)?,
key,
missing_ok,
ctx: document_context(invocation, slug_field, Vec::new())?,
})
}
fn project_enumerate(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
let mode = if invocation.action_id() == "paths" {
EnumerateMode::Paths
} else {
EnumerateMode::Keys
};
let combination = invocation.combination_id();
let (key, missing_ok, slug_field, list_slugs) = if combination.ends_with("-root") {
(None, false, None, false)
} else if combination.ends_with("-slugs") {
(
Some(invocation.text("key")?.to_string()),
invocation.flag("missing_ok")?,
Some(invocation.text("slug_field")?.to_string()),
invocation.flag("slugs")?,
)
} else {
(
Some(invocation.text("key")?.to_string()),
invocation.flag("missing_ok")?,
owned(invocation.optional_text("slug_field")?),
false,
)
};
let mut ctx = document_context(invocation, slug_field, Vec::new())?;
if list_slugs {
ctx.list_slugs.clone_from(&ctx.slug_field);
}
Ok(Command::Enumerate {
file: read_file(invocation)?,
key,
missing_ok,
null_separated: invocation.flag("null")?,
mode,
ctx,
})
}
fn project_path(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
let segments = owned_all(invocation.texts("segment")?);
let path = join_path(&segments);
if path.is_empty() {
return Err(CliStop::invalid_argument(
"SEGMENT values must form a nonempty dot-path",
"provide a nonempty segment or two or more segments",
));
}
Ok(Command::Raw(path.into_bytes()))
}
fn project_object(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
let mut seen = Vec::new();
let strings = unique_pairs(invocation.key_values("fields")?, &mut seen)?;
let embedded = unique_pairs(invocation.key_values("json")?, &mut seen)?;
let mut object = serde_json::Map::new();
for (name, value) in strings {
object.insert(name, Value::String(value));
}
for (name, text) in embedded {
let value = parse_embedded_json(&text, &format!("--json value for `{name}`"))?;
object.insert(name, value);
}
compact_json_line(&Value::Object(object))
.map(Command::Raw)
.map_err(projection_stop)
}
fn project_array(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
let as_json = invocation.flag("json")?;
let mut items = Vec::new();
for value in invocation.texts("values")? {
items.push(if as_json {
parse_embedded_json(value, "array element")?
} else {
Value::String(value.to_string())
});
}
compact_json_line(&Value::Array(items))
.map(Command::Raw)
.map_err(projection_stop)
}
fn projection_stop(err: CliDocError) -> CliStop {
let (event, code) = document_error_event(&err);
CliStop::new(event, code)
}
fn project_guard(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
let guard_type = guard::GuardType::parse(invocation.text("type")?).ok_or_else(|| {
CliStop::new(
cli_invocation_invalid_event("resolved invocation has an unregistered guard TYPE"),
1,
)
})?;
Ok(Command::Guard {
guard_type,
value: invocation.text("value")?.to_string(),
under: owned(invocation.optional_text("under")?),
})
}
fn project_set(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
let value = match invocation.combination_id() {
"set-secret" => SetValue::Secret(
parse_secret_from(invocation.text("secret_from")?).map_err(projection_stop)?,
),
combination => {
let value = match combination {
"set-value" => Some(invocation.text("value")?.to_string()),
_ => None,
};
if invocation.was_explicit("value_type")? {
let name = invocation.text("value_type")?;
let value_type = ValueType::parse(name).ok_or_else(|| {
usage_stop(format!(
"invalid --value-type `{name}`; expected string, number, bool, null, or json"
))
})?;
SetValue::Typed(value_from_type(value_type, value.as_deref()).map_err(|error| {
CliStop::invalid_argument(
&error.redacted_message(),
"pass VALUE in the form --value-type names; `afdata set --help` lists the types",
)
})?)
} else {
SetValue::Bare(value.ok_or_else(|| {
usage_stop("set requires VALUE, --value-type null, or --secret-from")
})?)
}
}
};
Ok(Command::Set {
file: read_file(invocation)?,
key: invocation.text("key")?.to_string(),
value,
ctx: document_context(
invocation,
owned(invocation.optional_text("slug_field")?),
Vec::new(),
)?,
})
}
fn project_unset(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
Ok(Command::Unset {
file: read_file(invocation)?,
key: invocation.text("key")?.to_string(),
ctx: document_context(
invocation,
owned(invocation.optional_text("slug_field")?),
Vec::new(),
)?,
})
}
fn project_add(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
let slug_field = nonempty_text(
invocation,
"slug_field",
"--slug-field must not be empty",
"name the field that identifies each element",
)?;
let slug = invocation.text("slug")?;
let mut seen = Vec::new();
let fields = unique_pairs(invocation.key_values("fields")?, &mut seen)?
.into_iter()
.map(|(name, value)| (name, DocumentValue::String(value)))
.collect();
Ok(Command::Add {
file: read_file(invocation)?,
key: invocation.text("key")?.to_string(),
slug: slug.to_string(),
slug_field: slug_field.to_string(),
fields,
ctx: document_context(invocation, None, Vec::new())?,
})
}
fn project_remove(invocation: &ResolvedInvocation) -> Result<Command, CliStop> {
Ok(Command::Remove {
file: read_file(invocation)?,
key: invocation.text("key")?.to_string(),
slug: invocation.text("slug")?.to_string(),
slug_field: invocation.text("slug_field")?.to_string(),
ctx: document_context(invocation, None, Vec::new())?,
})
}
fn finish_guard(result: Result<PathBuf, guard::GuardError>, emitter: &mut ProcessEmitter) -> u8 {
match result {
Ok(path) => write_raw(emitter, path.as_os_str().as_encoded_bytes()),
Err(err) => emitter.finish(
build_error_event(json_error(err.code(), &err.to_string())),
1,
),
}
}
fn compact_json_line(value: &Value) -> Result<Vec<u8>, CliDocError> {
let mut text = serde_json::to_string(value)
.map_err(|err| CliDocError::runtime("json_serialize_failed", err.to_string()))?;
text.push('\n');
Ok(text.into_bytes())
}
fn parse_embedded_json(text: &str, what: &str) -> Result<Value, CliStop> {
serde_json::from_str::<Value>(text).map_err(|err| {
CliStop::invalid_argument(
&format!("{what} is not valid JSON: {err}"),
"pass valid JSON text, quoted so the shell keeps it as one argument",
)
})
}
fn compute_json(
file: &Path,
key: Option<&str>,
reveal_secret: bool,
fallback: Option<Value>,
ctx: &DocumentContext,
) -> Result<Vec<u8>, CliDocError> {
let input_format = ctx.input_format;
let (root, doc_format) = read_document_input(file, input_format, ctx.max_bytes)?;
let (route, mut value) = match key {
None => (Vec::new(), Value::try_from(root)?),
Some(key) => {
let (route, found) = locate_with_route(&root, key, ctx.addressing(doc_format))?;
let value = match found {
Ok(value) if value.is_null() && fallback.is_some() => {
fallback.unwrap_or(Value::Null)
}
Ok(value) => project_json_node(value, key)?,
Err(err) => {
let err = CliDocError::Document(err);
match fallback {
Some(fallback) if is_addressing_miss(&err) => fallback,
_ => return Err(err),
}
}
};
(route, value)
}
};
if !reveal_secret {
ctx.redactor().redact_in_place_at(&route, &mut value);
}
compact_json_line(&value)
}
fn compute_count(
file: &Path,
key: Option<&str>,
missing_ok: bool,
ctx: &DocumentContext,
) -> Result<Vec<u8>, CliDocError> {
let input_format = ctx.input_format;
let (root, doc_format) = read_document_input(file, input_format, ctx.max_bytes)?;
let target = match key {
None => root,
Some(key) => match get_path(&root, key, ctx.addressing(doc_format)) {
Ok(target) => target,
Err(err) => {
let err = CliDocError::Document(err);
return if missing_ok && is_addressing_miss(&err) {
Ok(b"0".to_vec())
} else {
Err(err)
};
}
},
};
let count = match &target {
DocumentValue::Object(map) => map.len(),
DocumentValue::Array(items) => items.len(),
DocumentValue::Null if missing_ok && key.is_some() => return Ok(b"0".to_vec()),
DocumentValue::Null => return Err(null_container_error(key)),
_ => {
return Err(CliDocError::runtime(
"document_not_container",
format!(
"path `{}` is a scalar; nothing to count; read it with `value`",
key.unwrap_or("<root>")
),
));
}
};
Ok(count.to_string().into_bytes())
}
fn compute_has(file: &Path, key: &str, ctx: &DocumentContext) -> Result<Vec<u8>, CliDocError> {
let input_format = ctx.input_format;
let (root, doc_format) = read_document_input(file, input_format, ctx.max_bytes)?;
let present = match get_path(&root, key, ctx.addressing(doc_format)) {
Ok(_) => true,
Err(err) => {
let err = CliDocError::Document(err);
if is_addressing_miss(&err) {
false
} else {
return Err(err);
}
}
};
Ok(if present {
b"true".to_vec()
} else {
b"false".to_vec()
})
}
fn run_lint(
input: &Path,
resolved: Option<DocumentFormat>,
schema: bool,
violations_only: bool,
max_bytes: u64,
emitter: &mut ProcessEmitter,
) -> u8 {
let effective = resolved
.or_else(|| {
if input == Path::new("-") {
None
} else {
DocumentFormat::detect(input)
}
})
.unwrap_or(DocumentFormat::Json);
let untyped = Some(effective) == DocumentFormat::from_cli_name("dotenv")
|| Some(effective) == DocumentFormat::from_cli_name("ini");
let mut options = LintOptions::new().untyped_text_scalars(untyped);
if schema {
options = options.schema_properties();
}
let mut violations = Vec::new();
let mut advisories = Vec::new();
let mut check = |value: &Value, prefix: &str| {
let mut findings = lint_serialized_value(value, options);
if !prefix.is_empty() {
for finding in &mut findings {
finding.pointer.insert_str(0, prefix);
}
}
violations.extend(findings);
if !violations_only {
advisories.extend(advisories::advisories(value, prefix, schema, untyped));
}
};
if effective == DocumentFormat::Json {
let text = match read_input_or_stdin(input, max_bytes) {
Ok(text) => text,
Err(builder) => return emitter.finish(build_error_event(*builder), 1),
};
let parsed = match parse_json_or_jsonl(&text) {
Ok(parsed) => parsed,
Err(err) => return emit_parse_error(err, emitter),
};
match parsed {
ParsedInput::Single(value) => {
check(&value, "");
}
ParsedInput::Lines(values) => {
for (idx, value) in values.iter().enumerate() {
check(value, &format!("/{}", idx + 1));
}
}
}
} else {
let (value, _doc_format) = match read_document_input(input, Some(effective), max_bytes) {
Ok(pair) => pair,
Err(err) => {
return emitter.finish(build_error_event(document_error_builder(&err)), 1);
}
};
let json_value = match Value::try_from(value) {
Ok(value) => value,
Err(error) => {
let event = build_error_event(json_error(error.code(), &error.redacted_message()));
return emitter.finish(event, 1);
}
};
check(&json_value, "");
}
if violations.is_empty() {
let result =
json_result(json!({"ok": true, "violations": violations, "advisories": advisories}));
emitter.finish(result.build(), 0)
} else {
let error = json_error("lint_failed", "lint failed")
.fields(json!({"violations": violations, "advisories": advisories}));
emitter.finish(build_error_event(error), 1)
}
}
fn run_validate(
input: &Path,
strict: bool,
per_event: bool,
max_bytes: u64,
emitter: &mut ProcessEmitter,
) -> u8 {
let text = match read_input_or_stdin(input, max_bytes) {
Ok(text) => text,
Err(builder) => return emitter.finish(build_error_event(*builder), 1),
};
let parsed = match parse_json_or_jsonl(&text) {
Ok(parsed) => parsed,
Err(err) => return emit_parse_error(err, emitter),
};
let mut findings = Vec::new();
if per_event {
match parsed {
ParsedInput::Single(Value::Array(events)) | ParsedInput::Lines(events) => {
for (idx, event) in events.iter().enumerate() {
validate_one_event(event, strict, &format!("/{idx}"), &mut findings);
}
}
ParsedInput::Single(value) => validate_one_event(&value, strict, "", &mut findings),
}
return emit_validation(findings, emitter);
}
match parsed {
ParsedInput::Single(Value::Array(events)) => {
if let Err(vs) = validate_protocol_stream(&events, strict) {
findings.extend(vs);
}
}
ParsedInput::Single(value) => validate_single_input(value, strict, &mut findings),
ParsedInput::Lines(values) => {
if let Err(vs) = validate_protocol_stream(&values, strict) {
findings.extend(vs);
}
}
}
emit_validation(findings, emitter)
}
fn validate_single_input(value: Value, strict: bool, findings: &mut Vec<ProtocolViolation>) {
let kind = value.get("kind").and_then(Value::as_str);
if matches!(kind, Some("log" | "progress")) {
if let Err(vs) = validate_protocol_stream(&[value], strict) {
findings.extend(vs);
}
return;
}
validate_one_event(&value, strict, "", findings);
}
fn validate_one_event(
value: &Value,
strict: bool,
pointer: &str,
findings: &mut Vec<ProtocolViolation>,
) {
if let Err(mut violation) = validate_protocol_event(value, strict) {
violation.pointer.insert_str(0, pointer);
findings.push(violation);
}
}
fn run_render(
input: &Path,
secret_names: &[String],
max_bytes: u64,
emitter: &mut ProcessEmitter,
) -> u8 {
let format = emitter.format();
let text = match read_input_or_stdin(input, max_bytes) {
Ok(text) => text,
Err(builder) => return emitter.finish(build_error_event(*builder), 1),
};
let parsed = match parse_json_or_jsonl(&text) {
Ok(parsed) => parsed,
Err(err) => return emit_parse_error(err, emitter),
};
let output_options = OutputOptions {
redaction: Redactor::new().secret_names(secret_names.iter().cloned()),
style: PlainStyle::default(),
};
match parsed {
ParsedInput::Single(value) => write_raw(
emitter,
format_value(&value, format, false, &output_options).as_bytes(),
),
ParsedInput::Lines(values) => {
let mut out = String::new();
for (idx, value) in values.iter().enumerate() {
if idx > 0 && is_yaml_format(format) {
out.push_str("---\n");
}
out.push_str(&format_value(value, format, idx > 0, &output_options));
if !out.ends_with('\n') {
out.push('\n');
}
}
write_raw(emitter, out.as_bytes())
}
}
}
#[cfg(feature = "skill")]
fn run_skill_validate(input: &Path, max_bytes: u64, emitter: &mut ProcessEmitter) -> u8 {
let (text, expected_name, display_path) = match read_skill_input(input, max_bytes) {
Ok(value) => value,
Err(builder) => return emitter.finish(build_error_event(*builder), 1),
};
let validation = match expected_name.as_deref() {
Some(name) => agent_first_data::skill::validate_skill_named(&text, name),
None => agent_first_data::skill::validate_skill(&text),
};
let metadata = match validation {
Ok(metadata) => metadata,
Err(error) => {
let event = build_error_event(
json_error("skill_invalid", error.message())
.hint("make SKILL.md front matter conform to the Agent Skills specification"),
);
return emitter.finish(event, 1);
}
};
let event = json_result(json!({
"code": "skill_valid",
"path": display_path,
"name": metadata.name,
"description": metadata.description,
"license": metadata.license,
"compatibility": metadata.compatibility,
"metadata": metadata.metadata,
"allowed_tools": metadata.allowed_tools,
"disable_model_invocation": metadata.disable_model_invocation,
"user_invocable": metadata.user_invocable,
}))
.build();
emitter.finish(event, 0)
}
#[cfg(feature = "skill")]
fn read_skill_input(
input: &Path,
max_bytes: u64,
) -> Result<(String, Option<String>, String), Box<ErrorBuilder>> {
if input == Path::new("-") {
return read_input_or_stdin(input, max_bytes)
.map(|text| (text, None, "<stdin>".to_string()));
}
let read_failed = |detail| Box::new(document_error_builder(&DocumentError::IoError { detail }));
let input_metadata = std::fs::symlink_metadata(input)
.map_err(|error| read_failed(format!("failed to inspect {}: {error}", input.display())))?;
if input_metadata.file_type().is_symlink() {
return Err(read_failed(format!(
"refusing to validate symlinked skill input at {}",
input.display()
)));
}
let (skill_path, expected_name) = if input_metadata.is_dir() {
let name = path_file_name(input).map_err(read_failed)?;
(input.join("SKILL.md"), Some(name))
} else if input_metadata.is_file() {
let expected_name = if input.file_name().and_then(|name| name.to_str()) == Some("SKILL.md")
{
input
.parent()
.map(path_file_name)
.transpose()
.map_err(read_failed)?
} else {
None
};
(input.to_path_buf(), expected_name)
} else {
return Err(read_failed(format!(
"skill input is not a regular file or directory: {}",
input.display()
)));
};
let text = read_cli_file(&skill_path, max_bytes, SymlinkPolicy::NoFollow)?;
Ok((text, expected_name, skill_path.display().to_string()))
}
#[cfg(feature = "skill")]
fn path_file_name(path: &Path) -> Result<String, String> {
let resolved;
let path = if path.file_name().is_some() {
path
} else {
resolved = std::fs::canonicalize(if path.as_os_str().is_empty() {
Path::new(".")
} else {
path
})
.map_err(|error| format!("failed to resolve directory {}: {error}", path.display()))?;
&resolved
};
path.file_name()
.and_then(|name| name.to_str())
.map(str::to_string)
.ok_or_else(|| format!("path has no UTF-8 directory name: {}", path.display()))
}
fn format_value(
value: &Value,
format: OutputFormat,
suppress_yaml_boundary: bool,
output_options: &OutputOptions,
) -> String {
let mut out = render(value, format, output_options);
if suppress_yaml_boundary
&& is_yaml_format(format)
&& let Some(stripped) = out.strip_prefix("---\n")
{
out = stripped.to_string();
}
out
}
fn is_yaml_format(format: OutputFormat) -> bool {
format == OutputFormat::Yaml
}
fn read_input_or_stdin(input: &Path, max_bytes: u64) -> Result<String, Box<ErrorBuilder>> {
if input != Path::new("-") {
return read_cli_file(input, max_bytes, SymlinkPolicy::Follow);
}
let bytes =
read_stdin_capped(max_bytes).map_err(|error| Box::new(document_error_builder(&error)))?;
String::from_utf8(bytes).map_err(|error| {
Box::new(document_error_builder(&DocumentError::IoError {
detail: format!("failed to read stdin: {error}"),
}))
})
}
fn read_cli_file(
path: &Path,
max_bytes: u64,
symlink_policy: SymlinkPolicy,
) -> Result<String, Box<ErrorBuilder>> {
read_capped_file(path, max_bytes, symlink_policy)
.map_err(|error| Box::new(document_error_builder(&error)))
}
fn parse_json_or_jsonl(text: &str) -> Result<ParsedInput, ParseError> {
if text.trim().is_empty() {
return Err(ParseError {
code: "json_parse_failed",
message: "input is empty".to_string(),
hint: Some("provide a JSON value or JSONL stream".to_string()),
line: None,
});
}
match serde_json::from_str::<Value>(text) {
Ok(value) => Ok(ParsedInput::Single(value)),
Err(whole_error) => {
let mut values = Vec::new();
for (idx, line) in text.lines().enumerate() {
if line.trim().is_empty() {
continue;
}
match serde_json::from_str::<Value>(line) {
Ok(value) => values.push(value),
Err(line_error) => {
return Err(ParseError {
code: "jsonl_parse_failed",
message: format!("line {} is not valid JSON: {line_error}", idx + 1),
hint: Some(format!("complete JSON parse failed first: {whole_error}")),
line: Some(idx + 1),
});
}
}
}
if values.is_empty() {
Err(ParseError {
code: "json_parse_failed",
message: whole_error.to_string(),
hint: Some("provide a JSON value or JSONL stream".to_string()),
line: None,
})
} else {
Ok(ParsedInput::Lines(values))
}
}
}
}
fn build_error_event(builder: ErrorBuilder) -> Event {
match builder.build() {
Ok(event) => event,
Err(err) => build_cli_error(&err.to_string(), None),
}
}
fn emit_parse_error(err: ParseError, emitter: &mut ProcessEmitter) -> u8 {
let mut fields = serde_json::Map::new();
if let Some(line) = err.line {
fields.insert("line".to_string(), json!(line));
}
let mut builder = json_error(err.code, &err.message);
if let Some(hint) = err.hint.as_deref() {
builder = builder.hint(hint);
}
builder = builder.fields(Value::Object(fields));
emitter.finish(build_error_event(builder), 1)
}
fn emit_validation(violations: Vec<ProtocolViolation>, emitter: &mut ProcessEmitter) -> u8 {
if violations.is_empty() {
return emitter.finish(json_result(json!({"ok": true, "findings": []})).build(), 0);
}
let findings: Vec<_> = violations
.into_iter()
.map(|v| {
json!({
"rule_id": v.rule, "severity": "error", "pointer": v.pointer, "message": v.message,
})
})
.collect();
let error =
json_error("validation_failed", "validation failed").fields(json!({"findings": findings}));
emitter.finish(build_error_event(error), 1)
}
struct DocumentContext {
input_format: Option<DocumentFormat>,
slug_field: Option<String>,
list_slugs: Option<String>,
secret_names: Vec<String>,
max_bytes: u64,
}
impl DocumentContext {
fn redactor(&self) -> Redactor {
Redactor::new().secret_names(self.secret_names.iter().cloned())
}
fn addressing(&self, format: DocumentFormat) -> Addressing<'_> {
let rule = match self.slug_field.as_deref() {
Some(field) => Some(ArrayRule {
field,
match_kind: MatchKind::Exact,
}),
None => format.array_rule(),
};
Addressing::INDEX_ONLY.with_array_rule(rule)
}
}
enum CliDocError {
Usage(String),
Document(DocumentError),
Runtime { code: &'static str, message: String },
}
impl CliDocError {
fn runtime(code: &'static str, message: impl Into<String>) -> Self {
Self::Runtime {
code,
message: message.into(),
}
}
}
impl From<DocumentError> for CliDocError {
fn from(err: DocumentError) -> Self {
Self::Document(err)
}
}
fn null_container_error(key: Option<&str>) -> CliDocError {
match key.filter(|key| !key.is_empty()) {
Some(key) => CliDocError::runtime(
"document_null_value",
format!("path `{key}` is null; pass --missing-ok to read it as empty"),
),
None => CliDocError::runtime(
"document_not_container",
"the document is empty (its root is null); there are no children",
),
}
}
fn is_null_container(err: &CliDocError) -> bool {
matches!(
err,
CliDocError::Runtime {
code: "document_null_value",
..
}
)
}
fn is_addressing_miss(err: &CliDocError) -> bool {
matches!(err, CliDocError::Document(doc_err) if doc_err.is_address_miss())
}
fn document_error_builder(err: &DocumentError) -> ErrorBuilder {
let builder = json_error(err.code(), &err.redacted_message());
match err.code() {
"document_too_large" => builder.hint("raise the limit with --max-file-bytes BYTES"),
"document_format_unknown" => builder.hint("pass --input-format FORMAT"),
"document_io_failed" if err.redacted_message().ends_with("is not a regular file") => {
builder.hint("pass `-` to read stdin")
}
_ => builder,
}
}
fn document_error_event(err: &CliDocError) -> (Event, u8) {
match err {
CliDocError::Usage(message) => (
build_error_event(json_error("document_usage_error", message)),
2,
),
CliDocError::Document(doc_err) => (build_error_event(document_error_builder(doc_err)), 1),
CliDocError::Runtime { code, message } => (build_error_event(json_error(code, message)), 1),
}
}
fn overwrite_verb(overwrite: BareOverwrite) -> &'static str {
match overwrite {
BareOverwrite::Container(_) => "discard",
BareOverwrite::Scalar(_) => "change",
}
}
fn finish_document(
result: Result<Value, CliDocError>,
ctx: &DocumentContext,
emitter: &mut ProcessEmitter,
) -> u8 {
emitter.set_options(document_output_options(ctx));
match result {
Ok(payload) => emitter.finish(json_result(payload).build(), 0),
Err(err) => {
let (event, code) = document_error_event(&err);
emitter.finish(event, code)
}
}
}
fn finish_raw(
result: Result<Vec<u8>, CliDocError>,
ctx: &DocumentContext,
emitter: &mut ProcessEmitter,
) -> u8 {
match result {
Ok(bytes) => write_raw(emitter, &bytes),
Err(err) => {
emitter.set_options(document_output_options(ctx));
let (event, code) = document_error_event(&err);
emitter.finish(event, code)
}
}
}
fn document_output_options(ctx: &DocumentContext) -> OutputOptions {
OutputOptions {
redaction: ctx.redactor(),
style: PlainStyle::default(),
}
}
fn parse_document_format(name: &str) -> Result<DocumentFormat, String> {
DocumentFormat::from_cli_name(name).ok_or_else(|| {
format!(
"unsupported --input-format `{name}`; expected json, toml, yaml, yml, dotenv, env, \
ini, toml-frontmatter, yaml-frontmatter, markdown, or plist"
)
})
}
fn read_stdin_capped(max_bytes: u64) -> Result<Vec<u8>, DocumentError> {
let mut bytes = Vec::new();
std::io::stdin()
.lock()
.take(max_bytes.saturating_add(1))
.read_to_end(&mut bytes)
.map_err(|error| DocumentError::IoError {
detail: format!("failed to read stdin: {error}"),
})?;
if bytes.len() as u64 > max_bytes {
return Err(DocumentError::TooLarge {
path: "stdin".to_string(),
max_bytes,
});
}
Ok(bytes)
}
fn read_document_input(
file: &Path,
input_format: Option<DocumentFormat>,
max_bytes: u64,
) -> Result<(DocumentValue, DocumentFormat), DocumentError> {
if file == Path::new("-") {
let format = input_format.unwrap_or(DocumentFormat::Json);
let bytes = read_stdin_capped(max_bytes)?;
let doc = Document::from_reader(bytes.as_slice(), format).map_err(|err| match err {
DocumentError::EmptyInput { .. } => DocumentError::EmptyInput {
source: "stdin".to_string(),
},
other => other,
})?;
return Ok((doc.value().clone(), doc.format()));
}
let doc = DocumentFile::open_capped(file, input_format, max_bytes)?;
Ok((doc.value().clone(), doc.format()))
}
fn document_scalar_bytes(value: &DocumentValue, key: &str) -> Result<Vec<u8>, CliDocError> {
let text = match value {
DocumentValue::String(value) => return Ok(value.as_bytes().to_vec()),
DocumentValue::Bool(value) => value.to_string(),
DocumentValue::Integer(value) => value.to_string(),
DocumentValue::Unsigned(value) => value.to_string(),
DocumentValue::Float(value) => {
if !value.is_finite() {
return Err(DocumentError::NonFiniteNumber {
path: key.to_owned(),
}
.into());
}
value.to_string()
}
DocumentValue::Number(text) => return Ok(text.clone().into_bytes()),
DocumentValue::Null => {
return Err(CliDocError::runtime(
"document_null_value",
format!("path `{key}` is null"),
));
}
DocumentValue::Array(_) | DocumentValue::Object(_) => {
return Err(CliDocError::runtime(
"document_not_scalar",
format!(
"path `{key}` is a collection, not a scalar; list its children with `keys` \
or read it whole with `get`"
),
));
}
};
Ok(text.into_bytes())
}
fn secret_path_refused(key: &str) -> CliDocError {
CliDocError::runtime(
"document_secret_redacted",
format!("path `{key}` names a secret; pass --reveal-secret"),
)
}
fn url_value_carries_credentials(target: &DocumentValue, redactor: &Redactor) -> bool {
let Some(text) = target.as_str() else {
return true;
};
if redactor.url(text) != text {
return true;
}
url_text_carries_credentials(text, redactor, 0)
}
fn url_text_carries_credentials(text: &str, redactor: &Redactor, depth: usize) -> bool {
if depth >= 16 {
return true;
}
let Ok(url) = url::Url::parse(text) else {
return true;
};
if url.password().is_some() {
return true;
}
if url.cannot_be_a_base() && text.contains('@') && url.scheme() != "mailto" {
return true;
}
let fragment_pairs = url
.fragment()
.map(|fragment| url::form_urlencoded::parse(fragment.as_bytes()))
.into_iter()
.flatten();
url.query_pairs()
.chain(fragment_pairs)
.any(|(name, value)| {
redactor.is_secret_name(&name)
|| (url::Url::parse(&value).is_ok()
&& url_text_carries_credentials(&value, redactor, depth + 1))
})
}
fn reject_mutation_dash(file: &Path) -> Result<(), CliDocError> {
if file == Path::new("-") {
return Err(CliDocError::Usage(
"`-` is not a valid FILE for a mutation command; mutation commands never read stdin"
.to_string(),
));
}
Ok(())
}
fn compute_get(
file: &Path,
key: Option<&str>,
ctx: &DocumentContext,
) -> Result<DocumentValue, CliDocError> {
let (root, doc_format) = read_document_input(file, ctx.input_format, ctx.max_bytes)?;
let mut payload = std::collections::BTreeMap::new();
payload.insert(
"code".to_owned(),
DocumentValue::String("document".to_owned()),
);
payload.insert(
"format".to_owned(),
DocumentValue::String(doc_format.cli_name().to_owned()),
);
let value = if let Some(key) = key {
let located = locate(&root, key, ctx.addressing(doc_format))?;
payload.insert("key".to_owned(), DocumentValue::String(key.to_owned()));
located.value.redacted_at(&located.steps, &ctx.redactor())?
} else {
root
};
payload.insert("value".to_owned(), value);
Ok(DocumentValue::Object(payload))
}
fn document_relative_path(prefix: Option<&str>, path: &str) -> String {
match prefix {
Some(prefix) if path.is_empty() => prefix.to_owned(),
Some(prefix) => format!("{prefix}.{path}"),
None => path.to_owned(),
}
}
fn project_json_node(value: &DocumentValue, key: &str) -> Result<Value, DocumentError> {
Value::try_from(value).map_err(|error| match error {
DocumentError::NonFiniteNumber { path } => DocumentError::NonFiniteNumber {
path: document_relative_path(Some(key), &path),
},
error => error,
})
}
fn compute_value(
file: &Path,
key: &str,
reveal_secret: bool,
default: Option<&str>,
ctx: &DocumentContext,
) -> Result<Vec<u8>, CliDocError> {
let input_format = ctx.input_format;
let (root, doc_format) = read_document_input(file, input_format, ctx.max_bytes)?;
scalar_bytes_at(
&root,
key,
reveal_secret,
default,
ctx.addressing(doc_format),
ctx,
)
}
fn compute_values(
file: &Path,
keys: &[String],
reveal_secret: bool,
default: Option<&str>,
missing_ok: bool,
null_separated: bool,
ctx: &DocumentContext,
) -> Result<Vec<u8>, CliDocError> {
let input_format = ctx.input_format;
let (root, doc_format) = read_document_input(file, input_format, ctx.max_bytes)?;
let addressing = ctx.addressing(doc_format);
let missing = if missing_ok {
MissingContainer::Empty
} else {
MissingContainer::Error
};
let mut expanded = Vec::new();
for key in keys {
let paths =
expand_path_pattern(&root, key, addressing, missing).map_err(|err| match err {
DocumentError::NullContainer { path } => null_container_error(Some(&path)),
other => CliDocError::Document(other),
})?;
expanded.extend(paths);
}
let separator: u8 = if null_separated { 0 } else { b'\n' };
let mut out = Vec::new();
for key in &expanded {
let bytes = scalar_bytes_at(&root, key, reveal_secret, default, addressing, ctx)?;
if null_separated && bytes.contains(&0) {
return Err(CliDocError::runtime(
"document_unframeable_value",
format!(
"path `{key}` holds a value containing a NUL byte, which --null output cannot frame; read that path with `value`"
),
));
}
if !null_separated && bytes.contains(&b'\n') {
return Err(CliDocError::runtime(
"document_multiline_value",
format!(
"path `{key}` holds a value containing a newline, which one-per-line output cannot frame; read that path with `value` or pass --null"
),
));
}
out.extend_from_slice(&bytes);
out.push(separator);
}
Ok(out)
}
fn scalar_bytes_at(
root: &DocumentValue,
key: &str,
reveal_secret: bool,
default: Option<&str>,
addressing: Addressing<'_>,
ctx: &DocumentContext,
) -> Result<Vec<u8>, CliDocError> {
let redactor = ctx.redactor();
let (route, found) = locate_with_route(root, key, addressing)?;
if !reveal_secret && redactor.is_secret_path(&route) {
return Err(secret_path_refused(key));
}
let mut from_default = false;
let mut target = match found {
Ok(value) => value.clone(),
Err(err) => {
let err = CliDocError::Document(err);
if default.is_some() && is_addressing_miss(&err) {
from_default = true;
DocumentValue::String(default.unwrap_or_default().to_string())
} else {
return Err(err);
}
}
};
if target.is_null()
&& let Some(default) = default
{
from_default = true;
target = DocumentValue::String(default.to_string());
}
if target.is_null() {
return Err(CliDocError::runtime(
"document_null_value",
format!("path `{key}` is null; pass --default to choose replacement output"),
));
}
let scrubbed = |raw: Value| redactor.value_at(&route, &raw) != raw;
if !reveal_secret
&& target.is_string()
&& scrubbed(Value::try_from(&target)?)
&& url_value_carries_credentials(&target, &redactor)
{
return Err(CliDocError::runtime(
"document_secret_redacted",
if from_default {
format!(
"--default for `{key}` contains protected URL components; pass --reveal-secret"
)
} else {
format!("path `{key}` contains protected URL components; pass --reveal-secret")
},
));
}
document_scalar_bytes(&target, key)
}
enum EnumerateMode {
Paths,
Keys,
}
fn run_enumerate(
file: &Path,
key: Option<&str>,
ctx: &DocumentContext,
missing_ok: bool,
null_separated: bool,
mode: EnumerateMode,
emitter: &mut ProcessEmitter,
) -> u8 {
match compute_enumerate(file, key, ctx, mode) {
Ok(lines) => {
if lines
.iter()
.any(|line| line.contains('\0') || (!null_separated && line.contains('\n')))
{
let error = CliDocError::runtime(
"document_unframeable_name",
"a child name cannot be represented by the selected output separator; use --null for newline-containing names, or read the parent with get".to_string(),
);
return finish_raw(Err(error), ctx, emitter);
}
let separator: u8 = if null_separated { 0 } else { b'\n' };
let mut bytes = Vec::new();
for line in &lines {
bytes.extend_from_slice(line.as_bytes());
bytes.push(separator);
}
write_raw(emitter, &bytes)
}
Err(err) if missing_ok && (is_addressing_miss(&err) || is_null_container(&err)) => 0,
Err(err) => finish_raw(Err(err), ctx, emitter),
}
}
fn array_slugs(
items: &[DocumentValue],
field: &str,
location: &str,
) -> Result<Vec<String>, CliDocError> {
let mut slugs = Vec::with_capacity(items.len());
for (index, item) in items.iter().enumerate() {
match item {
DocumentValue::Object(map) => match map.get(field) {
Some(DocumentValue::String(slug)) => slugs.push(slug.clone()),
_ => {
return Err(CliDocError::runtime(
"document_type_mismatch",
format!(
"element {index} of `{location}` has no string field `{field}`; \
--slug-field needs a string on every element"
),
));
}
},
_ => {
return Err(CliDocError::runtime(
"document_type_mismatch",
format!(
"element {index} of `{location}` is not an object with a string \
field `{field}`"
),
));
}
}
}
let mut indices_by_slug: std::collections::HashMap<&str, Vec<usize>> =
std::collections::HashMap::new();
for (index, slug) in slugs.iter().enumerate() {
indices_by_slug
.entry(slug.as_str())
.or_default()
.push(index);
}
if let Some(same) = indices_by_slug
.into_values()
.filter(|same| same.len() > 1)
.min_by_key(|same| same[0])
{
let indices = same
.iter()
.map(usize::to_string)
.collect::<Vec<_>>()
.join(", ");
return Err(CliDocError::runtime(
"document_ambiguous_match",
format!(
"field `{field}` repeats a slug {} times in `{location}` at indices {indices}",
same.len()
),
));
}
Ok(slugs)
}
fn compute_enumerate(
file: &Path,
key: Option<&str>,
ctx: &DocumentContext,
mode: EnumerateMode,
) -> Result<Vec<String>, CliDocError> {
let input_format = ctx.input_format;
let (root, doc_format) = read_document_input(file, input_format, ctx.max_bytes)?;
let base_segments: Vec<String> = match key {
Some(key) => parse_path(key)?,
None => Vec::new(),
};
let target = match key {
Some(key) => {
let (route, found) = locate_with_route(&root, key, ctx.addressing(doc_format))?;
if ctx.redactor().is_secret_path(&route) {
return Err(CliDocError::runtime(
"document_secret_redacted",
"secret subtrees cannot be enumerated".to_string(),
));
}
found?.clone()
}
None => root.clone(),
};
let names: Vec<String> = match &target {
DocumentValue::Null => return Err(null_container_error(key)),
DocumentValue::Object(map) => map.keys().cloned().collect(),
DocumentValue::Array(items) => match ctx.list_slugs.as_deref() {
Some(field) => array_slugs(items, field, key.unwrap_or("<root>"))?,
None => (0..items.len()).map(|index| index.to_string()).collect(),
},
_ => {
return Err(CliDocError::runtime(
"document_not_container",
format!(
"path `{}` is a scalar; nothing to enumerate; read it with `value`",
key.unwrap_or("<root>")
),
));
}
};
let mut lines = Vec::with_capacity(names.len());
for name in names {
match mode {
EnumerateMode::Keys => lines.push(name),
EnumerateMode::Paths => {
let mut segments = base_segments.clone();
segments.push(name);
let path = join_path(&segments);
if ctx.list_slugs.is_some()
&& matches!(target, DocumentValue::Array(_))
&& let Some(slug) = segments.last()
{
agent_first_data::document::validate_array_slug(key.unwrap_or("<root>"), slug)
.map_err(CliDocError::Document)?;
}
if path.is_empty() {
return Err(CliDocError::runtime(
"document_unaddressable_key",
"the document root has an empty-string key, which has no path spelling; \
read its children by their own paths, or use `keys`"
.to_string(),
));
}
lines.push(path);
}
}
}
Ok(lines)
}
fn compute_set(
file: &Path,
key: &str,
value: SetValue,
ctx: &DocumentContext,
) -> Result<Value, CliDocError> {
reject_mutation_dash(file)?;
let input_format = ctx.input_format;
let mut doc = DocumentFile::open_capped(file, input_format, ctx.max_bytes)?;
doc.ensure_mutable("set")?;
let new_value = match value {
SetValue::Secret(secret_source) => {
let existing = get_path(doc.value(), key, ctx.addressing(doc.format())).ok();
if let Err(overwrite) = guard_bare_overwrite(existing.as_ref()) {
let inside = match overwrite {
BareOverwrite::Container(_) => "address a field inside it, or ",
BareOverwrite::Scalar(_) => "",
};
return Err(CliDocError::Usage(format!(
"--secret-from would silently {verb} the {found} at `{key}`; \
{inside}unset `{key}` first to replace it deliberately",
verb = overwrite_verb(overwrite),
found = overwrite.found(),
)));
}
DocumentValue::String(read_secret_from(&secret_source)?)
}
SetValue::Typed(value) => value,
SetValue::Bare(raw) => {
let existing = get_path(doc.value(), key, ctx.addressing(doc.format())).ok();
if let Err(overwrite) = guard_bare_overwrite(existing.as_ref()) {
let verb = overwrite_verb(overwrite);
let keep_instruction = if overwrite.found() == "null" {
"pass --value-type null without VALUE to keep it".to_string()
} else {
format!("pass --value-type {} to keep it", overwrite.keeps())
};
return Err(CliDocError::Usage(format!(
"bare VALUE would silently {verb} the {found} at `{key}`; \
{keep_instruction}, or pass --value-type string to replace it explicitly",
found = overwrite.found(),
)));
}
DocumentValue::String(raw)
}
};
let addressing = ctx.addressing(doc.format());
doc.set_addressed(key, new_value, addressing)?;
doc.save()?;
Ok(json!({
"code": "document_set",
"format": doc.format().cli_name(),
"key": key,
"path": doc.path().display().to_string(),
}))
}
fn compute_add(
file: &Path,
key: &str,
slug: &str,
slug_field: &str,
fields: &[(String, DocumentValue)],
ctx: &DocumentContext,
) -> Result<Value, CliDocError> {
reject_mutation_dash(file)?;
let input_format = ctx.input_format;
let mut doc = DocumentFile::open_capped(file, input_format, ctx.max_bytes)?;
doc.add(key, slug, slug_field, fields)?;
doc.save()?;
Ok(json!({
"code": "document_added",
"format": doc.format().cli_name(),
"key": key,
"slug": slug,
"path": doc.path().display().to_string(),
}))
}
fn compute_remove(
file: &Path,
key: &str,
slug: &str,
slug_field: &str,
ctx: &DocumentContext,
) -> Result<Value, CliDocError> {
reject_mutation_dash(file)?;
let input_format = ctx.input_format;
let mut doc = DocumentFile::open_capped(file, input_format, ctx.max_bytes)?;
doc.remove(key, slug, slug_field)?;
doc.save()?;
Ok(json!({
"code": "document_removed",
"format": doc.format().cli_name(),
"key": key,
"slug": slug,
"path": doc.path().display().to_string(),
}))
}
fn compute_unset(file: &Path, key: &str, ctx: &DocumentContext) -> Result<Value, CliDocError> {
reject_mutation_dash(file)?;
let input_format = ctx.input_format;
let mut doc = DocumentFile::open_capped(file, input_format, ctx.max_bytes)?;
let addressing = ctx.addressing(doc.format());
if !doc.unset_addressed(key, addressing)? {
return Err(DocumentError::PathNotFound {
path: key.to_string(),
}
.into());
}
doc.save()?;
Ok(json!({
"code": "document_unset",
"format": doc.format().cli_name(),
"key": key,
"path": doc.path().display().to_string(),
}))
}
fn secret_from_sources() -> SourceSet {
SourceSet::new([
SourceScheme::Stdin,
SourceScheme::Prompt,
SourceScheme::Fd,
SourceScheme::Env,
])
}
fn parse_secret_from(spec: &str) -> Result<ValueSource, CliDocError> {
const EXPECTED: &str = "expected stdin, prompt, fd:<N>, or env:<VAR>";
let sources = secret_from_sources();
let source = sources.parse(spec).map_err(|error| {
let detail = error
.to_string()
.replace(&sources.syntax_summary(), EXPECTED);
CliDocError::Usage(format!("invalid --secret-from; {detail}"))
})?;
if matches!(source, ValueSource::Literal(_)) {
return Err(CliDocError::Usage(format!(
"invalid --secret-from; {EXPECTED}"
)));
}
Ok(source)
}
fn read_secret_from(source: &ValueSource) -> Result<String, CliDocError> {
source
.read_secret()
.map(|secret| secret.expose_secret().to_string())
.map_err(|error| {
CliDocError::runtime("document_secret_source_failed", error.message().to_string())
})
}
#[cfg(test)]
mod cli_registry_tests {
use super::*;
#[test]
fn every_registered_afdata_shape_round_trips() {
let cli = afdata_cli_spec().unwrap();
let fixtures = cli.synthetic_invocations();
assert!(!fixtures.is_empty());
for fixture in fixtures {
let outcome = cli.resolve_from(fixture.argv).unwrap();
let agent_first_data::CliOutcome::Run(invocation) = outcome else {
panic!("synthetic afdata fixture did not resolve to Run");
};
assert_eq!(invocation.combination_id(), fixture.combination_id);
}
}
#[test]
fn every_combination_projects_without_a_read_defect() {
let cli = afdata_cli_spec().unwrap();
let bound = cli.bind_actions(action_handlers()).unwrap();
let results = bound.call_every_combination();
assert!(!results.is_empty());
}
#[test]
fn set_conflicts_are_closed_world_errors() {
let cli = afdata_cli_spec().unwrap();
let error = cli
.resolve_from([
"afdata",
"set",
"data.json",
"key",
"visible",
"--secret-from",
"env:VALUE_SECRET",
])
.unwrap_err();
assert_eq!(
error.rule,
agent_first_data::CliErrorRule::UnregisteredCombination
);
assert!(!error.message.contains("VALUE_SECRET"));
}
#[test]
fn raw_commands_reject_protocol_output_arguments() {
let cli = afdata_cli_spec().unwrap();
for (command, rest) in [
("value", &["data.json", "key"][..]),
("paths", &["data.json"][..]),
("keys", &["data.json"][..]),
("guard", &["path", "/tmp"][..]),
] {
let mut argv = vec!["afdata", command];
argv.extend(rest);
argv.extend(["--output", "json"]);
let error = cli.resolve_from(argv).unwrap_err();
assert_eq!(
error.rule,
agent_first_data::CliErrorRule::UnregisteredCombination
);
}
}
}
#[cfg(all(test, feature = "skill"))]
mod skill_tests {
use super::*;
#[test]
fn parses_and_validates_skill_directory() {
let cli = afdata_cli_spec().unwrap();
let parsed = cli
.resolve_from(["afdata", "skill", "validate", "skills/agent-first-data"])
.unwrap();
let agent_first_data::CliOutcome::Run(invocation) = parsed else {
panic!("expected a resolved skill validation");
};
assert_eq!(invocation.action_id(), "skill_validate");
assert_eq!(invocation.text("input").unwrap(), "skills/agent-first-data");
let loaded = read_skill_input(Path::new("skills/agent-first-data"), 1024 * 1024);
assert!(matches!(
loaded,
Ok((text, Some(expected_name), _))
if expected_name == "agent-first-data"
&& agent_first_data::skill::validate_skill_named(&text, &expected_name).is_ok()
));
}
#[cfg(feature = "skill-admin")]
#[test]
fn resolves_registered_skill_admin_combination() {
let cli = afdata_cli_spec().unwrap();
let parsed = cli
.resolve_from([
"afdata",
"skill",
"status",
"--agent",
"opencode",
"--scope",
"workspace",
])
.unwrap();
let agent_first_data::CliOutcome::Run(invocation) = parsed else {
panic!("expected a resolved skill status");
};
assert_eq!(invocation.combination_id(), "skill-status-agent");
assert_eq!(invocation.action_id(), "skill_status");
assert_eq!(invocation.text("agent").unwrap(), "opencode");
assert_eq!(invocation.text("scope").unwrap(), "workspace");
}
#[cfg(feature = "skill-admin")]
#[test]
fn admin_subcommands_reject_a_validate_only_input_path() {
let cli = afdata_cli_spec().unwrap();
let parsed = cli.resolve_from(["afdata", "skill", "status", "some/path"]);
assert!(parsed.is_err());
}
}