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/// [`crate::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/// Stateful emitter for structured CLI executions.
159///
160/// An emitter is one of two consumption modes ([`OutputTo`] selects between
161/// them, see the spec's CLI Event Framing):
162///
163/// - [`CliEmitter::finite`] — finite one-shot: `result` (and raw bytes) go to
164/// the result writer, `error`/`progress`/`log` to the diagnostic writer. The
165/// result stream then carries only successful payloads, so a shell capture
166/// or pipe never mistakes a failure for data.
167/// - [`CliEmitter::stream`] — event stream: every event, including `error`,
168/// goes to the one writer, preserving interleaved ordering for a consumer
169/// that reads in order and branches on `kind`.
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.
176///
177/// [`CliEmitter::from_output_to`] and [`CliEmitter::from_plan`] build either
178/// mode wired to the process streams. Options are chained:
179/// [`with_options`](Self::with_options),
180/// [`with_strict_protocol`](Self::with_strict_protocol).
181///
182/// Emitting after a terminal event or emitting a second terminal event is an
183/// error. A failed write is returned *and* remembered, so whoever owns the
184/// process exit can settle it once with [`exit_code`](Self::exit_code): a
185/// closed reader is success, any other failure is exit 4 with
186/// `output_write_failed` on the diagnostic stream.
187pub struct CliEmitter<W: std::io::Write> {
188 writer: W,
189 diagnostic: Option<Box<dyn std::io::Write>>,
190 write_failure_diagnostic: Option<Box<dyn std::io::Write>>,
191 diagnostic_failed: bool,
192 format: OutputFormat,
193 output_options: OutputOptions,
194 strict_protocol: bool,
195 terminal_emitted: bool,
196 write_failure: Option<std::io::ErrorKind>,
197 failure_reported: bool,
198}
199
200impl<W: std::io::Write> CliEmitter<W> {
201 /// Event-stream mode: every event, including `error`, goes to `writer`.
202 pub fn stream(writer: W, format: OutputFormat) -> Self {
203 Self {
204 writer,
205 diagnostic: None,
206 write_failure_diagnostic: None,
207 diagnostic_failed: false,
208 format,
209 output_options: OutputOptions::default(),
210 strict_protocol: false,
211 terminal_emitted: false,
212 write_failure: None,
213 failure_reported: false,
214 }
215 }
216
217 /// Finite one-shot mode: `result` and raw bytes go to `result_writer`,
218 /// `error`/`progress`/`log` go to `diagnostic`.
219 pub fn finite(
220 result_writer: W,
221 diagnostic: impl std::io::Write + 'static,
222 format: OutputFormat,
223 ) -> Self {
224 let mut emitter = Self::stream(result_writer, format);
225 emitter.diagnostic = Some(Box::new(diagnostic));
226 emitter
227 }
228
229 /// Render with these redaction and formatting options.
230 #[must_use]
231 pub fn with_options(mut self, output_options: OutputOptions) -> Self {
232 self.output_options = output_options;
233 self
234 }
235
236 /// Change the options of an emitter someone else built — the one a CLI
237 /// entry hands to its handler, for a command that decides its redaction
238 /// policy from its own arguments.
239 pub fn set_options(&mut self, output_options: OutputOptions) {
240 self.output_options = output_options;
241 }
242
243 /// Require the AFDATA recommended strict profile for every emitted event.
244 #[must_use]
245 pub fn with_strict_protocol(mut self) -> Self {
246 self.strict_protocol = true;
247 self
248 }
249
250 /// The format events are rendered in.
251 pub const fn format(&self) -> OutputFormat {
252 self.format
253 }
254
255 /// Emit a typed Event (unified entry for all event kinds).
256 ///
257 /// Accepts only SDK-constructed Event; for dynamic JSON, use emit_validated_value.
258 pub fn emit(&mut self, event: Event) -> Result<(), CliEmitterError> {
259 let value = event.into_value();
260 self.write_event(value)
261 }
262
263 /// Emit and validate dynamic JSON, then apply redaction/formatting/write.
264 ///
265 /// Runs strict validation first, ensuring the dynamic JSON is safe.
266 pub fn emit_validated_value(&mut self, value: Value) -> Result<(), CliEmitterError> {
267 validate_protocol_event(&value, true).map_err(CliEmitterError::Validation)?;
268 self.write_event(value)
269 }
270
271 /// Convenience: build and emit a result event.
272 pub fn emit_result(&mut self, payload: Value) -> Result<(), CliEmitterError> {
273 self.emit(json_result(payload).build())
274 }
275
276 /// Convenience: build and emit an error event.
277 pub fn emit_error(&mut self, code: &str, message: &str) -> Result<(), CliEmitterError> {
278 self.emit(json_error(code, message).build()?)
279 }
280
281 /// Convenience: build and emit a progress event.
282 pub fn emit_progress(&mut self, message: &str) -> Result<(), CliEmitterError> {
283 self.emit(json_progress(serde_json::json!({ "message": message })).build())
284 }
285
286 /// Convenience: build and emit a log event.
287 pub fn emit_log(&mut self, level: LogLevel, message: &str) -> Result<(), CliEmitterError> {
288 self.emit(
289 json_log(serde_json::json!({
290 "level": level.as_str(),
291 "message": message,
292 }))
293 .build(),
294 )
295 }
296
297 /// Write bytes that are not an event to the result writer, unchanged.
298 ///
299 /// Not everything a CLI emits is an event. `--docs` renders a Markdown
300 /// reference, `--output plain` help a human catalog, `shell bash` a
301 /// sourceable script, and a raw-output command its own bytes: their
302 /// consumer is `>` or `source`, so a protocol envelope would be wrong. They
303 /// still go through the emitter, so the routing and the exit policy for a
304 /// failed write are the same ones every event gets.
305 pub fn write_raw(&mut self, bytes: &[u8]) -> Result<(), CliEmitterError> {
306 if self.terminal_emitted {
307 return Err(CliEmitterError::Lifecycle(
308 "cannot write raw output after terminal output".to_string(),
309 ));
310 }
311 self.ensure_writable()?;
312 let written = self
313 .writer
314 .write_all(bytes)
315 .and_then(|()| self.writer.flush());
316 self.record(written).map_err(CliEmitterError::Write)
317 }
318
319 /// Write the invocation's final raw bytes and settle its exit code.
320 pub fn finish_raw(&mut self, bytes: &[u8]) -> u8 {
321 let result = self.write_raw(bytes);
322 self.terminal_emitted = true;
323 let intended = u8::from(matches!(result, Err(CliEmitterError::Lifecycle(_))));
324 self.exit_code(intended)
325 }
326
327 /// Emit `event` as the terminal event and resolve the process exit code.
328 ///
329 /// A refused event — a protocol violation or a second terminal event — is
330 /// the command's own failure and returns `1`. Otherwise this is
331 /// [`exit_code`](Self::exit_code) with `success_code`.
332 pub fn finish(&mut self, event: Event, success_code: u8) -> u8 {
333 match self.emit(event) {
334 Ok(()) | Err(CliEmitterError::Write(_)) => self.exit_code(success_code),
335 Err(
336 CliEmitterError::Validation(_)
337 | CliEmitterError::Build(_)
338 | CliEmitterError::Lifecycle(_),
339 ) => self.exit_code(1),
340 }
341 }
342
343 /// Convenience over [`CliEmitter::finish`]: emit a `result` payload and
344 /// return `0` on success.
345 ///
346 /// For an error, build it with [`json_error`] (`.hint(…)`, `.retryable(…)`,
347 /// `.field(…)` as needed) and pass the event to [`CliEmitter::finish`] with
348 /// the desired exit code.
349 pub fn finish_result(&mut self, payload: Value) -> u8 {
350 self.finish(json_result(payload).build(), 0)
351 }
352
353 /// The exit code a command that meant to exit `intended` must use, given
354 /// everything this emitter has written.
355 ///
356 /// No failed write: `intended`. A closed reader (`tool | head`): `0`,
357 /// silently — reading part of the output is not a failure. Any other failed
358 /// write: `4`, after reporting `output_write_failed` once as an `error`
359 /// event — on the diagnostic sink in finite mode, on the process's stderr
360 /// in event-stream mode, whose only writer may be the one that failed. That
361 /// report is best effort; a stderr that cannot be written leaves only the
362 /// code. A library never calls `process::exit` itself — return this from
363 /// `main` (`std::process::ExitCode::from(code)`).
364 pub fn exit_code(&mut self, intended: u8) -> u8 {
365 match self.write_failure {
366 None => intended,
367 Some(std::io::ErrorKind::BrokenPipe) => 0,
368 Some(_) => {
369 if !self.failure_reported {
370 self.failure_reported = true;
371 self.report_output_write_failed();
372 }
373 4
374 }
375 }
376 }
377
378 /// The kind of the first failed write, if any.
379 pub const fn write_failure(&self) -> Option<std::io::ErrorKind> {
380 self.write_failure
381 }
382
383 fn report_output_write_failed(&mut self) {
384 if self.diagnostic_failed {
385 return;
386 }
387 if let Some(diagnostic) = self
388 .diagnostic
389 .as_mut()
390 .or(self.write_failure_diagnostic.as_mut())
391 {
392 let event = crate::cli_afdata::cli_output_write_failed_event();
393 let rendered =
394 crate::formatting::render(event.as_value(), self.format, &OutputOptions::default());
395 let _unwritable = write_event_line(diagnostic.as_mut(), &rendered);
396 }
397 }
398
399 fn ensure_writable(&self) -> Result<(), CliEmitterError> {
400 match self.write_failure {
401 Some(kind) => Err(CliEmitterError::Write(kind.into())),
402 None => Ok(()),
403 }
404 }
405
406 /// Access the underlying writer.
407 pub fn into_inner(self) -> W {
408 self.writer
409 }
410
411 /// Remember the first failed write, and hand the result back.
412 fn record(&mut self, result: std::io::Result<()>) -> std::io::Result<()> {
413 if let Err(error) = &result
414 && self.write_failure.is_none()
415 {
416 self.write_failure = Some(error.kind());
417 }
418 result
419 }
420
421 fn write_event(&mut self, event: Value) -> Result<(), CliEmitterError> {
422 validate_protocol_event(&event, self.strict_protocol)
423 .map_err(CliEmitterError::Validation)?;
424 let kind = event.get("kind").and_then(Value::as_str).ok_or_else(|| {
425 CliEmitterError::Validation(ProtocolViolation {
426 rule: "kind_invalid",
427 pointer: "/kind".to_string(),
428 message: "event.kind is required".to_string(),
429 })
430 })?;
431 match kind {
432 "log" | "progress" => {
433 if self.terminal_emitted {
434 return Err(CliEmitterError::Lifecycle(
435 "cannot emit non-terminal event after terminal event".to_string(),
436 ));
437 }
438 }
439 "result" | "error" => {
440 if self.terminal_emitted {
441 return Err(CliEmitterError::Lifecycle(
442 "cannot emit duplicate terminal event".to_string(),
443 ));
444 }
445 }
446 _ => {
447 return Err(CliEmitterError::Validation(ProtocolViolation {
448 rule: "kind_unsupported",
449 pointer: "/kind".to_string(),
450 message: format!("unsupported event kind {kind:?}"),
451 }));
452 }
453 }
454 self.ensure_writable()?;
455 let terminal = matches!(kind, "result" | "error");
456 let rendered = crate::formatting::render(&event, self.format, &self.output_options);
457 // Finite mode (a diagnostic sink is present) splits by kind: `result`
458 // stays on the primary writer (stdout), while `error`/`progress`/`log`
459 // are diagnostics routed to the diagnostic writer (stderr). Event-stream
460 // mode (no diagnostic sink) keeps every event on the single writer.
461 let written = match &mut self.diagnostic {
462 Some(diagnostic) if kind != "result" => {
463 let written = write_event_line(diagnostic.as_mut(), &rendered);
464 self.diagnostic_failed = written.is_err();
465 written
466 }
467 _ => write_event_line(&mut self.writer, &rendered),
468 };
469 // A terminal event that failed to write still ends the command: the
470 // caller's outcome is now an output failure, not a second attempt.
471 if terminal {
472 self.terminal_emitted = true;
473 }
474 self.record(written)?;
475 Ok(())
476 }
477}
478
479/// Write one rendered event line (payload plus trailing newline) and flush.
480fn write_event_line(writer: &mut dyn std::io::Write, rendered: &str) -> std::io::Result<()> {
481 writer.write_all(rendered.as_bytes())?;
482 writer.write_all(b"\n")?;
483 writer.flush()
484}
485
486// The emitter's own sinks are the spec's sanctioned exception to the "no
487// ad-hoc stderr" rule (Channel policy): these wired constructors name the
488// process streams directly, and `clippy.toml`'s `disallowed-methods` keeps
489// stray writes elsewhere from bypassing this routing.
490#[allow(clippy::disallowed_methods)]
491impl CliEmitter<Box<dyn std::io::Write>> {
492 /// The emitter a resolved plan asks for, strict, wired to the process
493 /// streams. A raw-output plan gets finite mode with JSON diagnostics: its
494 /// bytes go to stdout through [`write_raw`](Self::write_raw), its failures
495 /// to stderr.
496 pub fn from_plan(plan: &crate::cli_spec::OutputPlan) -> Self {
497 Self::from_output_to(
498 plan.output_to().unwrap_or(OutputTo::Split),
499 plan.output_format().unwrap_or(OutputFormat::Json),
500 )
501 .with_strict_protocol()
502 }
503
504 /// Build either mode from a parsed [`OutputTo`] selector, wired to the
505 /// process streams: `Split` is finite mode (`result` → stdout, everything
506 /// else → stderr); `Stdout`/`Stderr` are event-stream mode onto that stream.
507 pub fn from_output_to(selector: OutputTo, format: OutputFormat) -> Self {
508 match selector {
509 OutputTo::Split => Self::finite(Box::new(std::io::stdout()), std::io::stderr(), format),
510 OutputTo::Stdout => {
511 let mut emitter = Self::stream(Box::new(std::io::stdout()), format);
512 emitter.write_failure_diagnostic = Some(Box::new(std::io::stderr()));
513 emitter
514 }
515 OutputTo::Stderr => Self::stream(Box::new(std::io::stderr()), format),
516 }
517 }
518}
519
520/// Build a standard CLI version event: a `kind:"result"` event whose payload is
521/// `{ "code": "version", "name": <name>, "version": <version> }`, plus
522/// `"display_name"`/`"build"` when given. `name` is the short/bin identity
523/// (e.g. `"afdata"`); `display_name` is an optional human-facing product name
524/// (e.g. `"Agent-First Data"`); `build` is an opaque caller-supplied identifier (a git
525/// commit SHA, for example) — its meaning is entirely up to the caller. Both
526/// are `None` when unavailable, and simply absent from the payload.
527pub fn build_cli_version(
528 name: &str,
529 display_name: Option<&str>,
530 version: &str,
531 build: Option<&str>,
532) -> Event {
533 let mut payload = serde_json::json!({
534 "code": "version",
535 "name": name,
536 "version": version,
537 });
538 if let Some(display_name) = display_name {
539 payload["display_name"] = Value::String(display_name.to_string());
540 }
541 if let Some(build) = build {
542 payload["build"] = Value::String(build.to_string());
543 }
544 json_result(payload).build()
545}
546
547/// Render a CLI version response as a protocol-v1 event in `format`.
548pub fn cli_render_version(
549 name: &str,
550 display_name: Option<&str>,
551 version: &str,
552 build: Option<&str>,
553 format: OutputFormat,
554) -> String {
555 let mut rendered = crate::formatting::render(
556 build_cli_version(name, display_name, version, build).as_value(),
557 format,
558 &OutputOptions::default(),
559 );
560 while rendered.ends_with('\n') {
561 rendered.pop();
562 }
563 rendered.push('\n');
564 rendered
565}