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
498
499
500
501
502
503
504
505
506
507
508
package afdata

import (
	"encoding"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"math"
	"reflect"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"
	"unicode"
)

// This file holds the reflection walk that applies the "Native values" rule
// per leaf: a struct, map, slice, array or pointer is converted node by node,
// so one ill-formed or non-finite leaf marks only itself instead of
// discarding the whole value.

var (
	jsonMarshalerType = reflect.TypeOf((*json.Marshaler)(nil)).Elem()
	textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
	errorType         = reflect.TypeOf((*error)(nil)).Elem()
	timeType          = reflect.TypeOf(time.Time{})
	isZeroerType      = reflect.TypeOf((*interface{ IsZero() bool })(nil)).Elem()
)

func implementsMarshaler(t reflect.Type) bool {
	return t.Implements(jsonMarshalerType) || t.Implements(textMarshalerType)
}

func implementsSpecial(t reflect.Type) bool {
	return implementsMarshaler(t) || t.Implements(errorType)
}

func unsupportedMarker(value any) string {
	// Never stringify raw value content here; it may contain secrets.
	return fmt.Sprintf("<unsupported:%T>", value)
}

// sanitizeMarshaled converts a value that controls its own JSON form.
func sanitizeMarshaled(value any) any {
	normalized := normalize(value)
	if _, err := json.Marshal(normalized); err == nil {
		return normalized
	}
	return unsupportedMarker(value)
}

func sanitizeReflect(rv reflect.Value, visited map[visitKey]struct{}, depth int) any {
	if depth >= maxDepth {
		return maxDepthMarker
	}
	if !rv.IsValid() {
		return nil
	}
	switch rv.Kind() {
	case reflect.Interface:
		if rv.IsNil() {
			return nil
		}
		return sanitizeReflect(rv.Elem(), visited, depth)
	case reflect.Pointer:
		if rv.IsNil() {
			return nil
		}
	}
	t := rv.Type()
	if !rv.CanInterface() {
		return unsupportedMarker(reflect.Zero(t).Interface())
	}

	// A value whose pointer type carries the method is converted through its
	// address, like encoding/json does for addressable operands.
	if rv.CanAddr() && t.Kind() != reflect.Pointer && !implementsSpecial(t) && implementsSpecial(reflect.PointerTo(t)) {
		return sanitizeForJSONWithVisited(rv.Addr().Interface(), visited, depth)
	}

	switch rv.Interface().(type) {
	case error, time.Time, json.Number, string, map[string]any, []any:
		return sanitizeForJSONWithVisited(rv.Interface(), visited, depth)
	}

	if t.Kind() == reflect.Pointer && t.Elem() == timeType {
		return sanitizeReflect(rv.Elem(), visited, depth)
	}
	if implementsMarshaler(t) {
		return sanitizeMarshaled(rv.Interface())
	}

	switch rv.Kind() {
	case reflect.Bool:
		return rv.Bool()
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return json.Number(strconv.FormatInt(rv.Int(), 10))
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return json.Number(strconv.FormatUint(rv.Uint(), 10))
	case reflect.String:
		return strings.ToValidUTF8(rv.String(), "�")
	case reflect.Float32, reflect.Float64:
		f := rv.Float()
		if math.IsNaN(f) || math.IsInf(f, 0) {
			return "<unsupported:number>"
		}
		return normalize(rv.Interface())
	case reflect.Pointer:
		key := visitKey{kind: reflect.Pointer, ptr: rv.Pointer()}
		if _, seen := visited[key]; seen {
			return "<unsupported:circular>"
		}
		visited[key] = struct{}{}
		defer delete(visited, key)
		return sanitizeReflect(rv.Elem(), visited, depth)
	case reflect.Map:
		return sanitizeMap(rv, visited, depth)
	case reflect.Slice:
		if rv.IsNil() {
			return nil
		}
		if isByteElem(t.Elem()) {
			return base64.StdEncoding.EncodeToString(rv.Bytes())
		}
		if rv.Len() > 0 {
			key := visitKey{kind: reflect.Slice, ptr: rv.Pointer()}
			if _, seen := visited[key]; seen {
				return "<unsupported:circular>"
			}
			visited[key] = struct{}{}
			defer delete(visited, key)
		}
		return sanitizeList(rv, visited, depth)
	case reflect.Array:
		if isByteElem(t.Elem()) {
			buf := make([]byte, rv.Len())
			for i := range buf {
				buf[i] = byte(rv.Index(i).Uint())
			}
			return base64.StdEncoding.EncodeToString(buf)
		}
		return sanitizeList(rv, visited, depth)
	case reflect.Struct:
		return sanitizeStruct(rv, visited, depth)
	}
	// Chan, Func, Complex, UnsafePointer.
	return unsupportedMarker(rv.Interface())
}

// isByteElem reports whether a slice or array of elem is a byte sequence the
// way encoding/json decides it: uint8 kind whose pointer type does not take
// over its own encoding.
func isByteElem(elem reflect.Type) bool {
	return elem.Kind() == reflect.Uint8 && !implementsMarshaler(reflect.PointerTo(elem))
}

func sanitizeList(rv reflect.Value, visited map[visitKey]struct{}, depth int) any {
	out := make([]any, rv.Len())
	for i := range out {
		out[i] = sanitizeReflect(rv.Index(i), visited, depth+1)
	}
	return out
}

func sanitizeMap(rv reflect.Value, visited map[visitKey]struct{}, depth int) any {
	if rv.IsNil() {
		return nil
	}
	switch rv.Type().Key().Kind() {
	case reflect.String,
		reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
		reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
	default:
		return unsupportedMarker(rv.Interface())
	}
	key := visitKey{kind: reflect.Map, ptr: rv.Pointer()}
	if _, seen := visited[key]; seen {
		return "<unsupported:circular>"
	}
	visited[key] = struct{}{}
	defer delete(visited, key)

	out := make(map[string]any, rv.Len())
	iter := rv.MapRange()
	for iter.Next() {
		k := iter.Key()
		var name string
		switch k.Kind() {
		case reflect.String:
			name = strings.ToValidUTF8(k.String(), "�")
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			name = strconv.FormatInt(k.Int(), 10)
		default:
			name = strconv.FormatUint(k.Uint(), 10)
		}
		out[name] = sanitizeReflect(iter.Value(), visited, depth+1)
	}
	return out
}

// ─── struct fields (encoding/json rules) ───

type nativeField struct {
	name      string
	index     []int
	typ       reflect.Type
	tagged    bool
	omitEmpty bool
	omitZero  bool
	quoted    bool
}

var nativeFieldCache sync.Map // reflect.Type -> []nativeField

func sanitizeStruct(rv reflect.Value, visited map[visitKey]struct{}, depth int) any {
	out := map[string]any{}
	for _, f := range cachedNativeFields(rv.Type()) {
		fv, ok := fieldByIndex(rv, f.index)
		if !ok {
			continue
		}
		if f.omitEmpty && isEmptyNative(fv) {
			continue
		}
		if f.omitZero && isZeroNative(fv) {
			continue
		}
		name := strings.ToValidUTF8(f.name, "�")
		if f.quoted {
			out[name] = sanitizeQuoted(fv, visited, depth+1)
			continue
		}
		out[name] = sanitizeReflect(fv, visited, depth+1)
	}
	return out
}

func fieldByIndex(v reflect.Value, index []int) (reflect.Value, bool) {
	for i, x := range index {
		if i > 0 {
			for v.Kind() == reflect.Pointer {
				if v.IsNil() {
					return reflect.Value{}, false
				}
				v = v.Elem()
			}
		}
		v = v.Field(x)
	}
	return v, true
}

func isEmptyNative(v reflect.Value) bool {
	switch v.Kind() {
	case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
		return v.Len() == 0
	case reflect.Bool:
		return !v.Bool()
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return v.Int() == 0
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return v.Uint() == 0
	case reflect.Float32, reflect.Float64:
		return v.Float() == 0
	case reflect.Interface, reflect.Pointer:
		return v.IsNil()
	}
	return false
}

func isZeroNative(v reflect.Value) bool {
	t := v.Type()
	if t.Implements(isZeroerType) {
		if t.Kind() == reflect.Pointer && v.IsNil() {
			return true
		}
		return v.Interface().(interface{ IsZero() bool }).IsZero()
	}
	if t.Kind() != reflect.Pointer && v.CanAddr() && reflect.PointerTo(t).Implements(isZeroerType) {
		return v.Addr().Interface().(interface{ IsZero() bool }).IsZero()
	}
	return v.IsZero()
}

// sanitizeQuoted applies the `,string` option: the scalar becomes the string
// holding its JSON text.
func sanitizeQuoted(v reflect.Value, visited map[visitKey]struct{}, depth int) any {
	for v.Kind() == reflect.Pointer {
		if v.IsNil() {
			return nil
		}
		v = v.Elem()
	}
	if implementsMarshaler(v.Type()) {
		return sanitizeReflect(v, visited, depth)
	}
	leaf := sanitizeReflect(v, visited, depth)
	switch x := leaf.(type) {
	case bool:
		return strconv.FormatBool(x)
	case json.Number:
		return string(x)
	case float64:
		b, _ := json.Marshal(x)
		return string(b)
	case string:
		if v.Kind() == reflect.String {
			b, _ := json.Marshal(x)
			return string(b)
		}
	}
	return leaf
}

func cachedNativeFields(t reflect.Type) []nativeField {
	if cached, ok := nativeFieldCache.Load(t); ok {
		return cached.([]nativeField)
	}
	fields := computeNativeFields(t)
	actual, _ := nativeFieldCache.LoadOrStore(t, fields)
	return actual.([]nativeField)
}

func parseJSONTag(tag string) (string, string) {
	name, opts, _ := strings.Cut(tag, ",")
	return name, opts
}

// jsonHonorsOmitZero reports whether this toolchain's encoding/json applies
// the `omitzero` option (Go 1.24 and later). Struct fields follow
// encoding/json, so the option means here exactly what it means there.
var jsonHonorsOmitZero = func() bool {
	encoded, err := json.Marshal(struct {
		A int `json:",omitzero"`
	}{})
	return err == nil && string(encoded) == "{}"
}()

func tagHasOption(opts, option string) bool {
	for opts != "" {
		var cur string
		cur, opts, _ = strings.Cut(opts, ",")
		if cur == option {
			return true
		}
	}
	return false
}

func isValidJSONTagName(name string) bool {
	if name == "" {
		return false
	}
	for _, c := range name {
		switch {
		case strings.ContainsRune("!#$%&()*+-./:;<=>?@[]^_{|}~ ", c):
		case !unicode.IsLetter(c) && !unicode.IsDigit(c):
			return false
		}
	}
	return true
}

// computeNativeFields mirrors encoding/json's typeFields: breadth-first walk
// over embedded structs, then dominant-field resolution per name.
func computeNativeFields(t reflect.Type) []nativeField {
	current := []nativeField{}
	next := []nativeField{{typ: t}}
	var count, nextCount map[reflect.Type]int
	visitedTypes := map[reflect.Type]bool{}
	var fields []nativeField

	for len(next) > 0 {
		current, next = next, current[:0]
		count, nextCount = nextCount, map[reflect.Type]int{}

		for _, f := range current {
			if visitedTypes[f.typ] {
				continue
			}
			visitedTypes[f.typ] = true

			for i := 0; i < f.typ.NumField(); i++ {
				sf := f.typ.Field(i)
				if sf.Anonymous {
					et := sf.Type
					if et.Kind() == reflect.Pointer {
						et = et.Elem()
					}
					if !sf.IsExported() && et.Kind() != reflect.Struct {
						continue
					}
				} else if !sf.IsExported() {
					continue
				}
				tag := sf.Tag.Get("json")
				if tag == "-" {
					continue
				}
				name, opts := parseJSONTag(tag)
				if !isValidJSONTagName(name) {
					name = ""
				}
				index := make([]int, len(f.index)+1)
				copy(index, f.index)
				index[len(f.index)] = i

				ft := sf.Type
				if ft.Name() == "" && ft.Kind() == reflect.Pointer {
					ft = ft.Elem()
				}
				quoted := false
				if tagHasOption(opts, "string") {
					switch ft.Kind() {
					case reflect.Bool,
						reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
						reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
						reflect.Float32, reflect.Float64, reflect.String:
						quoted = true
					}
				}

				if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct {
					tagged := name != ""
					if name == "" {
						name = sf.Name
					}
					field := nativeField{
						name:      name,
						index:     index,
						typ:       ft,
						tagged:    tagged,
						omitEmpty: tagHasOption(opts, "omitempty"),
						omitZero:  jsonHonorsOmitZero && tagHasOption(opts, "omitzero"),
						quoted:    quoted,
					}
					fields = append(fields, field)
					if count[f.typ] > 1 {
						// Two embedded structs at this depth: the duplicate
						// entry makes the name conflict cancel both.
						fields = append(fields, fields[len(fields)-1])
					}
					continue
				}

				nextCount[ft]++
				if nextCount[ft] == 1 {
					next = append(next, nativeField{name: ft.Name(), index: index, typ: ft})
				}
			}
		}
	}

	sort.Slice(fields, func(i, j int) bool {
		x := fields
		if x[i].name != x[j].name {
			return x[i].name < x[j].name
		}
		if len(x[i].index) != len(x[j].index) {
			return len(x[i].index) < len(x[j].index)
		}
		if x[i].tagged != x[j].tagged {
			return x[i].tagged
		}
		return indexLess(x[i].index, x[j].index)
	})

	out := fields[:0]
	for advance, i := 0, 0; i < len(fields); i += advance {
		fi := fields[i]
		advance = 1
		for advance = 1; i+advance < len(fields); advance++ {
			if fields[i+advance].name != fi.name {
				break
			}
		}
		if advance == 1 {
			out = append(out, fi)
			continue
		}
		if dom, ok := dominantNativeField(fields[i : i+advance]); ok {
			out = append(out, dom)
		}
	}
	sort.Slice(out, func(i, j int) bool { return indexLess(out[i].index, out[j].index) })
	return out
}

func indexLess(a, b []int) bool {
	for k, xv := range a {
		if k >= len(b) {
			return false
		}
		if xv != b[k] {
			return xv < b[k]
		}
	}
	return len(a) < len(b)
}

// dominantNativeField expects fields sorted shallowest first, tagged first.
func dominantNativeField(fields []nativeField) (nativeField, bool) {
	if len(fields) > 1 && len(fields[0].index) == len(fields[1].index) && fields[0].tagged == fields[1].tagged {
		return nativeField{}, false
	}
	return fields[0], true
}