Rust
cargo add agent-first-data
# data/protocol surface only — no CLI compiler, emitter, tracing, or skill admin:
cargo add agent-first-data --no-default-features
Add serde_json to run the examples below (cargo add serde_json).
use agent_first_data::{OutputFormat, OutputOptions, json_result, render};
use serde_json::json;
fn main() {
let event = json_result(json!({
"api_key_secret": "sk-123",
"latency_ms": 1280,
"db_url": "postgres://user:p@ss@db/app?token_secret=abc"
}))
.build();
let options = OutputOptions::default();
println!("{}", render(event.as_value(), OutputFormat::Json, &options));
println!("{}", render(event.as_value(), OutputFormat::Plain, &options));
}
Useful names use Rust casing: render (the single
value × format × options → String entry point), OutputFormat,
OutputOptions, Redactor, redacted_value, redact_url_secrets,
redact_urls_in_text, redact_argv, normalize_utc_offset, is_valid_rfc3339_date,
is_valid_rfc3339_time, is_valid_rfc3339, is_valid_bcp47, CliSpec,
CommandSpec, ArgSpec, Combination, OutputSpec, SourceSet,
SourceScheme, ValueSource, ErrorSpec, lint_value, lint_field_value,
build_afdata_cli, and decode_protocol_event.
Check contracts on the actual serialized data. The default input is typed runtime data.
use agent_first_data::{assert_no_lint_findings, lint_field_value, LintOptions};
use serde_json::json;
assert_no_lint_findings(&json!({"build": "8165", "rows": "1,200"})).unwrap();
let violations = lint_field_value("total_bytes", &json!([12, "8 MB"]), LintOptions::new());
assert_eq!(violations[0].rule_id, "suffix_type_mismatch");
assert_eq!(violations[0].pointer, "/1");
A separately supplied field has the root pointer "". Use lint_value with
LintOptions::new().schema_properties() for schema declarations and
untyped_text_scalars(true) for sources such as INI. afdata lint adds
optional naming and representation suggestions.
The general-purpose features below are on by default; --no-default-features
opts out. Tracing integration is behind tracing:
afdata_tracing::AfdataLayer is composable and accepts an injected writer,
while try_init is the global-subscriber convenience entry point. The whole
CLI surface — CliSpec, help-v2, emitters, and the AFDATA adapter — is behind
cli; skill administration is behind skill-admin; stdout/stderr file
redirection is behind stream-redirect. Unix hardened document opens are behind
libc, which is on by default and is also enabled by stream-redirect.
render and OutputFormat stay available with every feature off.
use agent_first_data::afdata_tracing::{self, LogFormat};
use agent_first_data::Redactor;
use tracing_subscriber::EnvFilter;
fn init_logging() -> Result<(), tracing_subscriber::util::TryInitError> {
afdata_tracing::try_init(
EnvFilter::new("info"),
LogFormat::Json,
Redactor::new().secret_names(["authorization"]),
)
}
For a closed-world CLI, CliMain is the whole lifecycle from main: it binds
one handler per action, resolves argv, runs an optional check, installs
--stdout-file/--stderr-file, answers help, version and docs, and settles
write failures (a closed reader is exit 0, any other failed write exit 4 with
output_write_failed). A handler is the pure step from a ResolvedInvocation
to the program’s own command value, fn(&ResolvedInvocation) -> Result<C, CliStop>; it runs before any sink opens, so a refusal never leaves a redirect
file behind. The command then runs with an emitter built from the resolved
OutputPlan, which is the only route to stdout and stderr, raw bytes
included. run_with_plan is the output half alone, for a plan that came from
somewhere other than the registry.
rust/examples/agent_cli.rs shows the finite-command
case.
Read a resolved invocation only through its typed accessors: text, flag,
integer::<T>, json_text, key_value, source and their optional and
repeated forms. Asking for an id the matched combination does not declare, as
the wrong type, or as an integer type the declared range does not fit is an
InvocationReadError — a defect in the program, reported as
cli_invocation_invalid at exit 1. Put every fixed bound in ArgSpec::range,
so the caller gets a usage error at exit 2 instead.
An ArgSpec can declare indirect values with
sources(SourceSet::config()) (env:NAME, file:PATH[#DOT_PATH], or
file+FORMAT:PATH#DOT_PATH) or SourceSet::stream() (also stdin, fd:N,
and prompt). The parser classifies the value and the invocation hands over
that ValueSource (invocation.source(id)); classification is syntax only,
so nothing has been read. Call ValueSource::read() for an ordinary value or
read_secret() for a credential when the value is actually needed. The latter returns
agent_first_data::value_source::SecretString; its Debug and Display
render ***, and only expose_secret() reveals it at the boundary that needs
the credential. Host-only schemes are declared with host_scheme and read by
the host. Empty strings remain values, reads are capped, and an fd:N read
does not close the caller-owned descriptor.
Canonical flags are --stdout-file and --stderr-file. They redirect the corresponding stream to an append-only file; stdout keeps the selected AFDATA output format, and stderr keeps native diagnostics such as panics and backtraces.
Behavior Notes
- Default redaction replaces every
_secretor configured secret-name subtree with***, including objects and arrays. _urlfields scrub userinfo passwords and secret-named query parameters; surrounding whitespace is trimmed, and internal whitespace or a://that is not the start of a clean URL redacts the whole field.Redactor::url_namesapplies that URL treatment to exact legacy field names and recurses through collections.redact_urls_in_textis the explicit scheme-URL-only prose helper; ordinary structured redaction never scans prose.Redactor::reveal_namesreveals exact structured field names at the selected output boundary. Children still pass through redaction; URL parameters and argv receive no exemption.- A value taken out of its document keeps the names above it through its route:
document::locate(orDocument::locate) returns the node with itsPathSteps — object keys and index-free array element steps — andRedactor::value_at(&steps, &value)renders it exactly as the whole redacted document shows it.Redactor::is_secret_path(&steps)gates printing it raw. Never judge a path by its last segment withis_secret_name. - YAML/plain quote and escape keys as well as values, sort by UTF-16 code unit order, and render nested objects in arrays as canonical JSON.
- Logging records use
kind:"log"with a nestedlogpayload and a separatelevelfield, so error-level logs are not terminal protocol errors. json_log(..).timestamp_now()andjson_progress(..).timestamp_now()write the currenttimestamp_epoch_msinto an object payload;AtomicWrite::new(bytes).mode(0o600).new_only().write(path)iswrite_atomicwith explicit permission bits (Unix) and a refuse-existing option.- Use
AfdataLayer::new(...).with_writer(...)when composing tracing or retaining aStructuredLogHandle; usetry_initwhen a global subscriber is the desired convenience. TracingTRACEmaps to AFDATAdebug; adapter-ownedlevel,message, andtimestamp_epoch_mscannot be overridden by span or event fields. - Build new CLIs from one
CliSpec. Register each command-local argument and every legalCombination, callbuild(), bind exactaction_idhandlers, and resolve toBoundOutcome<R>. Parsing, typed values, output planning, and help-v2 come from the registry; the application retains its command lifetime, redaction options, emission strategy, and exit policy. - The bound run branch owns its handler.
BoundCliSpec::call_every_combination()checks handler argument ids with synthetic invocations and runs every handler. Use it only for pure projections from argv to command values. CliErrorcarries a closed rule plus caller-safemessageandhint— never raw argument values.cli_error_eventrenders it as a strict protocol event;exit_code()is the process status.synthetic_invocations()generates type-correct argv for every combination and every fixedone_ofmember, so the same registered shapes can be round-trip tested independently of help placeholders.- Use
document::DocumentFile::open_cappedfor bounded untrusted reads,create_atomicfor a parsed first commit,decodefor a typed read, andedit_and_validatefor a typed transactional edit. TOML arrays of tables support source-preserving element edits, additions, and removals. Whole-array replacement is refused. - Feature
libcgivesopen_cappednonblocking special-file rejection and atomicSymlinkPolicy::NoFollowon unix. Without it,NoFollowis unsupported and opening a special file may block before its type is checked. ErrorSpec/ErrorCatalogkeep stable public errors separate from runtime diagnostics.lint_value, strict-event assertions, and redaction-canary assertions test final serialized boundaries in-process. Canary assertions inspect successive decoding layers, including JSON escapes around percent-encoded nested URLs.- Protocol payloads are
serde_json::Valuebuilt witharbitrary_precision, so decode and render keep every digit. Cargo unifies that feature across the whole dependency graph, including builds with default features disabled: convert at another serializer’s typed boundary, or it may renderserde_json’s private number marker. stream-redirectenableslibcand provides Unix fd-level redirection where supported. It is stream destination control, not a second AFDATA protocol stream, and it does not implement rotation.
A file value source without #DOT_PATH reads the complete UTF-8 file verbatim,
without document parsing or scalar conversion. An explicit # requires a
non-empty document address. Whole files and stream sources (stdin, fd:N)
read through read() are capped at 16 MiB and preserve trailing whitespace;
credential streams through read_secret() and terminal prompts retain their
1 MiB bound. File sources require regular files. Addressed file sources retain
their typed scalar semantics.
Document API
Document reads and edits for Rust callers. The CLI behaviour they mirror is described in the document workflow reference of the bundled skill.
In Rust, echo one value the same way: Document::locate(path) (or
document::locate with keyed lists) returns the value with its structural
route, Redactor::value_at(&located.steps, &value) renders it as the whole
redacted document shows it, and Redactor::is_secret_path(&located.steps)
gates a raw read. document::expand_path_pattern turns a * pattern into the
concrete paths it names.
For untrusted or secret-bearing paths in Rust, prefer
DocumentFile::open_capped. It opens once, checks regular-file metadata on
that handle, and limits the actual read to one byte beyond the cap so a path
replacement or later growth cannot bypass the limit. Choose
SymlinkPolicy::NoFollow when the final path component must not be a symlink;
on Unix this requires the default-on Cargo feature libc, and
stream-redirect enables that feature automatically. Builds without libc
and platforms without an atomic no-follow open refuse that policy instead of
simulating it with a racy precheck. Without libc, a normal Follow read
retains the single-handle and byte-cap guarantees, but opening a special file
can block before its type is rejected.
In Rust, Document::decode<T>() deserializes the complete document, and
DocumentFile::edit_and_validate<T>(...) stages edits on a clone, decodes the
typed model, then commits once. An edit or type failure rolls back both the
in-memory handle and disk state.
Rust write_atomic(path, bytes), exported at the crate root with
AtomicWrite, AtomicError, and AtomicStep, exposes the same durable atomic file
replacement primitive. Existing regular-file permissions survive, along with
the owner and group on Unix where the process may apply them. A writer that
cannot restore the owner becomes it, as with sed -i; a group that cannot be
restored aborts before installation when the mode grants that group access.
Extended attributes and ACLs are not copied. New files
start owner-only on Unix (Windows inherits the directory ACL), and
symlinks/special files are refused. Unlike the document mutations it does not
check hard links, so a hard-linked target is split from its other links; write
through DocumentFile when that must be refused. Parent directories
must exist; inspect AtomicError::commit_uncertain() after a directory-sync
failure because installation has already happened.
AtomicWrite::new(bytes) is the same write with options: .mode(0o600) sets explicit permission bits on the new file (Unix
only; the method does not exist on Windows, where a new file takes the
directory’s inherited ACL, so a caller writes the cfg(unix) itself), and
.new_only() refuses an existing target of any kind without touching it —
AtomicError::target_exists() is the distinguishable refusal. .write(path)
runs the same sequence, including the directory fsync.
For a Rust library caller’s first write, use
DocumentFile::create_atomic(path, document, CreateOptions::new()). It accepts
only an already-parsed Document, creates a private same-directory temporary
file, fsyncs it, and defaults to no-clobber mode with Unix permissions 0o600.
Choose .unix_mode(...) deliberately when different permissions are required,
and .replace() only when replacing an existing target is intended. The raw
atomic text writer is not public.
Reference
- Formal cross-language contract: spec/agent-first-data.md
- Conformance fixtures: spec/fixtures
- Agent skill: skills/agent-first-data/SKILL.md