agent-first-data 0.39.1

A naming convention that lets AI agents understand your data without being told what it means, plus the afdata CLI and a Rust library for reading Markdown structure and safely editing structured JSON, TOML, YAML, dotenv, and INI documents.
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
"""AFDATA CLI helpers — output format parsing, log filter normalization, error building."""

from __future__ import annotations

import enum
import os
import sys
from typing import Any, Iterator

from agent_first_data.format import (
    Event,
    LogLevel,
    OutputOptions,
    json_error,
    json_log,
    json_progress,
    json_result,
    _format_json,
    _format_yaml,
    _format_plain,
    validate_protocol_event,
)


class OutputFormat(enum.Enum):
    """Output format for CLI and pipe/MCP modes."""

    JSON = "json"
    YAML = "yaml"
    PLAIN = "plain"


class OutputTo(enum.Enum):
    """Where a CliEmitter sends its events, selected by ``--output-to``.

    The stream an event lands on follows the program's *consumption mode*, not
    the event's shape (see the spec's CLI Event Framing):

    - ``OutputTo.SPLIT`` (the default) is finite one-shot mode: ``result`` goes
      to stdout, while ``error``/``progress``/``log`` go to stderr. stdout
      therefore carries only successful payloads, so a shell capture or pipe
      never mistakes a failure for data.
    - ``OutputTo.STDOUT`` / ``OutputTo.STDERR`` are event-stream mode: every
      event, including ``error``, is collapsed onto that one stream so a consumer
      reading it in order (branching on ``kind``) sees preserved ordering.
    """

    SPLIT = "split"
    STDOUT = "stdout"
    STDERR = "stderr"

    @classmethod
    def parse(cls, value: str) -> OutputTo:
        """Parse an ``--output-to`` value: ``split`` (default), ``stdout``, or ``stderr``.

        Raises ValueError with a value-safe message suitable for build_cli_error
        on unknown values.

        >>> OutputTo.parse("split")
        <OutputTo.SPLIT: 'split'>
        >>> OutputTo.parse("xml")
        Traceback (most recent call last):
            ...
        ValueError: unsupported --output-to: expected split, stdout, or stderr
        """
        try:
            return cls(value)
        except ValueError:
            raise ValueError(
                "unsupported --output-to: expected split, stdout, or stderr"
            ) from None


class LogFilters:
    """Log event filter matcher."""

    def __init__(self, filters: list[str]) -> None:
        """Initialize with a normalized filter list."""
        self._filters = filters

    def enabled(self, event: str) -> bool:
        """Check if event should be logged.

        An empty filter list returns False (filtering is opt-in). The single
        wildcard word 'all' returns True ('*' is not special — one wildcard
        spelling, not two). Otherwise returns True iff event (lowercased) starts
        with any filter (prefix match); a mistyped filter simply matches nothing
        and silently emits no output.
        """
        if not self._filters:
            return False
        if "all" in self._filters:
            return True
        event_lower = event.lower()
        return any(event_lower.startswith(f) for f in self._filters)

    def __bool__(self) -> bool:
        """True if the filter list is non-empty."""
        return bool(self._filters)

    def __iter__(self) -> Iterator[str]:
        """Iterate over filter entries."""
        return iter(self._filters)

    def __len__(self) -> int:
        """Return the number of filters."""
        return len(self._filters)

    def append(self, item: str) -> None:
        """Append a filter entry."""
        self._filters.append(item)


def cli_parse_output(s: str) -> OutputFormat:
    """Parse the --output flag value into an OutputFormat.

    Raises ValueError with a value-safe message suitable for build_cli_error on
    unknown values.

    >>> cli_parse_output("json")
    <OutputFormat.JSON: 'json'>
    >>> cli_parse_output("xml")
    Traceback (most recent call last):
        ...
    ValueError: invalid --output format: expected json, yaml, or plain
    """
    try:
        return OutputFormat(s)
    except ValueError:
        raise ValueError(
            "invalid --output format: expected json, yaml, or plain"
        ) from None


def cli_parse_log_filters(entries: list[str]) -> LogFilters:
    """Normalize --log flag entries and return a LogFilters matcher.

    Trims, lowercases, deduplicates, and removes empty entries.
    Accepts pre-split entries (e.g. after splitting on comma).

    >>> filters = cli_parse_log_filters(["Query", " error ", "query"])
    >>> list(filters)
    ['query', 'error']
    """
    out: list[str] = []
    for entry in entries:
        s = entry.strip().lower()
        if s and s not in out:
            out.append(s)
    return LogFilters(out)


def render(value: Any, format: OutputFormat, *, options: OutputOptions | None = None) -> str:
    """Render a value as JSON, YAML, or plain (logfmt) text for OutputFormat.

    The single public render entry point: value x format x options -> str.
    JSON ignores PlainStyle and preserves original keys and values after redaction.

    >>> import json
    >>> v = {"code": "ok"}
    >>> render(v, OutputFormat.JSON).startswith('{"code"')
    True
    """
    if format is OutputFormat.YAML:
        return _format_yaml(value, options=options)
    if format is OutputFormat.PLAIN:
        return _format_plain(value, options=options)
    return _format_json(value, options=options)


class CliEmitter:
    """Stateful emitter for structured CLI executions.

    Build one with :meth:`stream`, :meth:`finite` or :meth:`from_output_to`;
    the constructor itself is internal. The output format, redaction policy, and
    stream routing are fixed when the emitter is created. Emitting after a
    terminal event, emitting a repeated terminal event, and writer failures all
    raise.

    Routing follows the consumption mode (:class:`OutputTo`):

    - :meth:`finite` — finite one-shot: ``result`` and raw bytes → the result
      writer (stdout), ``error``/``progress``/``log`` → the diagnostic writer
      (stderr). Shell capture and pipelines never treat a failure as data.
    - :meth:`stream` — event stream: every event, including ``error``, goes to
      the single writer, preserving interleaved ordering.
    - :meth:`from_output_to` picks either mode from a parsed :class:`OutputTo`
      selector, wired to the process streams.

    Options are chained: :meth:`with_options`,
    :meth:`with_strict_protocol`.

    A failed write is raised *and* remembered (the first one only), so whoever
    owns the process exit settles it once with :meth:`exit_code`.
    """

    def __init__(self, writer: Any, diagnostic: Any | None, format: OutputFormat) -> None:
        """Internal: use :meth:`stream`, :meth:`finite` or :meth:`from_output_to`."""
        self._writer = writer
        self._diagnostic = diagnostic
        self._format = format
        self._output_options = OutputOptions()
        self._strict_protocol = False
        self._terminal_emitted = False
        self._write_failure: BaseException | None = None
        self._failure_reported = False
        self._failed_sink: Any = None
        self._write_raised = False

    @classmethod
    def stream(cls, writer: Any, format: OutputFormat, *, options: OutputOptions | None = None) -> CliEmitter:
        """Event-stream mode: every event, including ``error``, goes to ``writer``."""
        return cls(writer, None, format).with_options(options or OutputOptions())

    @classmethod
    def finite(cls, result_writer: Any, diagnostic_writer: Any, format: OutputFormat, *, options: OutputOptions | None = None) -> CliEmitter:
        """Finite one-shot mode: ``result`` and raw bytes go to ``result_writer``,
        ``error``/``progress``/``log`` go to ``diagnostic_writer``.
        """
        return cls(result_writer, diagnostic_writer, format).with_options(options or OutputOptions())

    @classmethod
    def from_output_to(cls, selector: OutputTo, format: OutputFormat, *, options: OutputOptions | None = None) -> CliEmitter:
        """Build either mode from a parsed :class:`OutputTo` selector, wired to
        the process streams: ``SPLIT`` is finite mode (``result`` → stdout,
        everything else → stderr); ``STDOUT``/``STDERR`` are event-stream mode
        onto that one stream.
        """
        if selector is OutputTo.SPLIT:
            return cls.finite(sys.stdout, sys.stderr, format, options=options)
        if selector is OutputTo.STDOUT:
            return cls.stream(sys.stdout, format, options=options)
        if selector is OutputTo.STDERR:
            return cls.stream(sys.stderr, format, options=options)
        raise ValueError(f"unsupported OutputTo selector: {selector!r}")

    def with_options(self, options: OutputOptions) -> CliEmitter:
        """Render with these redaction and formatting options."""
        self._output_options = options
        return self

    def with_strict_protocol(self) -> CliEmitter:
        """Opt this emitter into the AFDATA recommended strict profile."""
        self._strict_protocol = True
        return self

    def _write(self, sink: Any, data: str | bytes) -> None:
        """Write and flush ``data`` to ``sink``, remembering the first failure."""
        self._write_raised = False
        if self._write_failure is not None:
            self._write_raised = True
            raise self._write_failure
        destination = sink
        try:
            if isinstance(data, bytes):
                flush = getattr(sink, "flush", None)
                if flush is not None:
                    flush()
                sink = getattr(sink, "buffer", sink)
            sink.write(data)
            flush = getattr(sink, "flush", None)
            if flush is not None:
                flush()
        except BrokenPipeError as error:
            # A failed flush leaves buffered bytes for interpreter shutdown to
            # retry. Redirect the closed descriptor before exit_code returns 0.
            fileno = getattr(sink, "fileno", None)
            if fileno is not None:
                try:
                    descriptor = fileno()
                except (OSError, ValueError):
                    descriptor = None
                if descriptor is not None:
                    null_descriptor = os.open(os.devnull, os.O_WRONLY)
                    try:
                        os.dup2(null_descriptor, descriptor)
                    finally:
                        os.close(null_descriptor)
            self._failed_sink = destination
            self._record(error)
            raise
        except Exception as error:
            self._failed_sink = destination
            self._record(error)
            raise

    def _record(self, error: BaseException) -> None:
        self._write_raised = True
        if self._write_failure is None:
            self._write_failure = error

    def write_raw(self, data: str | bytes) -> None:
        """Write text or bytes that are not an event to the result writer,
        unchanged, and flush.

        A Markdown reference, a sourceable script or a raw-output command's own
        bytes are consumed by ``>`` or ``source``, so a protocol envelope would
        be wrong. They still go through the emitter, so routing and the exit
        policy for a failed write are the ones every event gets.
        """
        if self._terminal_emitted:
            raise RuntimeError("cannot write raw output after terminal output")
        self._write(self._writer, data)

    def finish_raw(self, data: str | bytes) -> int:
        """Write final raw output and settle its exit code."""
        if self._terminal_emitted:
            return self.exit_code(1)
        try:
            self.write_raw(data)
        except Exception:
            return self.exit_code(1)
        finally:
            self._terminal_emitted = True
        return self.exit_code(0)

    def emit(self, event: Event | dict) -> None:
        """Emit a typed Event or a dict (for compatibility)."""
        if isinstance(event, Event):
            envelope = event.to_dict()
        else:
            envelope = event

        validate_protocol_event(envelope, strict=self._strict_protocol)
        kind = envelope["kind"]
        if kind in ("log", "progress"):
            if self._terminal_emitted:
                raise RuntimeError("cannot emit non-terminal event after terminal event")
        elif kind in ("result", "error"):
            if self._terminal_emitted:
                raise RuntimeError("cannot emit duplicate terminal event")
        else:
            raise ValueError(f"unsupported event kind {kind!r}")

        # Finite mode (a diagnostic sink is present) splits by kind: `result`
        # stays on the primary writer (stdout), while `error`/`progress`/`log`
        # are diagnostics routed to the diagnostic writer (stderr). Event-stream
        # mode (no diagnostic sink) keeps every event on the single writer.
        use_diagnostic = kind != "result" and self._diagnostic is not None
        sink = self._diagnostic if use_diagnostic else self._writer
        # A terminal event that failed to write still ends the command: the
        # caller's outcome is now an output failure, not a second attempt.
        if kind in ("result", "error"):
            self._terminal_emitted = True
        self._write(sink, render(envelope, self._format, options=self._output_options) + "\n")

    def emit_validated_value(self, value: Any) -> None:
        """Emit a dynamic JSON value after strict validation."""
        try:
            validate_protocol_event(value, strict=True)
        except ValueError as e:
            raise ValueError(f"emit_validated_value failed validation: {e}") from e
        self.emit(value)

    def emit_result(self, result: Any) -> None:
        """Emit a result event from a payload."""
        event = json_result(result).build()
        self.emit(event)

    def emit_error(self, code: str, message: str) -> None:
        """Emit an error event with retryable defaulting to False."""
        event = json_error(code, message).build()
        self.emit(event)

    def emit_progress(self, message: str) -> None:
        """Emit a progress event."""
        if not message or not isinstance(message, str):
            raise ValueError("message must be a non-empty string")
        # Use the builder to get default trace: {}
        event = json_progress({"message": message}).build()
        self.emit(event)

    def emit_log(self, level: LogLevel | str, message: str) -> None:
        """Emit a log event."""
        if isinstance(level, str):
            level = LogLevel(level)
        if not message or not isinstance(message, str):
            raise ValueError("message must be a non-empty string")
        event = json_log({"level": level.value, "message": message}).build()
        self.emit(event)

    def finish(self, event: Event | dict, success_code: int) -> int:
        """Emit ``event`` as the terminal event and resolve the process exit
        code: :meth:`exit_code` of ``success_code`` when the event was written
        or only its write failed, of ``1`` when the emitter refused the event
        (a protocol violation or a second terminal event).
        """
        try:
            self.emit(event)
        except Exception:
            return self.exit_code(success_code if self._write_raised else 1)
        return self.exit_code(success_code)

    def exit_code(self, intended: int) -> int:
        """The exit code a command that meant to exit ``intended`` must use,
        given everything this emitter has written.

        No failed write: ``intended``. A closed reader (``BrokenPipeError``,
        ``tool | head``): ``0``, silently. Any other failed write: ``4``, after
        reporting ``output_write_failed`` once as an ``error`` event, on the
        diagnostic writer in finite mode and on ``sys.stderr`` in event-stream
        mode, whose only writer may be the one that failed. That report is best
        effort. A library never calls :func:`sys.exit` itself — return this code
        from the program's entry point.
        """
        if self._write_failure is None:
            return intended
        if isinstance(self._write_failure, BrokenPipeError):
            return 0
        if not self._failure_reported:
            self._failure_reported = True
            self._report_output_write_failed()
        return 4

    def _report_output_write_failed(self) -> None:
        event = json_error("output_write_failed", "could not write command output").build()
        sink = self._diagnostic if self._diagnostic is not None else sys.stderr
        if sink is self._failed_sink:
            return
        try:
            line = render(event.to_dict(), self._format) + "\n"
            sink.write(line)
            flush = getattr(sink, "flush", None)
            if flush is not None:
                flush()
        except Exception:
            pass

    def finish_result(self, payload: Any) -> int:
        """Convenience over :meth:`finish`: emit a ``result`` payload and return
        ``0`` on success.

        Errors have no matching convenience: build the event through the error
        builder — ``json_error(code, message).hint_if_some(hint)...build()``, which
        also carries ``retryable`` and extra fields — and pass it to
        :meth:`finish` with the desired exit code."""
        return self.finish(json_result(payload).build(), 0)



def build_cli_version(
    name: str,
    display_name: str | None,
    version: str,
    build: str | None,
) -> dict:
    """Build a standard CLI version result event.

    The result payload always carries ``code: "version"`` alongside ``name`` and
    ``version``, so structured consumers can dispatch on ``code`` the same way
    they would for any other result shape. ``name`` is the short/bin identity
    (e.g. ``"afdata"``); ``display_name`` is an optional human-facing product
    name (e.g. ``"Agent-First Data"``); ``build`` is an opaque caller-supplied
    identifier (a git commit SHA, for example) — its meaning is entirely up to
    the caller. Both ``display_name`` and ``build`` are ``None`` when
    unavailable, and simply absent from the payload.
    """
    payload: dict[str, Any] = {"code": "version", "name": name, "version": version}
    if display_name is not None:
        payload["display_name"] = display_name
    if build is not None:
        payload["build"] = build
    return json_result(payload).build().to_dict()


def cli_render_version(
    name: str,
    display_name: str | None,
    version: str,
    build: str | None,
    format: OutputFormat,
) -> str:
    """Render a CLI version response as a protocol-v1 event in ``format``.

    There is no conventional ``"<name> <version>"`` path: ``--version`` always
    answers with the structured event (see :func:`build_cli_version`).
    """
    rendered = render(build_cli_version(name, display_name, version, build), format)
    return rendered.rstrip("\n") + "\n"



def build_cli_error(message: str, hint: str | None = None) -> dict | Event:
    """Build a standard CLI parse error event.

    Use when argument parsing fails or a flag value is invalid.
    Print with render(..., OutputFormat.JSON) and exit with code 2.

    Always returns a strict-valid ``kind: "error"`` event with code
    ``"cli_error"``. Never raises: an empty ``message`` is replaced with a
    generic placeholder so the returned event stays strict-valid.

    Returns the event envelope as a dict.
    """
    if not message:
        message = "unspecified error"
    event = json_error("cli_error", message)
    if hint is not None:
        event = event.hint(hint)
    return event.build().to_dict()