agent-first-data 0.41.0

Self-describing data and structured CLI contracts for AI agents — field-name suffixes for units and secrets, the afdata CLI for rendering, validation, path guards, and reading or editing structured documents (JSON, TOML, YAML, dotenv, INI, Markdown), plus libraries for Rust, Go, Python, TypeScript, and Bash.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use super::*;
use serde::Serialize;
use std::collections::{BTreeMap, BTreeSet};

/// Agent-first help-v2 payload.
///
/// `defaults` carries [`CliValue`], which admits finite `f64`, so this model is
/// `PartialEq` but not `Eq`.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct CliHelpV2 {
    pub schema: String,
    pub command_path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub about: Option<String>,
    /// Every legal shape of this command, each complete.
    ///
    /// Help is answered in one round trip rather than two. A second level would
    /// only pay off by omitting something, and what it omitted — the optional
    /// arguments — would be undiscoverable to a caller that stopped at the
    /// first level.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub shapes: Vec<CliShape>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub subcommands: Vec<String>,
    /// Argument meanings. Arguments belong to the command, not to one shape,
    /// so these are stated once rather than per shape.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub notes: BTreeMap<String, String>,
    /// The single public default value for each applicable argument.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub defaults: BTreeMap<String, CliValue>,
}

/// One legal shape of a call.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct CliShape {
    pub id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub about: Option<String>,
    pub usage: String,
}

/// Resolved help response plus its lifecycle output plan.
#[derive(Clone, Debug, PartialEq)]
pub struct ResolvedHelp {
    pub(super) model: CliHelpV2,
    pub(super) output: OutputPlan,
}

impl ResolvedHelp {
    pub fn model(&self) -> &CliHelpV2 {
        &self.model
    }

    pub fn output_plan(&self) -> &OutputPlan {
        &self.output
    }

    pub fn plain(&self) -> String {
        let mut output = String::new();
        if let Some(about) = &self.model.about {
            output.push_str(about);
            output.push_str("\n\n");
        }
        for shape in &self.model.shapes {
            if self.model.shapes.len() > 1 {
                let about = shape.about.as_deref().unwrap_or_default();
                output.push_str(&format!("{}  {about}\n", shape.id));
            }
            output.push_str(&shape.usage);
            output.push('\n');
        }
        // The same facts the structured form carries. Without these the plain
        // rendering was strictly weaker than the JSON it claims to be a human
        // catalog of — no argument meanings, no defaults — so a reader who
        // asked for the readable form got told less.
        if !self.model.notes.is_empty() {
            output.push('\n');
            let width = self
                .model
                .notes
                .keys()
                .map(String::len)
                .max()
                .unwrap_or_default();
            for (name, note) in &self.model.notes {
                output.push_str(&format!("  {name:<width$}  {note}\n"));
            }
        }
        if !self.model.defaults.is_empty() {
            output.push_str("\ndefaults:");
            output.push(' ');
            output.push_str(&describe_defaults(&self.model.defaults, " "));
            output.push('\n');
        }
        for (index, subcommand) in self.model.subcommands.iter().enumerate() {
            output.push_str(if index == 0 {
                "\nmore:    "
            } else {
                "         "
            });
            output.push_str(subcommand);
            output.push('\n');
        }
        output
    }
}

/// Resolved version response plus its lifecycle output plan.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedVersion {
    pub(super) name: String,
    pub(super) version: String,
    pub(super) display_name: Option<String>,
    pub(super) build: Option<String>,
    pub(super) output: OutputPlan,
}

impl ResolvedVersion {
    pub fn output_plan(&self) -> &OutputPlan {
        &self.output
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn version(&self) -> &str {
        &self.version
    }

    pub fn display_name(&self) -> Option<&str> {
        self.display_name.as_deref()
    }

    pub fn build(&self) -> Option<&str> {
        self.build.as_deref()
    }
}

/// The registry asked to describe itself in full.
///
/// Rendering is not the core's business — it carries no Markdown — so this only
/// carries the legal sink plan and registry so the rendering adapter can
/// complete the response without a second registry argument.
#[derive(Clone, Debug, PartialEq)]
pub struct ResolvedDocs {
    pub(super) output: OutputPlan,
    pub(super) registry: BuiltCliSpec,
}

impl ResolvedDocs {
    pub fn registry(&self) -> &BuiltCliSpec {
        &self.registry
    }
    pub fn output_plan(&self) -> &OutputPlan {
        &self.output
    }
}

pub(super) fn combination_usage(
    command: &CommandSpec,
    combination: &Combination,
    command_path: &str,
    hidden_defaults: Option<&BTreeSet<String>>,
    include_output_usage: bool,
) -> (String, BTreeMap<String, String>, BTreeMap<String, CliValue>) {
    let mut parts = vec![command_path.to_string()];
    let mut notes = BTreeMap::new();
    let mut defaults = BTreeMap::new();
    for argument in &command.arguments {
        let id = argument.argument_id.as_str();
        let fixed = combination.fixed.get(id);
        let required = combination.required.iter().any(|candidate| candidate == id);
        let optional = combination.optional.iter().any(|candidate| candidate == id);
        if fixed.is_none() && !required && !optional {
            continue;
        }
        // A fixed argument the caller may leave out: `matches_combination`
        // accepts the argument's own default in place of an explicit value, so
        // rendering it as required would describe a stricter call than the one
        // the parser demands.
        let default_satisfies_fixed = fixed.is_some_and(|fixed| {
            argument
                .default
                .as_ref()
                .and_then(CliValue::as_str)
                .is_some_and(|value| fixed.values().iter().any(|fixed| fixed == value))
        });
        let omittable = optional || default_satisfies_fixed;
        let visible = !argument.sensitive && !hidden_defaults.is_some_and(|ids| ids.contains(id));
        let token = render_argument(argument, fixed, omittable, visible);
        parts.push(token);
        let key = argument_key(argument);
        if let Some(about) = argument.rendered_about() {
            notes.insert(key.clone(), about);
        }
        // A default is only worth stating where leaving the argument out is
        // legal; on a required argument it describes nothing the caller can
        // reach.
        if omittable
            && visible
            && let Some(default) = &argument.default
        {
            defaults.insert(key, default.clone());
        }
    }
    match &combination.output {
        OutputSpec::Raw { file_sinks } => {
            if include_output_usage {
                render_file_sinks(&mut parts, file_sinks);
            }
        }
        OutputSpec::Protocol {
            formats,
            destinations,
            default_format,
            default_destination,
            file_sinks,
            ..
        } => {
            if include_output_usage {
                parts.push(format!("[--output <{}>]", formats.join("|")));
                parts.push(format!("[--output-to <{}>]", destinations.join("|")));
                render_file_sinks(&mut parts, file_sinks);
            }
            if file_sinks.iter().any(|sink| sink == "stdout")
                && let Some(destination) = destinations
                    .iter()
                    .find(|destination| !stdout_file_allowed(destination))
            {
                notes.insert(
                    "--stdout-file".into(),
                    format!("Cannot be combined with --output-to {destination}."),
                );
            }
            defaults.insert(
                "--output".to_string(),
                CliValue::String(default_format.clone()),
            );
            defaults.insert(
                "--output-to".to_string(),
                CliValue::String(default_destination.clone()),
            );
        }
    }
    (parts.join(" "), notes, defaults)
}

/// The same facts are projected into the existing help-v2 fields and the
/// reference, where placement can express the scope directly.
pub(crate) struct HelpCatalog {
    /// Command defaults here apply to every shape.
    pub(crate) model: CliHelpV2,
    pub(crate) shape_defaults: Vec<BTreeMap<String, CliValue>>,
}

impl HelpCatalog {
    pub(super) fn into_help_model(self) -> CliHelpV2 {
        let mut model = self.model;
        let mut conflicting = BTreeSet::new();

        for (shape, defaults) in model.shapes.iter_mut().zip(self.shape_defaults) {
            if defaults.is_empty() {
                continue;
            }

            // The v2 wire contract has no structured field for scoped defaults.
            // Retain typed values at command level when they agree and qualify
            // applicability in the existing one-line shape description.
            let about = shape.about.get_or_insert_with(String::new);
            about.push_str(&format!(
                " (defaults {} when omitted)",
                describe_defaults(&defaults, ", ")
            ));
            for (name, value) in defaults {
                if let Some(previous) = model.defaults.get(&name) {
                    if previous != &value {
                        conflicting.insert(name);
                    }
                } else {
                    model.defaults.insert(name, value);
                }
            }
        }
        model.defaults.retain(|name, _| !conflicting.contains(name));
        model
    }
}

fn describe_defaults(defaults: &BTreeMap<String, CliValue>, separator: &str) -> String {
    defaults
        .iter()
        .map(|(name, value)| format!("{name}={}", display_help_default(value)))
        .collect::<Vec<_>>()
        .join(separator)
}

/// A compact literal for the plain catalog and Markdown reference.
pub(crate) fn display_help_default(value: &CliValue) -> String {
    match value {
        CliValue::Bool(value) => value.to_string(),
        CliValue::String(value) => display_help_string(value),
        CliValue::Json(value) => value.clone(),
        CliValue::I64(value) => value.to_string(),
        CliValue::FiniteF64(value) => value.to_string(),
        CliValue::List(values) => values
            .iter()
            .map(display_help_default)
            .collect::<Vec<_>>()
            .join(","),
    }
}

fn display_help_string(value: &str) -> String {
    if value.is_empty()
        || value.contains(|ch: char| {
            ch.is_whitespace() || ch.is_control() || matches!(ch, ',' | '"' | '\\')
        })
    {
        format!("{value:?}")
    } else {
        value.to_owned()
    }
}

/// The spelling the caller reads in `usage`, and therefore the key `notes` and
/// `defaults` use — an agent looks up a token it just read without having to
/// transform it first.
///
/// It also keeps AFDATA's own convention from misfiring on this crate's help:
/// an argument id like `reveal_secret` names a description, not a secret, and
/// the `_secret` suffix would redact this command's own help text away.
pub(crate) fn argument_key(argument: &ArgSpec) -> String {
    match &argument.syntax {
        ArgSyntax::Long { name } => name.clone(),
        ArgSyntax::Positional { .. } => argument
            .value_name
            .clone()
            .unwrap_or_else(|| argument.argument_id.clone()),
    }
}

fn render_argument(
    argument: &ArgSpec,
    fixed: Option<&FixedValue>,
    optional: bool,
    show_values: bool,
) -> String {
    let value = if argument.value_type == ArgValueType::Flag {
        String::new()
    } else if let Some(fixed) = fixed.filter(|_| show_values) {
        match fixed {
            FixedValue::Value(value) => display_usage_choice(value),
            FixedValue::OneOf { one_of } => render_usage_choices(one_of),
        }
    } else if show_values && !argument.enum_values.is_empty() {
        // A closed value set is the argument's contract. Printing only the
        // placeholder would leave those values registered but undiscoverable —
        // the caller would have to provoke an error to be told what they are.
        render_usage_choices(&argument.enum_values)
    } else {
        format!(
            "<{}>",
            argument
                .value_name
                .as_deref()
                .unwrap_or(argument.argument_id.as_str())
        )
    };
    let mut token = match &argument.syntax {
        ArgSyntax::Long { name } => {
            if value.is_empty() {
                name.clone()
            } else {
                format!("{name} {value}")
            }
        }
        ArgSyntax::Positional { .. } => value,
    };
    if argument.repeatable {
        token.push_str("...");
    }
    if optional {
        token = format!("[{token}]");
    }
    token
}

fn render_usage_choices(values: &[String]) -> String {
    let choices = values
        .iter()
        .map(|value| display_usage_choice(value))
        .collect::<Vec<_>>();
    format!("<{}>", choices.join("|"))
}

fn display_usage_choice(value: &str) -> String {
    if value.contains(['<', '>', '[', ']', '|']) {
        format!("{value:?}")
    } else {
        display_help_string(value)
    }
}

fn render_file_sinks(parts: &mut Vec<String>, file_sinks: &[String]) {
    if file_sinks.iter().any(|sink| sink == "stdout") {
        parts.push("[--stdout-file <PATH>]".to_string());
    }
    if file_sinks.iter().any(|sink| sink == "stderr") {
        parts.push("[--stderr-file <PATH>]".to_string());
    }
}