Skip to main content

agent_first_data/
cli.rs

1use crate::output::{OutputFormat, OutputTo};
2use crate::protocol::{
3    BuildError, Event, LogLevel, ProtocolViolation, json_error, json_log, json_progress,
4    json_result, validate_protocol_event,
5};
6use crate::redaction::OutputOptions;
7use serde_json::Value;
8
9// ═══════════════════════════════════════════
10// Public API: CLI Helpers
11// ═══════════════════════════════════════════
12
13/// Parsed and normalized log filters (trimmed, lowercased, deduplicated).
14///
15/// Semantics (a stable contract):
16/// - An **empty** set emits no logs (filtering is opt-in, not opt-out).
17/// - The single wildcard word `"all"` emits every log. (`"*"` is not special —
18///   there is one wildcard spelling, not two.)
19/// - Otherwise a log is emitted iff its lowercased event name **starts with**
20///   any filter string (prefix match).
21///
22/// Consequence to know: a mistyped filter simply matches nothing, so it
23/// silently emits no output — that is the documented behavior, not a bug.
24#[derive(Clone, Debug, Default, PartialEq, Eq)]
25pub struct LogFilters(Vec<String>);
26
27impl LogFilters {
28    /// Create a new LogFilters from filter strings. Entries are trimmed,
29    /// lowercased, and de-duplicated; empty entries are dropped.
30    pub fn new<I, S>(filters: I) -> Self
31    where
32        I: IntoIterator<Item = S>,
33        S: AsRef<str>,
34    {
35        let mut out: Vec<String> = Vec::new();
36        for entry in filters {
37            let s = entry.as_ref().trim().to_ascii_lowercase();
38            if !s.is_empty() && !out.contains(&s) {
39                out.push(s);
40            }
41        }
42        Self(out)
43    }
44
45    /// Check if an event should be logged based on these filters.
46    ///
47    /// Returns `false` if empty (no logs). Returns `true` if the set contains
48    /// the wildcard word `"all"`. Otherwise returns `true` iff the lowercased
49    /// event name starts with any filter (prefix match).
50    pub fn enabled(&self, event: &str) -> bool {
51        if self.0.is_empty() {
52            return false;
53        }
54        let event_lower = event.to_ascii_lowercase();
55        if self.0.contains(&"all".to_string()) {
56            return true;
57        }
58        self.0.iter().any(|filter| event_lower.starts_with(filter))
59    }
60
61    /// Check if this filter set is empty (no filters configured).
62    pub fn is_empty(&self) -> bool {
63        self.0.is_empty()
64    }
65
66    /// Access the underlying filter strings as a slice.
67    pub fn as_slice(&self) -> &[String] {
68        &self.0
69    }
70}
71
72/// Parse `--output` flag value into [`OutputFormat`].
73///
74/// Returns `Err` with a value-safe message suitable for passing to
75/// [`build_cli_error`] on unknown values.
76///
77/// ```
78/// use agent_first_data::{cli_parse_output, OutputFormat};
79/// assert!(matches!(cli_parse_output("json"), Ok(OutputFormat::Json)));
80/// assert!(cli_parse_output("xml").is_err());
81/// ```
82pub fn cli_parse_output(s: &str) -> Result<OutputFormat, String> {
83    s.parse()
84        .map_err(|_| "invalid --output format: expected json, yaml, or plain".to_string())
85}
86
87/// Normalize `--log` flag entries: trim, lowercase, deduplicate, remove empty.
88///
89/// Accepts pre-split entries produced by a caller's comma-list parser.
90///
91/// ```
92/// use agent_first_data::{cli_parse_log_filters, LogFilters};
93/// let f = cli_parse_log_filters(&["Query", " error ", "query"]);
94/// assert_eq!(f, LogFilters::new(["query", "error"]));
95/// ```
96pub fn cli_parse_log_filters<S: AsRef<str>>(entries: &[S]) -> LogFilters {
97    LogFilters::new(entries.iter().map(AsRef::as_ref))
98}
99
100/// Error returned by [`CliEmitter`].
101#[derive(Debug)]
102pub enum CliEmitterError {
103    /// A protocol-validation failure.
104    Validation(ProtocolViolation),
105    /// An event builder rejected its inputs (empty code/message, reserved field).
106    Build(BuildError),
107    /// An emitter lifecycle rule was violated (terminal ordering).
108    Lifecycle(String),
109    /// Writing the event to the underlying writer failed.
110    Write(std::io::Error),
111}
112
113impl std::fmt::Display for CliEmitterError {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        match self {
116            Self::Validation(v) => write!(f, "{v}"),
117            Self::Build(e) => write!(f, "{e}"),
118            Self::Lifecycle(err) => f.write_str(err),
119            Self::Write(err) => write!(f, "failed to write CLI event: {err}"),
120        }
121    }
122}
123
124impl CliEmitterError {
125    /// Return the underlying writer error, when event emission failed during I/O.
126    pub const fn io_error(&self) -> Option<&std::io::Error> {
127        match self {
128            Self::Write(err) => Some(err),
129            Self::Validation(_) | Self::Build(_) | Self::Lifecycle(_) => None,
130        }
131    }
132
133    /// Return the underlying writer error kind, when available.
134    pub fn io_error_kind(&self) -> Option<std::io::ErrorKind> {
135        self.io_error().map(std::io::Error::kind)
136    }
137}
138
139impl std::error::Error for CliEmitterError {
140    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
141        self.io_error()
142            .map(|err| err as &(dyn std::error::Error + 'static))
143    }
144}
145
146impl From<std::io::Error> for CliEmitterError {
147    fn from(err: std::io::Error) -> Self {
148        Self::Write(err)
149    }
150}
151
152impl From<BuildError> for CliEmitterError {
153    fn from(err: BuildError) -> Self {
154        Self::Build(err)
155    }
156}
157
158/// Where a [`CliEmitter`] sends its events, selected by `--output-to`.
159///
160/// The stream an event lands on follows the program's *consumption mode*, not
161/// the event's shape (see the spec's CLI Event Framing):
162///
163/// - [`OutputTo::Split`] (the default) is finite one-shot mode: `result` goes
164///   to `stdout`, while `error`/`progress`/`log` go to `stderr`. `stdout`
165///   therefore carries only successful payloads, so a shell capture or pipe
166///   never mistakes a failure for data.
167/// - [`OutputTo::Stdout`] / [`OutputTo::Stderr`] are event-stream mode: every
168///   event, including `error`, is collapsed onto that one stream so a consumer
169///   reading it in order (`kind`-branching) sees preserved ordering.
170///
171/// A command is an event stream when it produces more than one caller-needed
172/// output over time — a chunked payload, or an address the caller must act on
173/// before the command can report its outcome. Such a command defaults to
174/// [`OutputTo::Stdout`] and rejects an explicit `split`, because splitting it
175/// would strand the caller's data on the diagnostic stream. If a
176/// `kind:"progress"` event carries a payload the caller must read, the command
177/// is an event stream that has not declared itself.
178/// Stateful emitter for structured CLI executions.
179///
180/// The output format, redaction policy, and stream routing are fixed when the
181/// emitter is created. Emitting after a terminal event, emitting a repeated
182/// terminal event, and writer failures all return explicit errors.
183///
184/// Routing follows the consumption mode ([`OutputTo`]):
185///
186/// - [`CliEmitter::finite`] / [`CliEmitter::finite_with`] — finite one-shot:
187///   `result` → the primary writer (stdout), `error`/`progress`/`log` → the
188///   diagnostic writer (stderr). This is the recommended default for a
189///   one-shot CLI, so shell capture and pipelines never treat a failure as data.
190/// - [`CliEmitter::stream`] — event stream: every event, including `error`,
191///   goes to the single writer, preserving interleaved ordering.
192/// - [`CliEmitter::from_output_to`] builds either shape from a parsed
193///   [`OutputTo`] selector.
194pub struct CliEmitter<W: std::io::Write> {
195    writer: W,
196    diagnostic: Option<Box<dyn std::io::Write>>,
197    format: OutputFormat,
198    output_options: OutputOptions,
199    strict_protocol: bool,
200    terminal_emitted: bool,
201}
202
203impl<W: std::io::Write> CliEmitter<W> {
204    /// Create an event-stream emitter: every event goes to `writer`.
205    ///
206    /// Alias for [`CliEmitter::stream`]. Use [`CliEmitter::finite`] for a
207    /// one-shot command that should split `result`/`error` across stdout/stderr.
208    pub fn new(writer: W, format: OutputFormat) -> Self {
209        Self::stream(writer, format)
210    }
211
212    /// Create an event-stream emitter with custom output options.
213    pub fn with_options(writer: W, format: OutputFormat, output_options: OutputOptions) -> Self {
214        Self {
215            writer,
216            diagnostic: None,
217            format,
218            output_options,
219            strict_protocol: false,
220            terminal_emitted: false,
221        }
222    }
223
224    /// Create an event-stream emitter: every event, including `error`, goes to
225    /// the single `writer`, preserving interleaved ordering. Pick this when the
226    /// consumer reads one ordered stream and branches on `kind`.
227    pub fn stream(writer: W, format: OutputFormat) -> Self {
228        Self::with_options(writer, format, OutputOptions::default())
229    }
230
231    /// Create a finite one-shot emitter with explicit sinks: `result` goes to
232    /// `result_writer`, while `error`/`progress`/`log` go to `diagnostic`.
233    pub fn finite_with(
234        result_writer: W,
235        diagnostic: impl std::io::Write + 'static,
236        format: OutputFormat,
237    ) -> Self {
238        Self::finite_with_options(result_writer, diagnostic, format, OutputOptions::default())
239    }
240
241    /// Create a finite one-shot emitter with explicit sinks and output options.
242    pub fn finite_with_options(
243        result_writer: W,
244        diagnostic: impl std::io::Write + 'static,
245        format: OutputFormat,
246        output_options: OutputOptions,
247    ) -> Self {
248        Self {
249            writer: result_writer,
250            diagnostic: Some(Box::new(diagnostic)),
251            format,
252            output_options,
253            strict_protocol: false,
254            terminal_emitted: false,
255        }
256    }
257
258    /// Require the AFDATA recommended strict profile for every emitted event.
259    pub fn with_strict_protocol(mut self) -> Self {
260        self.strict_protocol = true;
261        self
262    }
263
264    /// Emit a typed Event (unified entry for all event kinds).
265    ///
266    /// Accepts only SDK-constructed Event; for dynamic JSON, use emit_validated_value.
267    pub fn emit(&mut self, event: Event) -> Result<(), CliEmitterError> {
268        let value = event.into_value();
269        self.write_event(value)
270    }
271
272    /// Emit and validate dynamic JSON, then apply redaction/formatting/write.
273    ///
274    /// Runs strict validation first, ensuring the dynamic JSON is safe.
275    pub fn emit_validated_value(&mut self, value: Value) -> Result<(), CliEmitterError> {
276        validate_protocol_event(&value, true).map_err(CliEmitterError::Validation)?;
277        self.write_event(value)
278    }
279
280    /// Convenience: build and emit a result event.
281    pub fn emit_result(&mut self, payload: Value) -> Result<(), CliEmitterError> {
282        self.emit(json_result(payload).build())
283    }
284
285    /// Convenience: build and emit an error event.
286    pub fn emit_error(&mut self, code: &str, message: &str) -> Result<(), CliEmitterError> {
287        self.emit(json_error(code, message).build()?)
288    }
289
290    /// Convenience: build and emit a progress event.
291    pub fn emit_progress(&mut self, message: &str) -> Result<(), CliEmitterError> {
292        self.emit(json_progress(serde_json::json!({ "message": message })).build())
293    }
294
295    /// Convenience: build and emit a log event.
296    pub fn emit_log(&mut self, level: LogLevel, message: &str) -> Result<(), CliEmitterError> {
297        self.emit(
298            json_log(serde_json::json!({
299            "level": level.as_str(),
300            "message": message,
301            }))
302            .build(),
303        )
304    }
305
306    /// Emit `event` as the terminal event and resolve the outcome to a process
307    /// exit code, so a one-shot CLI need not hand-roll the emit-then-exit dance.
308    ///
309    /// A successful write returns `success_code`; a broken pipe (the reader hung
310    /// up) returns `0`; any other write or validation failure returns `4`. A
311    /// library never calls `process::exit` itself — return this code from `main`
312    /// (`std::process::ExitCode::from(code)`).
313    pub fn finish(&mut self, event: Event, success_code: u8) -> u8 {
314        match self.emit(event) {
315            Ok(()) => success_code,
316            Err(err) if err.io_error_kind() == Some(std::io::ErrorKind::BrokenPipe) => 0,
317            Err(_) => 4,
318        }
319    }
320
321    /// Convenience over [`CliEmitter::finish`]: emit a `result` payload and
322    /// return `0` on success.
323    ///
324    /// For an error, build it with [`json_error`] (`.hint(…)`, `.retryable(…)`,
325    /// `.field(…)` as needed) and pass the event to [`CliEmitter::finish`] with
326    /// the desired exit code — the builder is the error type, so no separate
327    /// error-emitting convenience is needed.
328    pub fn finish_result(&mut self, payload: Value) -> u8 {
329        self.finish(json_result(payload).build(), 0)
330    }
331
332    /// Access the underlying writer.
333    pub fn into_inner(self) -> W {
334        self.writer
335    }
336
337    fn write_event(&mut self, event: Value) -> Result<(), CliEmitterError> {
338        validate_protocol_event(&event, self.strict_protocol)
339            .map_err(CliEmitterError::Validation)?;
340        let kind = event.get("kind").and_then(Value::as_str).ok_or_else(|| {
341            CliEmitterError::Validation(ProtocolViolation {
342                rule: "kind_invalid",
343                pointer: "/kind".to_string(),
344                message: "event.kind is required".to_string(),
345            })
346        })?;
347        match kind {
348            "log" | "progress" => {
349                if self.terminal_emitted {
350                    return Err(CliEmitterError::Lifecycle(
351                        "cannot emit non-terminal event after terminal event".to_string(),
352                    ));
353                }
354            }
355            "result" | "error" => {
356                if self.terminal_emitted {
357                    return Err(CliEmitterError::Lifecycle(
358                        "cannot emit duplicate terminal event".to_string(),
359                    ));
360                }
361            }
362            _ => {
363                return Err(CliEmitterError::Validation(ProtocolViolation {
364                    rule: "kind_unsupported",
365                    pointer: "/kind".to_string(),
366                    message: format!("unsupported event kind {kind:?}"),
367                }));
368            }
369        }
370        let rendered = crate::formatting::render(&event, self.format, &self.output_options);
371        // Finite mode (a diagnostic sink is present) splits by kind: `result`
372        // stays on the primary writer (stdout), while `error`/`progress`/`log`
373        // are diagnostics routed to the diagnostic writer (stderr). Event-stream
374        // mode (no diagnostic sink) keeps every event on the single writer.
375        match &mut self.diagnostic {
376            Some(diagnostic) if kind != "result" => {
377                write_event_line(diagnostic.as_mut(), &rendered)
378            }
379            _ => write_event_line(&mut self.writer, &rendered),
380        }?;
381        if matches!(kind, "result" | "error") {
382            self.terminal_emitted = true;
383        }
384        Ok(())
385    }
386}
387
388/// Write one rendered event line (payload plus trailing newline) and flush.
389fn write_event_line(writer: &mut dyn std::io::Write, rendered: &str) -> std::io::Result<()> {
390    writer.write_all(rendered.as_bytes())?;
391    writer.write_all(b"\n")?;
392    writer.flush()
393}
394
395// The emitter's own diagnostic sink is the spec's sanctioned exception to the
396// "no ad-hoc stderr" rule (Channel policy): a finite one-shot emitter routes
397// `error`/`progress`/`log` to `std::io::stderr` on purpose, so these wired
398// constructors are allowed to name it directly.
399#[allow(clippy::disallowed_methods)]
400impl CliEmitter<std::io::Stdout> {
401    /// Create a finite one-shot emitter wired to the process streams: `result`
402    /// → `stdout`, `error`/`progress`/`log` → `stderr`. The recommended default
403    /// for a one-shot CLI.
404    pub fn finite(format: OutputFormat) -> Self {
405        Self::finite_with(std::io::stdout(), std::io::stderr(), format)
406    }
407
408    /// Create a finite one-shot emitter wired to the process streams, with
409    /// custom output options.
410    pub fn finite_options(format: OutputFormat, output_options: OutputOptions) -> Self {
411        Self::finite_with_options(std::io::stdout(), std::io::stderr(), format, output_options)
412    }
413}
414
415// Same sanctioned exception as above: `from_output_to` wires the process
416// streams (`std::io::stderr` included) as the emitter's own sinks.
417#[allow(clippy::disallowed_methods)]
418impl CliEmitter<Box<dyn std::io::Write>> {
419    /// Build an emitter from a parsed [`OutputTo`] selector, wired to the
420    /// process streams: `Split` is finite mode (`result` → stdout, everything
421    /// else → stderr); `Stdout`/`Stderr` are event-stream mode onto that stream.
422    pub fn from_output_to(selector: OutputTo, format: OutputFormat) -> Self {
423        Self::from_output_to_with(selector, format, OutputOptions::default())
424    }
425
426    /// As [`CliEmitter::from_output_to`], with custom output options.
427    pub fn from_output_to_with(
428        selector: OutputTo,
429        format: OutputFormat,
430        output_options: OutputOptions,
431    ) -> Self {
432        match selector {
433            OutputTo::Split => Self::finite_with_options(
434                Box::new(std::io::stdout()),
435                std::io::stderr(),
436                format,
437                output_options,
438            ),
439            OutputTo::Stdout => {
440                Self::with_options(Box::new(std::io::stdout()), format, output_options)
441            }
442            OutputTo::Stderr => {
443                Self::with_options(Box::new(std::io::stderr()), format, output_options)
444            }
445        }
446    }
447}
448
449/// Write a raw document to the process stream `selector` names.
450///
451/// Not everything a CLI emits is an event. `--docs` renders a Markdown
452/// reference, `--output plain` help renders a human catalog, and `shell bash`
453/// renders a sourceable script: the consumer is `>` or `source`, so wrapping
454/// them in a protocol envelope would mean `tool --docs > cli.md` wrote JSON.
455/// Every CLI compiled from a registry inherits those outcomes, so something
456/// must write bytes to a process stream — and this is that one place. Without
457/// it each CLI hand-rolls the same dispatch, and they drift: this crate's own
458/// binary treats a broken pipe as success while other tools returned a failure
459/// exit code for it.
460///
461/// A broken pipe is success. `tool --docs | head` closes the reader early, and
462/// reading the first page of a document is not a failure to report.
463///
464/// `Split` writes to stdout: a document is the result, not a diagnostic.
465// The spec's Channel policy sanctions this sink, exactly as it does the
466// emitter's constructors above; `clippy.toml`'s `disallowed-methods` keeps
467// stray writes elsewhere from bypassing this routing.
468#[allow(clippy::disallowed_methods)]
469pub fn write_raw(text: &str, selector: OutputTo) -> std::io::Result<()> {
470    use std::io::Write;
471    let written = match selector {
472        OutputTo::Stderr => std::io::stderr().lock().write_all(text.as_bytes()),
473        OutputTo::Split | OutputTo::Stdout => std::io::stdout().lock().write_all(text.as_bytes()),
474    };
475    forgive_broken_pipe(written)
476}
477
478/// A closed reader is not a failure to report.
479///
480/// Split out so the policy is reachable from a test: piping a document into
481/// `head` is a normal way to read one, and the exit code must not say the tool
482/// failed. Every hand-rolled copy of this write got to decide that separately,
483/// and they did not agree.
484fn forgive_broken_pipe(result: std::io::Result<()>) -> std::io::Result<()> {
485    match result {
486        Err(error) if error.kind() == std::io::ErrorKind::BrokenPipe => Ok(()),
487        other => other,
488    }
489}
490
491/// Build a standard CLI version event: a `kind:"result"` event whose payload is
492/// `{ "code": "version", "name": <name>, "version": <version> }`, plus
493/// `"display_name"`/`"build"` when given. `name` is the short/bin identity
494/// (e.g. `"afdata"`); `display_name` is an optional human-facing product name
495/// (e.g. `"Agent-First Data"`); `build` is an opaque caller-supplied identifier (a git
496/// commit SHA, for example) — its meaning is entirely up to the caller. Both
497/// are `None` when unavailable, and simply absent from the payload.
498pub fn build_cli_version(
499    name: &str,
500    display_name: Option<&str>,
501    version: &str,
502    build: Option<&str>,
503) -> Event {
504    let mut payload = serde_json::json!({
505        "code": "version",
506        "name": name,
507        "version": version,
508    });
509    if let Some(display_name) = display_name {
510        payload["display_name"] = Value::String(display_name.to_string());
511    }
512    if let Some(build) = build {
513        payload["build"] = Value::String(build.to_string());
514    }
515    json_result(payload).build()
516}
517
518/// Render a CLI version response as a protocol-v1 event in `format`.
519pub fn cli_render_version(
520    name: &str,
521    display_name: Option<&str>,
522    version: &str,
523    build: Option<&str>,
524    format: OutputFormat,
525) -> String {
526    let mut rendered = crate::formatting::render(
527        build_cli_version(name, display_name, version, build).as_value(),
528        format,
529        &OutputOptions::default(),
530    );
531    while rendered.ends_with('\n') {
532        rendered.pop();
533    }
534    rendered.push('\n');
535    rendered
536}
537
538#[cfg(test)]
539mod raw_write_tests {
540    use super::forgive_broken_pipe;
541    use std::io::{Error, ErrorKind};
542
543    #[test]
544    fn a_closed_reader_is_success_and_every_other_failure_is_not() {
545        assert!(forgive_broken_pipe(Ok(())).is_ok());
546        assert!(forgive_broken_pipe(Err(Error::from(ErrorKind::BrokenPipe))).is_ok());
547        let denied = forgive_broken_pipe(Err(Error::from(ErrorKind::PermissionDenied)));
548        assert_eq!(
549            denied.map_err(|error| error.kind()),
550            Err(ErrorKind::PermissionDenied)
551        );
552    }
553}