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/// Normalization is ASCII-only in every SDK: entries are trimmed of ASCII
16/// whitespace (space, tab, LF, FF, CR) and only ASCII letters are lowercased.
17/// Event names are identifiers, and Unicode case mapping and whitespace sets
18/// differ between runtimes, so a filter must not select different events
19/// depending on which SDK parsed it.
20///
21/// Semantics (a stable contract):
22/// - An **empty** set emits no logs (filtering is opt-in, not opt-out).
23/// - The single wildcard word `"all"` emits every log. (`"*"` is not special —
24/// there is one wildcard spelling, not two.)
25/// - Otherwise a log is emitted iff its lowercased event name **starts with**
26/// any filter string (prefix match).
27///
28/// Consequence to know: a mistyped filter simply matches nothing, so it
29/// silently emits no output — that is the documented behavior, not a bug.
30#[derive(Clone, Debug, Default, PartialEq, Eq)]
31pub struct LogFilters(Vec<String>);
32
33impl LogFilters {
34 /// Create a new LogFilters from filter strings. Entries are trimmed
35 /// (ASCII whitespace), lowercased (ASCII letters), and de-duplicated; empty
36 /// entries are dropped. The set is immutable afterwards.
37 pub fn new<I, S>(filters: I) -> Self
38 where
39 I: IntoIterator<Item = S>,
40 S: AsRef<str>,
41 {
42 let mut out: Vec<String> = Vec::new();
43 for entry in filters {
44 let s = entry
45 .as_ref()
46 .trim_matches(|c| matches!(c, ' ' | '\t' | '\n' | '\x0c' | '\r'))
47 .to_ascii_lowercase();
48 if !s.is_empty() && !out.contains(&s) {
49 out.push(s);
50 }
51 }
52 Self(out)
53 }
54
55 /// Check if an event should be logged based on these filters.
56 ///
57 /// Returns `false` if empty (no logs). Returns `true` if the set contains
58 /// the wildcard word `"all"`. Otherwise returns `true` iff the lowercased
59 /// event name starts with any filter (prefix match).
60 pub fn enabled(&self, event: &str) -> bool {
61 if self.0.is_empty() {
62 return false;
63 }
64 let event_lower = event.to_ascii_lowercase();
65 if self.0.contains(&"all".to_string()) {
66 return true;
67 }
68 self.0.iter().any(|filter| event_lower.starts_with(filter))
69 }
70
71 /// Check if this filter set is empty (no filters configured).
72 pub fn is_empty(&self) -> bool {
73 self.0.is_empty()
74 }
75
76 /// Access the underlying filter strings as a slice.
77 pub fn as_slice(&self) -> &[String] {
78 &self.0
79 }
80}
81
82/// Parse `--output` flag value into [`OutputFormat`].
83///
84/// Returns `Err` with a value-safe message suitable for passing to
85/// [`crate::build_cli_error`] on unknown values.
86///
87/// ```
88/// use agent_first_data::{cli_parse_output, OutputFormat};
89/// assert!(matches!(cli_parse_output("json"), Ok(OutputFormat::Json)));
90/// assert!(cli_parse_output("xml").is_err());
91/// ```
92pub fn cli_parse_output(s: &str) -> Result<OutputFormat, String> {
93 s.parse()
94 .map_err(|_| "invalid --output format: expected json, yaml, or plain".to_string())
95}
96
97/// Normalize `--log` flag entries: trim, lowercase, deduplicate, remove empty.
98///
99/// Accepts pre-split entries produced by a caller's comma-list parser.
100///
101/// ```
102/// use agent_first_data::{cli_parse_log_filters, LogFilters};
103/// let f = cli_parse_log_filters(&["Query", " error ", "query"]);
104/// assert_eq!(f, LogFilters::new(["query", "error"]));
105/// ```
106pub fn cli_parse_log_filters<S: AsRef<str>>(entries: &[S]) -> LogFilters {
107 LogFilters::new(entries.iter().map(AsRef::as_ref))
108}
109
110/// Error returned by [`CliEmitter`].
111#[derive(Debug)]
112pub enum CliEmitterError {
113 /// A protocol-validation failure.
114 Validation(ProtocolViolation),
115 /// An event builder rejected its inputs (empty code/message, reserved field).
116 Build(BuildError),
117 /// An emitter lifecycle rule was violated (terminal ordering).
118 Lifecycle(String),
119 /// Writing the event to the underlying writer failed.
120 Write(std::io::Error),
121}
122
123impl std::fmt::Display for CliEmitterError {
124 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125 match self {
126 Self::Validation(v) => write!(f, "{v}"),
127 Self::Build(e) => write!(f, "{e}"),
128 Self::Lifecycle(err) => f.write_str(err),
129 Self::Write(err) => write!(f, "failed to write CLI event: {err}"),
130 }
131 }
132}
133
134impl CliEmitterError {
135 /// Return the underlying writer error, when event emission failed during I/O.
136 pub const fn io_error(&self) -> Option<&std::io::Error> {
137 match self {
138 Self::Write(err) => Some(err),
139 Self::Validation(_) | Self::Build(_) | Self::Lifecycle(_) => None,
140 }
141 }
142
143 /// Return the underlying writer error kind, when available.
144 pub fn io_error_kind(&self) -> Option<std::io::ErrorKind> {
145 self.io_error().map(std::io::Error::kind)
146 }
147}
148
149impl std::error::Error for CliEmitterError {
150 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
151 self.io_error()
152 .map(|err| err as &(dyn std::error::Error + 'static))
153 }
154}
155
156impl From<std::io::Error> for CliEmitterError {
157 fn from(err: std::io::Error) -> Self {
158 Self::Write(err)
159 }
160}
161
162impl From<BuildError> for CliEmitterError {
163 fn from(err: BuildError) -> Self {
164 Self::Build(err)
165 }
166}
167
168/// Stateful emitter for structured CLI executions.
169///
170/// An emitter is one of two consumption modes ([`OutputTo`] selects between
171/// them, see the spec's CLI Event Framing):
172///
173/// - [`CliEmitter::finite`] — finite one-shot: `result` (and raw bytes) go to
174/// the result writer, `error`/`progress`/`log` to the diagnostic writer. The
175/// result stream then carries only successful payloads, so a shell capture
176/// or pipe never mistakes a failure for data.
177/// - [`CliEmitter::stream`] — event stream: every event, including `error`,
178/// goes to the one writer, preserving interleaved ordering for a consumer
179/// that reads in order and branches on `kind`.
180///
181/// A command is an event stream when it produces more than one caller-needed
182/// output over time — a chunked payload, or an address the caller must act on
183/// before the command can report its outcome. Such a command defaults to
184/// [`OutputTo::Stdout`] and rejects an explicit `split`, because splitting it
185/// would strand the caller's data on the diagnostic stream.
186///
187/// [`CliEmitter::from_output_to`] and [`CliEmitter::from_plan`] build either
188/// mode wired to the process streams. Options are chained:
189/// [`with_options`](Self::with_options),
190/// [`with_strict_protocol`](Self::with_strict_protocol).
191///
192/// Emitting after a terminal event or emitting a second terminal event is an
193/// error. A failed write is returned *and* remembered, so whoever owns the
194/// process exit can settle it once with [`exit_code`](Self::exit_code): a
195/// closed reader is success, any other failure is exit 4 with
196/// `output_write_failed` on the diagnostic stream.
197pub struct CliEmitter<W: std::io::Write> {
198 writer: W,
199 diagnostic: Option<Box<dyn std::io::Write>>,
200 write_failure_diagnostic: Option<Box<dyn std::io::Write>>,
201 diagnostic_failed: bool,
202 format: OutputFormat,
203 output_options: OutputOptions,
204 strict_protocol: bool,
205 terminal_emitted: bool,
206 write_failure: Option<std::io::ErrorKind>,
207 failure_reported: bool,
208}
209
210impl<W: std::io::Write> CliEmitter<W> {
211 /// Event-stream mode: every event, including `error`, goes to `writer`.
212 pub fn stream(writer: W, format: OutputFormat) -> Self {
213 Self {
214 writer,
215 diagnostic: None,
216 write_failure_diagnostic: None,
217 diagnostic_failed: false,
218 format,
219 output_options: OutputOptions::default(),
220 strict_protocol: false,
221 terminal_emitted: false,
222 write_failure: None,
223 failure_reported: false,
224 }
225 }
226
227 /// Finite one-shot mode: `result` and raw bytes go to `result_writer`,
228 /// `error`/`progress`/`log` go to `diagnostic`.
229 pub fn finite(
230 result_writer: W,
231 diagnostic: impl std::io::Write + 'static,
232 format: OutputFormat,
233 ) -> Self {
234 let mut emitter = Self::stream(result_writer, format);
235 emitter.diagnostic = Some(Box::new(diagnostic));
236 emitter
237 }
238
239 /// Render with these redaction and formatting options.
240 #[must_use]
241 pub fn with_options(mut self, output_options: OutputOptions) -> Self {
242 self.output_options = output_options;
243 self
244 }
245
246 /// Change the options of an emitter someone else built — the one a CLI
247 /// entry hands to its handler, for a command that decides its redaction
248 /// policy from its own arguments.
249 pub fn set_options(&mut self, output_options: OutputOptions) {
250 self.output_options = output_options;
251 }
252
253 /// Require the AFDATA recommended strict profile for every emitted event.
254 #[must_use]
255 pub fn with_strict_protocol(mut self) -> Self {
256 self.strict_protocol = true;
257 self
258 }
259
260 /// The format events are rendered in.
261 pub const fn format(&self) -> OutputFormat {
262 self.format
263 }
264
265 /// Emit a typed Event (unified entry for all event kinds).
266 ///
267 /// Accepts only SDK-constructed Event; for dynamic JSON, use emit_validated_value.
268 pub fn emit(&mut self, event: Event) -> Result<(), CliEmitterError> {
269 let value = event.into_value();
270 self.write_event(value)
271 }
272
273 /// Emit and validate dynamic JSON, then apply redaction/formatting/write.
274 ///
275 /// Runs strict validation first, ensuring the dynamic JSON is safe.
276 pub fn emit_validated_value(&mut self, value: Value) -> Result<(), CliEmitterError> {
277 validate_protocol_event(&value, true).map_err(CliEmitterError::Validation)?;
278 self.write_event(value)
279 }
280
281 /// Convenience: build and emit a result event.
282 pub fn emit_result(&mut self, payload: Value) -> Result<(), CliEmitterError> {
283 self.emit(json_result(payload).build())
284 }
285
286 /// Convenience: build and emit an error event.
287 pub fn emit_error(&mut self, code: &str, message: &str) -> Result<(), CliEmitterError> {
288 self.emit(json_error(code, message).build()?)
289 }
290
291 /// Convenience: build and emit a progress event.
292 pub fn emit_progress(&mut self, message: &str) -> Result<(), CliEmitterError> {
293 self.emit(json_progress(serde_json::json!({ "message": message })).build())
294 }
295
296 /// Convenience: build and emit a log event.
297 pub fn emit_log(&mut self, level: LogLevel, message: &str) -> Result<(), CliEmitterError> {
298 self.emit(
299 json_log(serde_json::json!({
300 "level": level.as_str(),
301 "message": message,
302 }))
303 .build(),
304 )
305 }
306
307 /// Write bytes that are not an event to the result writer, unchanged.
308 ///
309 /// Not everything a CLI emits is an event. `--docs` renders a Markdown
310 /// reference, `--output plain` help a human catalog, `shell bash` a
311 /// sourceable script, and a raw-output command its own bytes: their
312 /// consumer is `>` or `source`, so a protocol envelope would be wrong. They
313 /// still go through the emitter, so the routing and the exit policy for a
314 /// failed write are the same ones every event gets.
315 pub fn write_raw(&mut self, bytes: &[u8]) -> Result<(), CliEmitterError> {
316 if self.terminal_emitted {
317 return Err(CliEmitterError::Lifecycle(
318 "cannot write raw output after terminal output".to_string(),
319 ));
320 }
321 self.ensure_writable()?;
322 let written = self
323 .writer
324 .write_all(bytes)
325 .and_then(|()| self.writer.flush());
326 self.record(written).map_err(CliEmitterError::Write)
327 }
328
329 /// Write the invocation's final raw bytes and settle its exit code.
330 pub fn finish_raw(&mut self, bytes: &[u8]) -> u8 {
331 let result = self.write_raw(bytes);
332 self.terminal_emitted = true;
333 let intended = u8::from(matches!(result, Err(CliEmitterError::Lifecycle(_))));
334 self.exit_code(intended)
335 }
336
337 /// Emit `event` as the terminal event and resolve the process exit code.
338 ///
339 /// A refused event — a protocol violation or a second terminal event — is
340 /// the command's own failure and returns `1`. Otherwise this is
341 /// [`exit_code`](Self::exit_code) with `success_code`.
342 pub fn finish(&mut self, event: Event, success_code: u8) -> u8 {
343 match self.emit(event) {
344 Ok(()) | Err(CliEmitterError::Write(_)) => self.exit_code(success_code),
345 Err(
346 CliEmitterError::Validation(_)
347 | CliEmitterError::Build(_)
348 | CliEmitterError::Lifecycle(_),
349 ) => self.exit_code(1),
350 }
351 }
352
353 /// Convenience over [`CliEmitter::finish`]: emit a `result` payload and
354 /// return `0` on success.
355 ///
356 /// For an error, build it with [`json_error`] (`.hint(…)`, `.retryable(…)`,
357 /// `.field(…)` as needed) and pass the event to [`CliEmitter::finish`] with
358 /// the desired exit code.
359 pub fn finish_result(&mut self, payload: Value) -> u8 {
360 self.finish(json_result(payload).build(), 0)
361 }
362
363 /// Emit a result whose source can carry native non-finite numbers.
364 /// YAML preserves these numbers and plain displays their spellings.
365 /// JSON returns a document error before emitting anything.
366 pub fn finish_document_result(
367 &mut self,
368 payload: crate::document::Value,
369 ) -> crate::document::DocumentResult<u8> {
370 use crate::document::Value as DocumentValue;
371
372 let json = payload.project_output(self.format != OutputFormat::Json, &mut Vec::new())?;
373 let event = json_result(json).build().into_value();
374 let original = DocumentValue::Object([("result".into(), payload)].into_iter().collect());
375 let written = self.write_event_with_source(event, Some(&original));
376 Ok(match written {
377 Ok(()) | Err(CliEmitterError::Write(_)) => self.exit_code(0),
378 Err(_) => self.exit_code(1),
379 })
380 }
381
382 /// The exit code a command that meant to exit `intended` must use, given
383 /// everything this emitter has written.
384 ///
385 /// No failed write: `intended`. A closed reader (`tool | head`): `0`,
386 /// silently — reading part of the output is not a failure. Any other failed
387 /// write: `4`, after reporting `output_write_failed` once as an `error`
388 /// event — on the diagnostic sink in finite mode, on the process's stderr
389 /// in event-stream mode, whose only writer may be the one that failed. That
390 /// report is best effort; a stderr that cannot be written leaves only the
391 /// code. A library never calls `process::exit` itself — return this from
392 /// `main` (`std::process::ExitCode::from(code)`).
393 pub fn exit_code(&mut self, intended: u8) -> u8 {
394 match self.write_failure {
395 None => intended,
396 Some(std::io::ErrorKind::BrokenPipe) => 0,
397 Some(_) => {
398 if !self.failure_reported {
399 self.failure_reported = true;
400 self.report_output_write_failed();
401 }
402 4
403 }
404 }
405 }
406
407 /// The kind of the first failed write, if any.
408 pub const fn write_failure(&self) -> Option<std::io::ErrorKind> {
409 self.write_failure
410 }
411
412 fn report_output_write_failed(&mut self) {
413 if self.diagnostic_failed {
414 return;
415 }
416 if let Some(diagnostic) = self
417 .diagnostic
418 .as_mut()
419 .or(self.write_failure_diagnostic.as_mut())
420 {
421 let event = crate::cli_afdata::cli_output_write_failed_event();
422 let rendered =
423 crate::formatting::render(event.as_value(), self.format, &OutputOptions::default());
424 let _unwritable = write_event_line(diagnostic.as_mut(), &rendered);
425 }
426 }
427
428 fn ensure_writable(&self) -> Result<(), CliEmitterError> {
429 match self.write_failure {
430 Some(kind) => Err(CliEmitterError::Write(kind.into())),
431 None => Ok(()),
432 }
433 }
434
435 /// Access the underlying writer.
436 pub fn into_inner(self) -> W {
437 self.writer
438 }
439
440 /// Remember the first failed write, and hand the result back.
441 fn record(&mut self, result: std::io::Result<()>) -> std::io::Result<()> {
442 if let Err(error) = &result
443 && self.write_failure.is_none()
444 {
445 self.write_failure = Some(error.kind());
446 }
447 result
448 }
449
450 fn write_event(&mut self, event: Value) -> Result<(), CliEmitterError> {
451 self.write_event_with_source(event, None)
452 }
453
454 fn write_event_with_source(
455 &mut self,
456 event: Value,
457 source: Option<&crate::document::Value>,
458 ) -> Result<(), CliEmitterError> {
459 validate_protocol_event(&event, self.strict_protocol)
460 .map_err(CliEmitterError::Validation)?;
461 let kind = event.get("kind").and_then(Value::as_str).ok_or_else(|| {
462 CliEmitterError::Validation(ProtocolViolation {
463 rule: "kind_invalid",
464 pointer: "/kind".to_string(),
465 message: "event.kind is required".to_string(),
466 })
467 })?;
468 match kind {
469 "log" | "progress" => {
470 if self.terminal_emitted {
471 return Err(CliEmitterError::Lifecycle(
472 "cannot emit non-terminal event after terminal event".to_string(),
473 ));
474 }
475 }
476 "result" | "error" => {
477 if self.terminal_emitted {
478 return Err(CliEmitterError::Lifecycle(
479 "cannot emit duplicate terminal event".to_string(),
480 ));
481 }
482 }
483 _ => {
484 return Err(CliEmitterError::Validation(ProtocolViolation {
485 rule: "kind_unsupported",
486 pointer: "/kind".to_string(),
487 message: format!("unsupported event kind {kind:?}"),
488 }));
489 }
490 }
491 self.ensure_writable()?;
492 let terminal = matches!(kind, "result" | "error");
493 let rendered = if let (OutputFormat::Yaml, Some(source)) = (self.format, source) {
494 crate::formatting::render_yaml_value(
495 &self.output_options.redaction.value(&event),
496 Some(source),
497 )
498 } else {
499 crate::formatting::render(&event, self.format, &self.output_options)
500 };
501 // Finite mode (a diagnostic sink is present) splits by kind: `result`
502 // stays on the primary writer (stdout), while `error`/`progress`/`log`
503 // are diagnostics routed to the diagnostic writer (stderr). Event-stream
504 // mode (no diagnostic sink) keeps every event on the single writer.
505 let written = match &mut self.diagnostic {
506 Some(diagnostic) if kind != "result" => {
507 let written = write_event_line(diagnostic.as_mut(), &rendered);
508 self.diagnostic_failed = written.is_err();
509 written
510 }
511 _ => write_event_line(&mut self.writer, &rendered),
512 };
513 // A terminal event that failed to write still ends the command: the
514 // caller's outcome is now an output failure, not a second attempt.
515 if terminal {
516 self.terminal_emitted = true;
517 }
518 self.record(written)?;
519 Ok(())
520 }
521}
522
523/// Write one rendered event line (payload plus trailing newline) and flush.
524fn write_event_line(writer: &mut dyn std::io::Write, rendered: &str) -> std::io::Result<()> {
525 writer.write_all(rendered.as_bytes())?;
526 writer.write_all(b"\n")?;
527 writer.flush()
528}
529
530// The emitter's own sinks are the spec's sanctioned exception to the "no
531// ad-hoc stderr" rule (Channel policy): these wired constructors name the
532// process streams directly, and `clippy.toml`'s `disallowed-methods` keeps
533// stray writes elsewhere from bypassing this routing.
534#[allow(clippy::disallowed_methods)]
535impl CliEmitter<Box<dyn std::io::Write>> {
536 /// The emitter a resolved plan asks for, strict, wired to the process
537 /// streams. A raw-output plan gets finite mode with JSON diagnostics: its
538 /// bytes go to stdout through [`write_raw`](Self::write_raw), its failures
539 /// to stderr.
540 pub fn from_plan(plan: &crate::cli_spec::OutputPlan) -> Self {
541 Self::from_output_to(
542 plan.output_to().unwrap_or(OutputTo::Split),
543 plan.output_format().unwrap_or(OutputFormat::Json),
544 )
545 .with_strict_protocol()
546 }
547
548 /// Build either mode from a parsed [`OutputTo`] selector, wired to the
549 /// process streams: `Split` is finite mode (`result` → stdout, everything
550 /// else → stderr); `Stdout`/`Stderr` are event-stream mode onto that stream.
551 pub fn from_output_to(selector: OutputTo, format: OutputFormat) -> Self {
552 match selector {
553 OutputTo::Split => Self::finite(Box::new(std::io::stdout()), std::io::stderr(), format),
554 OutputTo::Stdout => {
555 let mut emitter = Self::stream(Box::new(std::io::stdout()), format);
556 emitter.write_failure_diagnostic = Some(Box::new(std::io::stderr()));
557 emitter
558 }
559 OutputTo::Stderr => Self::stream(Box::new(std::io::stderr()), format),
560 }
561 }
562}
563
564/// Build a standard CLI version event: a `kind:"result"` event whose payload is
565/// `{ "code": "version", "name": <name>, "version": <version> }`, plus
566/// `"display_name"`/`"build"` when given. `name` is the short/bin identity
567/// (e.g. `"afdata"`); `display_name` is an optional human-facing product name
568/// (e.g. `"Agent-First Data"`); `build` is an opaque caller-supplied identifier (a git
569/// commit SHA, for example) — its meaning is entirely up to the caller. Both
570/// are `None` or empty when unavailable, and simply absent from the payload.
571pub fn build_cli_version(
572 name: &str,
573 display_name: Option<&str>,
574 version: &str,
575 build: Option<&str>,
576) -> Event {
577 let mut payload = serde_json::json!({
578 "code": "version",
579 "name": name,
580 "version": version,
581 });
582 if let Some(display_name) = display_name.filter(|text| !text.is_empty()) {
583 payload["display_name"] = Value::String(display_name.to_string());
584 }
585 if let Some(build) = build.filter(|text| !text.is_empty()) {
586 payload["build"] = Value::String(build.to_string());
587 }
588 json_result(payload).build()
589}
590
591/// Render a CLI version response as a protocol-v1 event in `format`.
592pub fn cli_render_version(
593 name: &str,
594 display_name: Option<&str>,
595 version: &str,
596 build: Option<&str>,
597 format: OutputFormat,
598) -> String {
599 let mut rendered = crate::formatting::render(
600 build_cli_version(name, display_name, version, build).as_value(),
601 format,
602 &OutputOptions::default(),
603 );
604 while rendered.ends_with('\n') {
605 rendered.pop();
606 }
607 rendered.push('\n');
608 rendered
609}