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
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
package afdata

import (
	"errors"
	"fmt"
	"io"
	"os"
	"os/signal"
	"strings"
	"syscall"
)

// ═══════════════════════════════════════════
// Public API: CLI Helpers
// ═══════════════════════════════════════════

// OutputFormat represents the output format for CLI and pipe/MCP modes.
type OutputFormat string

const (
	OutputFormatJson  OutputFormat = "json"
	OutputFormatYaml  OutputFormat = "yaml"
	OutputFormatPlain OutputFormat = "plain"
)

// CliParseOutput parses the --output flag value into an OutputFormat.
// Returns a value-safe error suitable for BuildCliError on unknown values.
func CliParseOutput(s string) (OutputFormat, error) {
	switch s {
	case "json":
		return OutputFormatJson, nil
	case "yaml":
		return OutputFormatYaml, nil
	case "plain":
		return OutputFormatPlain, nil
	default:
		return "", errors.New("invalid --output format: expected json, yaml, or plain")
	}
}

// LogFilters represents parsed log filter entries with enabled/prefix matching.
type LogFilters struct {
	filters []string
}

// NewLogFilters normalizes entries into a LogFilters: each is trimmed (ASCII
// whitespace) and lowercased (ASCII letters), duplicates are dropped in
// first-seen order, and empty entries are removed. Event names are identifiers,
// so the rule is the ASCII one in every SDK: Unicode case mapping and
// whitespace sets differ between runtimes, and a filter must select the same
// events whichever SDK parsed it. The zero LogFilters is the empty set.
func NewLogFilters(entries []string) LogFilters {
	var out []string
	for _, entry := range entries {
		s := asciiLower(strings.Trim(entry, " \t\n\f\r"))
		if s == "" {
			continue
		}
		duplicate := false
		for _, existing := range out {
			if existing == s {
				duplicate = true
				break
			}
		}
		if !duplicate {
			out = append(out, s)
		}
	}
	return LogFilters{filters: out}
}

// asciiLower lowercases ASCII letters only, leaving every other byte intact.
func asciiLower(text string) string {
	out := []byte(text)
	for i, c := range out {
		if c >= 'A' && c <= 'Z' {
			out[i] = c + ('a' - 'A')
		}
	}
	return string(out)
}

// CliParseLogFilters normalizes --log flag entries; it is NewLogFilters under
// the name of the flag it serves. Accepts pre-split entries (e.g. after
// strings.Split(flag, ",")).
func CliParseLogFilters(entries []string) LogFilters {
	return NewLogFilters(entries)
}

// Enabled returns true if the event is enabled by the filters.
// An empty filter list returns false (filtering is opt-in); the single wildcard
// word "all" returns true ("*" is not special); otherwise the event is
// prefix-matched (ASCII-lowercased) against each filter, so a mistyped filter matches
// nothing and silently emits no output.
func (lf LogFilters) Enabled(event string) bool {
	if len(lf.filters) == 0 {
		return false
	}
	lower := asciiLower(event)
	for _, filter := range lf.filters {
		if filter == "all" {
			return true
		}
		if strings.HasPrefix(lower, filter) {
			return true
		}
	}
	return false
}

// IsEmpty returns true if no filters are set.
func (lf LogFilters) IsEmpty() bool {
	return len(lf.filters) == 0
}

// Values returns the underlying slice of filter values.
func (lf LogFilters) Values() []string {
	return append([]string(nil), lf.filters...)
}

// Render renders a value as a string in the given format with the given
// options. The single value × format × options → string entry point,
// replacing the former OutputJson/OutputYaml/OutputPlain (+WithOptions) and
// CliOutput/CliOutputWithOptions families. Pass a zero OutputOptions{} for
// defaults.
//
// JSON and YAML are structure-preserving and ignore PlainStyle: they keep
// original keys and values after redaction. Plain (logfmt) honors PlainStyle.
func Render(value any, format OutputFormat, options OutputOptions) string {
	if event, ok := value.(Event); ok {
		value = event.Value()
	}
	switch format {
	case OutputFormatYaml:
		return renderYaml(value, options)
	case OutputFormatPlain:
		return renderPlain(value, options)
	default:
		return renderJSON(value, options)
	}
}

// OutputTo selects where a CliEmitter sends its events, as chosen by the
// --output-to flag. The stream an event lands on follows the program's
// consumption mode, not the event's shape (see the spec's CLI Event Framing):
//
//   - OutputToSplit (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.
//   - OutputToStdout / OutputToStderr 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.
type OutputTo string

const (
	// OutputToSplit is finite one-shot: result → stdout, error/progress/log → stderr.
	OutputToSplit OutputTo = "split"
	// OutputToStdout is event-stream mode: every event onto stdout.
	OutputToStdout OutputTo = "stdout"
	// OutputToStderr is event-stream mode: every event onto stderr.
	OutputToStderr OutputTo = "stderr"
)

// ParseOutputTo parses an --output-to value: split (default), stdout, or stderr.
// It returns a value-safe error suitable for BuildCliError on unknown values.
func ParseOutputTo(value string) (OutputTo, error) {
	switch value {
	case "split":
		return OutputToSplit, nil
	case "stdout":
		return OutputToStdout, nil
	case "stderr":
		return OutputToStderr, nil
	default:
		return "", errors.New("unsupported --output-to: expected split, stdout, or stderr")
	}
}

// CliEmitter is a stateful emitter for structured CLI executions.
//
// It has two consumption modes. Finite mode (NewCliEmitterFinite) routes result
// and raw bytes to the result writer and error/progress/log to the diagnostic
// writer, so a shell capture or pipe never mistakes a failure for data. Stream
// mode (NewCliEmitterStream) sends every event, including error, to the single
// writer, preserving interleaved ordering. NewCliEmitterFromOutputTo picks the
// mode from a parsed OutputTo selector and wires it to the process streams.
// Options are chained: WithOptions, WithStrictProtocol.
//
// A failed write is returned and remembered (the first one only), so whoever
// owns the process exit settles it once with ExitCode.
type CliEmitter struct {
	writer           io.Writer
	diagnostic       io.Writer
	format           OutputFormat
	outputOptions    OutputOptions
	strictProtocol   bool
	terminalEmitted  bool
	writeFailure     error
	diagnosticFailed bool
	failureReported  bool
	// processStderr overrides where an event-stream emitter reports a failed
	// write when it is distinct from the output writer. Tests also set it.
	processStderr io.Writer
}

// emitWriteError marks an emit failure that happened while writing, as
// opposed to an event the emitter refused.
type emitWriteError struct{ err error }

func (e *emitWriteError) Error() string { return fmt.Sprintf("failed to write CLI event: %v", e.err) }
func (e *emitWriteError) Unwrap() error { return e.err }

// NewCliEmitterStream creates an event-stream emitter: every event, including
// error, goes to writer.
func NewCliEmitterStream(writer io.Writer, format OutputFormat) *CliEmitter {
	return &CliEmitter{writer: writer, format: format}
}

// NewCliEmitterFinite creates a finite one-shot emitter: result and raw bytes go
// to resultWriter, while error/progress/log go to diagnostic.
func NewCliEmitterFinite(resultWriter, diagnostic io.Writer, format OutputFormat) *CliEmitter {
	return &CliEmitter{writer: resultWriter, diagnostic: diagnostic, format: format}
}

// NewCliEmitterFromOutputTo builds either mode from a parsed OutputTo selector,
// wired to the process streams: OutputToSplit is finite mode (result → stdout,
// everything else → stderr); OutputToStdout/OutputToStderr are event-stream mode
// onto that one stream.
//
// Because it owns the process streams it also makes a closed reader an
// ordinary write error: by default the Go runtime kills a process that writes
// to a closed stdout or stderr pipe with SIGPIPE, before any code can settle an
// exit status, so this constructor ignores SIGPIPE for the process and the
// write fails with EPIPE, which ExitCode treats as success.
func NewCliEmitterFromOutputTo(selector OutputTo, format OutputFormat) *CliEmitter {
	signal.Ignore(syscall.SIGPIPE)
	switch selector {
	case OutputToStdout:
		emitter := NewCliEmitterStream(os.Stdout, format)
		emitter.processStderr = os.Stderr
		return emitter
	case OutputToStderr:
		return NewCliEmitterStream(os.Stderr, format)
	default: // OutputToSplit
		return NewCliEmitterFinite(os.Stdout, os.Stderr, format)
	}
}

// WithOptions renders with these redaction and formatting options.
func (e *CliEmitter) WithOptions(outputOptions OutputOptions) *CliEmitter {
	e.outputOptions = outputOptions
	return e
}

// WithStrictProtocol opts this emitter into the AFDATA recommended strict
// profile. Emitters otherwise enforce the protocol base schema.
func (e *CliEmitter) WithStrictProtocol() *CliEmitter {
	e.strictProtocol = true
	return e
}

// Emit accepts a typed Event and writes it as one line, routed by kind.
func (e *CliEmitter) Emit(event Event) error {
	return e.writeEvent(event.Value())
}

// EmitValidatedValue accepts untyped JSON and applies strict validation before emitting.
// Use only when dynamic JSON must be accepted. Prefer the typed Emit() for normal use.
func (e *CliEmitter) EmitValidatedValue(value any) error {
	if err := ValidateProtocolEvent(value, true); err != nil {
		return err
	}
	envelope := value.(map[string]any)
	return e.writeEvent(envelope)
}

// writeEvent enforces terminal-lifecycle ordering, then renders and writes the
// event to the stream selected by kind. In finite mode (a diagnostic writer is
// present) result stays on the primary writer while error/progress/log are
// routed to the diagnostic writer; in event-stream mode (no diagnostic writer)
// every event goes to the single writer. Routing follows kind, not exit code.
func (e *CliEmitter) writeEvent(envelope map[string]any) error {
	if err := ValidateProtocolEvent(envelope, e.strictProtocol); err != nil {
		return err
	}
	kind, _ := envelope["kind"].(string)
	switch kind {
	case "log", "progress":
		if e.terminalEmitted {
			return fmt.Errorf("cannot emit non-terminal event after terminal event")
		}
	case "result", "error":
		if e.terminalEmitted {
			return fmt.Errorf("cannot emit duplicate terminal event")
		}
	default:
		return fmt.Errorf("unsupported event kind %q", kind)
	}
	if e.writeFailure != nil {
		return &emitWriteError{err: e.writeFailure}
	}
	sink := e.writer
	useDiagnostic := e.diagnostic != nil && kind != "result"
	if useDiagnostic {
		sink = e.diagnostic
	}
	err := writeAndFlush(sink, []byte(Render(envelope, e.format, e.outputOptions)+"\n"))
	// 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 == "result" || kind == "error" {
		e.terminalEmitted = true
	}
	if err != nil {
		e.diagnosticFailed = useDiagnostic
		return e.record(err)
	}
	return nil
}

// writeAndFlush writes data and flushes the writer when it can flush.
func writeAndFlush(w io.Writer, data []byte) error {
	written, err := w.Write(data)
	if err != nil {
		return err
	}
	if written != len(data) {
		return io.ErrShortWrite
	}
	if f, ok := w.(interface{ Flush() error }); ok {
		return f.Flush()
	}
	return nil
}

// record remembers the first failed write and returns it as an emitWriteError.
func (e *CliEmitter) record(err error) error {
	if e.writeFailure == nil {
		e.writeFailure = err
	}
	return &emitWriteError{err: err}
}

// WriteRaw writes bytes that are not an event to the result writer, unchanged.
//
// Not everything a CLI emits is an event: 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
// the routing and the exit policy for a failed write are the ones every event
// gets.
func (e *CliEmitter) WriteRaw(data []byte) error {
	if e.terminalEmitted {
		return errors.New("cannot write raw output after terminal output")
	}
	if e.writeFailure != nil {
		return &emitWriteError{err: e.writeFailure}
	}
	if err := writeAndFlush(e.writer, data); err != nil {
		return e.record(err)
	}
	return nil
}

// FinishRaw writes the final raw bytes and settles the process exit code.
func (e *CliEmitter) FinishRaw(data []byte) int {
	err := e.WriteRaw(data)
	e.terminalEmitted = true
	if err != nil {
		return e.ExitCode(1)
	}
	return e.ExitCode(0)
}

// EmitResult emits a result event with the given payload.
func (e *CliEmitter) EmitResult(payload any) error {
	event := NewJSONResult(payload).Build()
	return e.Emit(event)
}

// EmitError emits an error event with the given code and message.
func (e *CliEmitter) EmitError(code string, message string) error {
	event, err := NewJSONError(code, message).Build()
	if err != nil {
		return err
	}
	return e.Emit(event)
}

// EmitProgress emits a progress event with the given message.
func (e *CliEmitter) EmitProgress(message string) error {
	event := NewJSONProgress(map[string]any{"message": message}).Build()
	return e.Emit(event)
}

// EmitLog emits a log event with the given level and message.
func (e *CliEmitter) EmitLog(level LogLevel, message string) error {
	payload := map[string]any{"level": string(level), "message": message}
	event := NewJSONLog(payload).Build()
	return e.Emit(event)
}

// Finish emits event (routed by kind exactly like Emit) as the terminal event
// and resolves the process exit code: ExitCode(successCode) when the event was
// written or only its write failed, 1 (through ExitCode) when the emitter
// refused the event (a protocol violation or a second terminal event).
func (e *CliEmitter) Finish(event Event, successCode int) int {
	err := e.Emit(event)
	var writeErr *emitWriteError
	if err == nil || errors.As(err, &writeErr) {
		return e.ExitCode(successCode)
	}
	return e.ExitCode(1)
}

// ExitCode is 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 (EPIPE, or on Windows
// ERROR_BROKEN_PIPE or ERROR_NO_DATA; `tool | head`): 0, silently — reading part of the output is not a failure.
// Any other failed write: 4, after reporting output_write_failed once as an
// error event, on the diagnostic writer in finite mode and on the process's
// stderr in event-stream mode, whose only writer may be the one that failed.
// That report is best effort. A library must not call os.Exit itself: return
// this to the caller.
func (e *CliEmitter) ExitCode(intended int) int {
	switch {
	case e.writeFailure == nil:
		return intended
	case isClosedReader(e.writeFailure):
		return 0
	}
	if !e.failureReported {
		e.failureReported = true
		e.reportOutputWriteFailed()
	}
	return 4
}

func (e *CliEmitter) reportOutputWriteFailed() {
	if e.diagnosticFailed {
		return
	}
	event, err := NewJSONError("output_write_failed", "could not write command output").Build()
	if err != nil {
		return
	}
	sink := e.diagnostic
	if sink == nil {
		sink = e.processStderr
	}
	if sink == nil {
		return
	}
	_ = writeAndFlush(sink, []byte(Render(event.Value(), e.format, OutputOptions{})+"\n"))
}

// FinishResult builds a result event for payload, emits it to the primary
// (stdout) sink, and returns the exit code: 0 on success or a broken-pipe
// shutdown, 4 on any other write failure.
//
// Errors — simple or rich — go through the error builder instead: build the
// event with NewJSONError(code, message).Hint(...).RetryableIf(...).Build() (the
// builder is the error "type") and pass it to Finish(event, exitCode).
func (e *CliEmitter) FinishResult(payload any) int {
	return e.Finish(NewJSONResult(payload).Build(), 0)
}

// BuildCliVersion builds a standard CLI version event: a protocol-v1 result
// whose payload is {code:"version", name, version}, plus display_name and build
// only when non-empty. name is the short/bin identity (e.g. "afdata");
// displayName 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) whose meaning is entirely up to the caller. Passing "" for
// displayName or build means absent: the field is omitted from the payload.
func BuildCliVersion(name, displayName, version, build string) Event {
	result := map[string]any{
		"code":    "version",
		"name":    name,
		"version": version,
	}
	if displayName != "" {
		result["display_name"] = displayName
	}
	if build != "" {
		result["build"] = build
	}
	return NewJSONResult(result).Build()
}

// CliRenderVersion renders a CLI version response as a protocol-v1 event in the
// given format. There is no conventional "<name> <version>" text path: --version
// always answers with a structured event.
func CliRenderVersion(name, displayName, version, build string, format OutputFormat) string {
	rendered := Render(BuildCliVersion(name, displayName, version, build), format, OutputOptions{})
	return strings.TrimRight(rendered, "\n") + "\n"
}