reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
#![cfg(test)]

use std::error::Error;

use crate::opaque::Payload;
use crate::redact_tests::{SECRET, assert_redacted, assert_states};

use super::content::{Metadata, MetadataValue, Part, PartFields, PartKind};
use super::tool_call::{
    Id, MetadataPresence, Name, ToolCall, ToolOutput, ToolPart, ToolPartError, ToolResult,
};

fn complete_part(kind: i64) -> Part {
    let entries = Metadata::from_iter([(
        "present".to_owned(),
        MetadataValue::Bytes(vec![7].into_boxed_slice()),
    )]);
    Part::new(
        PartKind::from_i64(kind),
        PartFields::new(
            "cross-kind".into(),
            "application/example".into(),
            Some(vec![1, 2].into_boxed_slice()),
            "reef://part".into(),
            Some(entries),
            Some(Payload::copy_from_slice(b"raw")),
        ),
    )
}

#[test]
fn tool_call_leaf_round_trips_empty_and_nonempty_values() {
    for (id, name, arguments) in [
        ("", "", b"".as_slice()),
        ("call-1", "search", b"{}".as_slice()),
    ] {
        let call = ToolCall::new(
            Id::new(id.into()),
            Name::new(name.into()),
            Payload::copy_from_slice(arguments),
        );
        assert_eq!(call.id().as_str(), id);
        assert_eq!(call.name().as_str(), name);
        assert_eq!(call.arguments().as_bytes(), arguments);

        let clone = call.clone();
        let (owned_id, owned_name, owned_arguments) = call.into_parts();
        assert_eq!(owned_id.into_string(), id);
        assert_eq!(owned_name.into_string(), name);
        assert_eq!(owned_arguments.into_bytes().as_ref(), arguments);
        assert_eq!(clone.id().as_str(), id);
    }
}

#[test]
fn tool_call_equality_is_field_wise_content_not_correlation_identity() {
    let call = |id: &str, name: &str, arguments: &[u8]| {
        ToolCall::new(
            Id::new(id.into()),
            Name::new(name.into()),
            Payload::copy_from_slice(arguments),
        )
    };

    let subject = call("call-1", "search", br#"{"q":"reef"}"#);
    assert_eq!(subject, subject.clone());
    assert_eq!(Id::new("call-1".into()), Id::new("call-1".into()));
    assert_eq!(Name::new("search".into()), Name::new("search".into()));
    assert_eq!(Id::new(String::new()), Id::new(String::new()));
    assert_eq!(Name::new(String::new()), Name::new(String::new()));
    assert_ne!(Id::new("a".into()), Id::new("b".into()));
    assert_ne!(Name::new("search".into()), Name::new("lookup".into()));

    // Same correlation identity is not equality: name or argument bytes can
    // change under ToolCallDecision::Modify while the id stays put.
    assert_ne!(subject, call("call-2", "search", br#"{"q":"reef"}"#));
    assert_ne!(subject, call("call-1", "lookup", br#"{"q":"reef"}"#));
    assert_ne!(subject, call("call-1", "search", br#"{"q":"other"}"#));
    // Same JSON to a provider; different bytes, so a different call.
    assert_ne!(subject, call("call-1", "search", br#"{ "q" : "reef" }"#));
    assert_eq!(call("", "", b""), call("", "", b""));
}

#[test]
fn tool_part_accepts_every_known_kind_without_field_loss() {
    for kind in 0..=4 {
        let verified = ToolPart::try_from_part(complete_part(kind)).expect("known kind is valid");
        let part = verified.as_part();
        assert_eq!(part.kind().as_i64(), kind);
        assert_eq!(part.fields().text(), "cross-kind");
        assert_eq!(part.fields().mime(), "application/example");
        assert_eq!(part.fields().data(), Some([1, 2].as_slice()));
        assert_eq!(part.fields().reference(), "reef://part");
        assert!(matches!(
            part.fields().metadata().and_then(|value| value.get("present")),
            Some(MetadataValue::Bytes(value)) if value.as_ref() == [7]
        ));
        assert_eq!(
            part.fields().raw_payload().map(Payload::as_bytes),
            Some(b"raw".as_slice())
        );

        let recovered = verified.into_part();
        assert_eq!(recovered.kind().as_i64(), kind);
        assert_eq!(recovered.fields().data(), Some([1, 2].as_slice()));
    }
}

#[test]
fn tool_part_rejects_unknown_kind_with_exact_typed_error() {
    for kind in [i64::MIN, -1, 5, 99, i64::MAX] {
        let error = match ToolPart::try_from_part(complete_part(kind)) {
            Ok(_) => panic!("unknown kind unexpectedly accepted"),
            Err(error) => error,
        };
        assert_eq!(error, ToolPartError::UnknownKind(kind));
        assert_eq!(error.to_string(), format!("unknown tool part kind {kind}"));
        assert!(error.source().is_none());
    }

    let ordinary = complete_part(99);
    assert_eq!(ordinary.kind().as_i64(), 99);
    assert_eq!(ordinary.fields().text(), "cross-kind");
}

#[test]
fn tool_output_preserves_user_log_and_metadata_presence() {
    let metadata_states = [
        MetadataPresence::Absent,
        MetadataPresence::PresentNull,
        MetadataPresence::Present(Metadata::new()),
        MetadataPresence::Present(Metadata::from_iter([(
            "key".to_owned(),
            MetadataValue::String("value".into()),
        )])),
    ];

    for metadata in metadata_states {
        for user in [None, Some(String::new()), Some("user".into())] {
            for log in [None, Some(String::new()), Some("log".into())] {
                let output =
                    ToolOutput::new(Vec::new(), user.clone(), log.clone(), metadata.clone());
                assert!(output.model_content().is_empty());
                assert_eq!(output.user_view(), user.as_deref());
                assert_eq!(output.log_preview(), log.as_deref());
                match (output.metadata(), &metadata) {
                    (MetadataPresence::Absent, MetadataPresence::Absent)
                    | (MetadataPresence::PresentNull, MetadataPresence::PresentNull) => {}
                    (MetadataPresence::Present(actual), MetadataPresence::Present(expected)) => {
                        assert_eq!(actual.iter().count(), expected.iter().count());
                    }
                    _ => panic!("metadata presence changed"),
                }

                let (parts, owned_user, owned_log, owned_metadata) = output.into_parts();
                assert!(parts.is_empty());
                assert_eq!(owned_user, user);
                assert_eq!(owned_log, log);
                assert_eq!(
                    matches!(owned_metadata, MetadataPresence::PresentNull),
                    matches!(metadata, MetadataPresence::PresentNull)
                );
            }
        }
    }
}

#[test]
fn tool_output_borrowed_getters_retain_owned_content() {
    let verified = ToolPart::try_from_part(complete_part(2)).expect("known kind is valid");
    let output = ToolOutput::new(
        vec![verified],
        Some("complete user view".into()),
        Some("bounded log".into()),
        MetadataPresence::Present(Metadata::new()),
    );
    let clone = output.clone();
    assert_eq!(
        output.model_content()[0].as_part().fields().data(),
        Some([1, 2].as_slice())
    );
    assert_eq!(clone.user_view(), Some("complete user view"));
    assert_eq!(clone.log_preview(), Some("bounded log"));
    assert!(
        matches!(clone.metadata(), MetadataPresence::Present(value) if value.iter().count() == 0)
    );
}

#[test]
fn tool_result_closed_states_and_explicit_empty_outputs() {
    let default = ToolResult::default();
    assert!(!default.has_output());
    assert!(!default.is_business_error());
    assert!(default.output().is_none());

    let no_output = ToolResult::no_output();
    assert!(matches!(no_output, ToolResult::NoOutput));

    let success = ToolResult::success(ToolOutput::new(
        Vec::new(),
        None,
        None,
        MetadataPresence::Absent,
    ));
    assert!(success.has_output());
    assert!(!success.is_business_error());
    assert!(
        success
            .output()
            .is_some_and(|output| output.model_content().is_empty())
    );

    let business_error = ToolResult::business_error(ToolOutput::new(
        Vec::new(),
        Some(String::new()),
        Some(String::new()),
        MetadataPresence::PresentNull,
    ));
    assert!(business_error.has_output());
    assert!(business_error.is_business_error());
    let output = business_error
        .output()
        .expect("business error carries output");
    assert_eq!(output.user_view(), Some(""));
    assert_eq!(output.log_preview(), Some(""));
    assert!(matches!(output.metadata(), MetadataPresence::PresentNull));

    let cloned = business_error.clone();
    assert!(matches!(cloned, ToolResult::BusinessError(_)));
}

/// The one rule a hand-written descent gets wrong, pinned on its own.
///
/// Every other test of this rendering happens to use outputs whose user view and
/// model content say the same thing — `ToolResult::success_text` builds exactly
/// that — so none of them can tell the two apart. This one makes them disagree
/// and asserts which one wins, because a renderer that reads model content when
/// a user view is present produces no error and no failing test: just the wrong
/// text on a screen.
#[test]
fn a_user_view_wins_over_model_content_in_every_state_that_has_one() {
    fn text_part(text: &str) -> ToolPart {
        ToolPart::try_from_part(Part::text(text.to_owned())).expect("text is a known kind")
    }
    fn output(user_view: Option<&str>) -> ToolOutput {
        ToolOutput::new(
            vec![text_part("row one"), text_part("row two")],
            user_view.map(str::to_owned),
            None,
            MetadataPresence::Absent,
        )
    }

    // Present, and different from the model's rows: the view wins.
    for result in [
        ToolResult::success(output(Some("2 matches"))),
        ToolResult::business_error(output(Some("2 matches"))),
    ] {
        assert_eq!(result.to_plain_text(), "2 matches");
        assert_ne!(result.to_plain_text(), "row one\nrow two");
    }

    // Present and empty is still present. A tool that says "show nothing" is
    // obeyed rather than overridden by the content it sent the model.
    assert_eq!(ToolResult::success(output(Some(""))).to_plain_text(), "");

    // Absent is the only case that falls back, and it joins blocks with one
    // newline and adds nothing else.
    assert_eq!(
        ToolResult::success(output(None)).to_plain_text(),
        "row one\nrow two"
    );

    // No output renders as nothing rather than as a placeholder.
    assert_eq!(ToolResult::no_output().to_plain_text(), "");
    assert_eq!(ToolResult::default().to_plain_text(), "");
}

#[test]
fn scalar_text_helpers_bound_preview_on_utf8_boundary() {
    let cases = [
        (String::new(), String::new()),
        ("a".repeat(200), "a".repeat(200)),
        ("b".repeat(201), format!("{}…", "b".repeat(200))),
        (
            format!("{}界", "a".repeat(199)),
            format!("{}…", "a".repeat(199)),
        ),
        (
            format!("{}😀", "c".repeat(197)),
            format!("{}…", "c".repeat(197)),
        ),
    ];

    for (text, preview) in cases {
        for result in [
            ToolResult::success_text(text.clone()),
            ToolResult::error_text(text.clone()),
        ] {
            assert!(result.has_output());
            let output = result.output().expect("helper always creates output");
            assert_eq!(output.user_view(), Some(text.as_str()));
            assert_eq!(output.log_preview(), Some(preview.as_str()));
            assert!(matches!(output.metadata(), MetadataPresence::Absent));
            assert_eq!(output.model_content().len(), 1);
            let part = output.model_content()[0].as_part();
            assert_eq!(part.kind().as_i64(), 0);
            assert_eq!(part.fields().text(), text);
        }
    }

    assert!(!ToolResult::success_text("ok".into()).is_business_error());
    assert!(ToolResult::error_text("error".into()).is_business_error());
}

#[test]
fn tool_output_debug_sizes_both_rendered_views() {
    // `user_view` and `log_preview` are the two fields an end user reads, so
    // they are the last place a formatter should quote from.
    let output = ToolOutput::new(
        vec![ToolPart::try_from_part(Part::text(SECRET.into())).expect("known kind")],
        Some(SECRET.into()),
        Some(String::new()),
        MetadataPresence::Present(Metadata::from_iter([(
            "secret".to_owned(),
            MetadataValue::String(SECRET.into()),
        )])),
    );
    assert_redacted(&output);
    assert_states(
        &output,
        &[
            "user_view: Some(<21 bytes>)",
            "log_preview: Some(<0 bytes>)",
            "metadata: Present(Metadata { entries: 1 })",
            "text: <21 bytes>",
        ],
    );

    let empty = ToolOutput::new(Vec::new(), None, None, MetadataPresence::Absent);
    assert_redacted(&empty);
    assert_states(
        &empty,
        &[
            "model_content: []",
            "user_view: None",
            "log_preview: None",
            "metadata: Absent",
        ],
    );
}

#[test]
fn tool_call_debug_keeps_identifiers_and_sizes_the_arguments() {
    let call = ToolCall::new(
        Id::new("call-1".into()),
        Name::new("search".into()),
        Payload::copy_from_slice(SECRET.as_bytes()),
    );
    assert_redacted(&call);
    assert_eq!(
        format!("{call:?}"),
        r#"ToolCall { id: Id("call-1"), name: Name("search"), arguments: <21 bytes> }"#
    );
}

#[test]
fn tool_result_debug_redacts_through_every_variant() {
    let output = || {
        ToolOutput::new(
            Vec::new(),
            Some(SECRET.into()),
            None,
            MetadataPresence::PresentNull,
        )
    };
    for result in [
        ToolResult::no_output(),
        ToolResult::success(output()),
        ToolResult::business_error(output()),
    ] {
        assert_redacted(&result);
    }
    assert_eq!(format!("{:?}", ToolResult::no_output()), "NoOutput");
    assert_states(
        &ToolResult::business_error(output()),
        &["BusinessError", "user_view: Some(<21 bytes>)"],
    );
}

/// What the `serde` feature adds to this module, and what it refuses.
#[cfg(feature = "serde")]
mod serde_format {
    use super::super::content::{Metadata, Part, PartFields, PartKind};
    use super::super::tool_call::{
        Id, MetadataPresence, Name, ToolCall, ToolOutput, ToolPart, ToolResult,
    };
    use crate::opaque::Payload;
    use crate::wire::wire_tests::{assert_expecting, assert_refusal, encode, round_trip};

    fn text_part() -> ToolPart {
        ToolPart::try_from_part(Part::text("ok".into())).expect("text is a known kind")
    }

    fn output() -> ToolOutput {
        ToolOutput::new(
            vec![text_part()],
            Some(String::new()),
            None,
            MetadataPresence::Present(Metadata::new()),
        )
    }

    #[test]
    fn an_identity_and_a_name_travel_as_the_strings_they_are() {
        assert_eq!(encode(&Id::new("call-1".into())), r#""call-1""#);
        assert_eq!(encode(&Name::new(String::new())), r#""""#);
        assert_eq!(round_trip(&Id::new("call-1".into())).as_str(), "call-1");
        assert_eq!(round_trip(&Name::new("search".into())).as_str(), "search");
    }

    #[test]
    fn a_tool_call_reads_from_both_forms_and_refuses_the_rest() {
        let call = ToolCall::new(
            Id::new("call-1".into()),
            Name::new("search".into()),
            Payload::copy_from_slice(b"{}"),
        );
        assert_eq!(encode(&round_trip(&call)), encode(&call));

        let from_sequence: ToolCall = serde_json::from_str(r#"["call-1","search",[123,125]]"#)
            .expect("a compact format writes a struct as its fields in order");
        assert_eq!(encode(&from_sequence), encode(&call));

        assert_refusal(
            serde_json::from_str::<ToolCall>(r#"{"id":"c","call_id":"c"}"#),
            "unknown field `call_id`",
        );
        assert_refusal(
            serde_json::from_str::<ToolCall>(r#"{"id":"c","id":"c"}"#),
            "duplicate field `id`",
        );
        assert_refusal(
            serde_json::from_str::<ToolCall>(r#"{"id":"c","name":"t"}"#),
            "missing field `arguments`",
        );
        assert_refusal(
            serde_json::from_str::<ToolCall>(r#"["c"]"#),
            "every struct field",
        );
        assert_expecting::<ToolCall>("a tool invocation");
    }

    /// Tool output is the one Part consumer that narrows, and a file is no more
    /// trusted than a call site.
    #[test]
    fn reading_a_tool_part_re_runs_the_kind_check() {
        assert_eq!(encode(&round_trip(&text_part())), encode(&text_part()));

        let unknown = Part::new(
            PartKind::from_i64(77),
            PartFields::new(
                String::new(),
                String::new(),
                None,
                String::new(),
                None,
                None,
            ),
        );
        assert_refusal(
            serde_json::from_str::<ToolPart>(&encode(&unknown)),
            "unknown tool part kind 77",
        );
    }

    #[test]
    fn every_metadata_presence_state_stays_distinct() {
        let states = [
            MetadataPresence::Absent,
            MetadataPresence::PresentNull,
            MetadataPresence::Present(Metadata::new()),
        ];
        let encoded: Vec<String> = states.iter().map(encode).collect();
        assert_eq!(
            encoded,
            [r#""absent""#, r#""present_null""#, r#"{"present":{}}"#]
        );
        for state in &states {
            assert_eq!(encode(&round_trip(state)), encode(state));
        }

        assert_refusal(
            serde_json::from_str::<MetadataPresence>(r#"{"null":null}"#),
            "unknown variant `null`",
        );
        assert_expecting::<MetadataPresence>("a tool-result metadata presence state");
    }

    /// A unit variant arrives either as a bare tag or as a tag mapped to unit.
    ///
    /// External tagging says which variant, not how the format spells the empty
    /// payload. Reading only the shape `serde_json` writes would leave the other
    /// half of the contract untested, and these two states are precisely the ones
    /// ADR-005 exists to keep apart.
    #[test]
    fn the_payload_free_states_read_from_both_spellings_of_a_unit_variant() {
        assert!(matches!(
            serde_json::from_str::<MetadataPresence>(r#"{"absent":null}"#)
                .expect("the tag-to-unit mapping reads"),
            MetadataPresence::Absent
        ));
        assert!(matches!(
            serde_json::from_str::<MetadataPresence>(r#"{"present_null":null}"#)
                .expect("the tag-to-unit mapping reads"),
            MetadataPresence::PresentNull
        ));
        assert!(matches!(
            serde_json::from_str::<ToolResult>(r#"{"no_output":null}"#)
                .expect("the tag-to-unit mapping reads"),
            ToolResult::NoOutput
        ));
    }

    #[test]
    fn a_tool_output_reads_from_both_forms_and_refuses_the_rest() {
        assert_eq!(encode(&round_trip(&output())), encode(&output()));

        let from_sequence: ToolOutput =
            serde_json::from_str(r#"[[],null,null,"absent"]"#).expect("the sequence form reads");
        assert_eq!(
            encode(&from_sequence),
            encode(&ToolOutput::new(
                Vec::new(),
                None,
                None,
                MetadataPresence::Absent
            ))
        );

        assert_refusal(
            serde_json::from_str::<ToolOutput>(r#"{"model_content":[],"content":[]}"#),
            "unknown field `content`",
        );
        assert_refusal(
            serde_json::from_str::<ToolOutput>(r#"{"model_content":[],"model_content":[]}"#),
            "duplicate field `model_content`",
        );
        assert_refusal(
            serde_json::from_str::<ToolOutput>(
                r#"{"model_content":[],"user_view":null,"log_preview":null}"#,
            ),
            "missing field `metadata`",
        );
        assert_refusal(
            serde_json::from_str::<ToolOutput>("[[]]"),
            "every struct field",
        );
        assert_expecting::<ToolOutput>("a tool output payload");
    }

    #[test]
    fn every_tool_result_state_survives_a_round_trip() {
        let results = [
            ToolResult::no_output(),
            ToolResult::success(output()),
            ToolResult::business_error(output()),
        ];
        for result in &results {
            assert_eq!(encode(&round_trip(result)), encode(result));
        }
        assert_eq!(encode(&results[0]), r#""no_output""#);

        assert_refusal(
            serde_json::from_str::<ToolResult>(r#"{"failure":null}"#),
            "unknown variant `failure`",
        );
        assert_expecting::<ToolResult>("a closed tool result");
    }
}