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
#![cfg(test)]

use std::error::Error;
use std::fmt;
use std::sync::{Arc, Mutex};

use crate::cancel::Token;

use super::hook::{
    self, AfterToolCommitScope, CallbackResources, DispatchError, Emitter, HookError, HookResult,
    StepSnapshot, ToolCallDecision, ToolCallScope, ToolHooks, ToolResultDecision, ToolResultScope,
};
use super::model::{Info, RequestPlan};
use super::session::Session;
use super::tool::{self, ExposeAll};
use super::tool_batch::SettledDisposition;
use super::tool_batch_prepare::{PreparedSettlement, prepare_tool_calls};
use crate::audit;
use crate::opaque::Payload;
use crate::state::run_state::{self};
use crate::state::session_state::{self};
use crate::transcript::item::Item;
use crate::transcript::store::{Snapshot, Version};
use crate::value::lifecycle::Coord;
use crate::value::tool_call::{self, Id, ToolCall, ToolResult};

#[derive(Debug)]
struct TestError;

impl fmt::Display for TestError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("callback failed")
    }
}

impl Error for TestError {}

struct NoopEmitter;

impl Emitter for NoopEmitter {
    fn emit_audit(&self, _event: audit::Event) {}

    fn emit_error(&self, _error: Arc<dyn Error + Send + Sync>) {}
}

type Callback = dyn for<'a> Fn(&ToolCallScope<'a>) -> ToolCallDecision + Send + Sync;
type FallibleCallback =
    dyn for<'a> Fn(&ToolCallScope<'a>) -> HookResult<ToolCallDecision> + Send + Sync;

struct CallbackHook(Box<Callback>);

impl CallbackHook {
    fn new(
        callback: impl for<'a> Fn(&ToolCallScope<'a>) -> ToolCallDecision + Send + Sync + 'static,
    ) -> Arc<Self> {
        Arc::new(Self(Box::new(callback)))
    }
}

impl ToolHooks for CallbackHook {
    fn before_tool_call(&self, scope: &ToolCallScope<'_>) -> HookResult<ToolCallDecision> {
        Ok((self.0)(scope))
    }

    fn before_tool_result(&self, _scope: &ToolResultScope<'_>) -> HookResult<ToolResultDecision> {
        Ok(ToolResultDecision::Continue)
    }

    fn after_tool_commit(&self, _scope: &AfterToolCommitScope<'_>) -> Vec<Item> {
        Vec::new()
    }
}

struct FallibleCallbackHook(Box<FallibleCallback>);

impl FallibleCallbackHook {
    fn new(
        callback: impl for<'a> Fn(&ToolCallScope<'a>) -> HookResult<ToolCallDecision>
        + Send
        + Sync
        + 'static,
    ) -> Arc<Self> {
        Arc::new(Self(Box::new(callback)))
    }
}

impl ToolHooks for FallibleCallbackHook {
    fn before_tool_call(&self, scope: &ToolCallScope<'_>) -> HookResult<ToolCallDecision> {
        (self.0)(scope)
    }

    fn before_tool_result(&self, _scope: &ToolResultScope<'_>) -> HookResult<ToolResultDecision> {
        Ok(ToolResultDecision::Continue)
    }

    fn after_tool_commit(&self, _scope: &AfterToolCommitScope<'_>) -> Vec<Item> {
        Vec::new()
    }
}

fn call(id: &str, name: &str, arguments: &[u8]) -> ToolCall {
    ToolCall::new(
        Id::new(id.to_owned()),
        tool_call::Name::new(name.to_owned()),
        Payload::copy_from_slice(arguments),
    )
}

fn snapshot() -> Arc<StepSnapshot> {
    let tools = tool::RegistryBuilder::new()
        .build()
        .unwrap()
        .resolve_step_without_providers(
            Snapshot::new(Version::ZERO, Vec::new()),
            &Token::new(),
            &ExposeAll,
        )
        .unwrap()
        .into_snapshot();
    StepSnapshot::freeze(
        Info::new("model".into(), 1024).with_tools(true),
        RequestPlan::new(),
        tools,
    )
}

fn registry(registrations: Vec<hook::Registration>) -> hook::RuntimeRegistry {
    let mut builder = hook::RegistryBuilder::new();
    for registration in registrations {
        builder.register(registration);
    }
    builder.build_runtime().unwrap()
}

fn resources<'a>(
    coord: &'a Coord,
    states: &'a [run_state::Store],
    reader: &'a session_state::Reader,
    emitter: &'a dyn Emitter,
) -> Vec<CallbackResources<'a>> {
    states
        .iter()
        .map(|state| CallbackResources::new(coord, state, reader, None, emitter))
        .collect()
}

#[test]
fn a_registration_that_never_fails_reaches_the_adapter_and_its_decision_applies() {
    let calls = Arc::new(Mutex::new(0));
    let callback_calls = Arc::clone(&calls);
    let hook = CallbackHook::new(move |_scope| {
        *callback_calls.lock().unwrap() += 1;
        ToolCallDecision::Block("infallible".into())
    });
    let registry = registry(vec![
        hook::Registration::new("infallible".into()).tool(hook),
    ]);
    let session = Session::new("session".into(), None);
    let reader = session.state();
    let coord = Coord::at_run("session".into(), "run".into()).unwrap();
    let states = [run_state::Store::new()];
    let emitter = NoopEmitter;
    let resources = resources(&coord, &states, &reader, &emitter);

    let plan = prepare_tool_calls(
        vec![call("one", "tool", b"{}")],
        &registry,
        &resources,
        snapshot(),
        &Token::new(),
    )
    .unwrap();

    assert_eq!(*calls.lock().unwrap(), 1);
    assert_eq!(
        plan.entries()[0].settled().unwrap().disposition(),
        SettledDisposition::Blocked
    );
}

#[test]
fn rewrites_chain_in_registration_order_preserve_ids_and_source_order() {
    let log = Arc::new(Mutex::new(Vec::new()));
    let first_log = Arc::clone(&log);
    let first = CallbackHook::new(move |scope| {
        first_log.lock().unwrap().push(format!(
            "first:{}:{}",
            scope.call().id().as_str(),
            scope.call().name().as_str()
        ));
        if scope.call().id().as_str() == "one" {
            ToolCallDecision::Modify(call("spoof-1", "middle", b"one"))
        } else {
            ToolCallDecision::Continue
        }
    });
    let second_log = Arc::clone(&log);
    let second = CallbackHook::new(move |scope| {
        second_log.lock().unwrap().push(format!(
            "second:{}:{}",
            scope.call().id().as_str(),
            scope.call().name().as_str()
        ));
        ToolCallDecision::Modify(call(
            "spoof-2",
            &format!("final-{}", scope.call().name().as_str()),
            b"two",
        ))
    });
    let registry = registry(vec![
        hook::Registration::new("first".into()).tool(first),
        hook::Registration::new("second".into()).tool(second),
    ]);
    let session = Session::new("session".into(), None);
    let reader = session.state();
    let coord = Coord::at_run("session".into(), "run".into()).unwrap();
    let states = [run_state::Store::new(), run_state::Store::new()];
    let emitter = NoopEmitter;
    let resources = resources(&coord, &states, &reader, &emitter);

    let plan = prepare_tool_calls(
        vec![
            call("one", "alpha", b"original-1"),
            call("two", "beta", b"original-2"),
        ],
        &registry,
        &resources,
        snapshot(),
        &Token::new(),
    )
    .unwrap();

    assert_eq!(
        *log.lock().unwrap(),
        [
            "first:one:alpha",
            "second:one:middle",
            "first:two:beta",
            "second:two:beta"
        ]
    );
    let entries = plan.entries();
    assert_eq!(entries[0].original().name().as_str(), "alpha");
    assert_eq!(entries[0].effective().id().as_str(), "one");
    assert_eq!(entries[0].effective().name().as_str(), "final-middle");
    assert_eq!(entries[1].original().id().as_str(), "two");
    assert_eq!(entries[1].effective().id().as_str(), "two");
    assert_eq!(entries[1].effective().name().as_str(), "final-beta");
    assert!(entries.iter().all(|entry| entry.settled().is_none()));
    let (original, effective, settled) = plan.into_entries().remove(0).into_parts();
    assert_eq!(original.arguments().as_bytes(), b"original-1");
    assert_eq!(effective.arguments().as_bytes(), b"two");
    assert!(settled.is_none());
}

#[test]
fn an_empty_modified_name_is_a_typed_registration_attributed_failure() {
    let hook = CallbackHook::new(|scope| {
        ToolCallDecision::Modify(call("spoofed", "", scope.call().arguments().as_bytes()))
    });
    let registry = registry(vec![
        hook::Registration::new("empty-name".into()).tool(hook),
    ]);
    let session = Session::new("session".into(), None);
    let reader = session.state();
    let coord = Coord::at_run("session".into(), "run".into()).unwrap();
    let states = [run_state::Store::new()];
    let emitter = NoopEmitter;
    let resources = resources(&coord, &states, &reader, &emitter);

    let error = prepare_tool_calls(
        vec![call("original", "tool", b"{}")],
        &registry,
        &resources,
        snapshot(),
        &Token::new(),
    )
    .err()
    .expect("the empty effective name is rejected");

    let DispatchError::Callback(failure) = error else {
        panic!("an invalid hook decision is not cancellation");
    };
    assert_eq!(failure.name(), "empty-name");
    assert!(matches!(
        failure.error().source_ref().downcast_ref::<super::model::RequestError>(),
        Some(super::model::RequestError::EmptyToolCallName { call_id }) if call_id == "original"
    ));
}

#[test]
fn block_and_short_circuit_settle_immediately_and_stop_later_hooks() {
    let later_calls = Arc::new(Mutex::new(Vec::new()));
    let deciding = CallbackHook::new(|scope| match scope.call().id().as_str() {
        "blocked" => ToolCallDecision::Block("policy".into()),
        _ => ToolCallDecision::ShortCircuit(ToolResult::success_text("cached".into())),
    });
    let later_log = Arc::clone(&later_calls);
    let later = CallbackHook::new(move |scope| {
        later_log
            .lock()
            .unwrap()
            .push(scope.call().id().as_str().to_owned());
        ToolCallDecision::Continue
    });
    let registry = registry(vec![
        hook::Registration::new("deciding".into()).tool(deciding),
        hook::Registration::new("later".into()).tool(later),
    ]);
    let session = Session::new("session".into(), None);
    let reader = session.state();
    let coord = Coord::at_run("session".into(), "run".into()).unwrap();
    let states = [run_state::Store::new(), run_state::Store::new()];
    let emitter = NoopEmitter;
    let resources = resources(&coord, &states, &reader, &emitter);
    let plan = prepare_tool_calls(
        vec![call("blocked", "a", b"{}"), call("short", "b", b"{}")],
        &registry,
        &resources,
        snapshot(),
        &Token::new(),
    )
    .unwrap();

    assert!(later_calls.lock().unwrap().is_empty());
    let entries = plan.into_entries();
    let blocked = entries[0].settled().unwrap();
    assert_eq!(blocked.disposition(), SettledDisposition::Blocked);
    assert!(blocked.result().is_business_error());
    assert_eq!(
        blocked.result().output().unwrap().user_view(),
        Some("blocked: policy")
    );
    let short = entries[1].settled().unwrap();
    assert_eq!(short.disposition(), SettledDisposition::ShortCircuited);
    assert_eq!(short.result().output().unwrap().user_view(), Some("cached"));

    for disposition in [
        SettledDisposition::Truncated,
        SettledDisposition::NotExecuted,
    ] {
        let (result, retained) =
            PreparedSettlement::new(ToolResult::no_output(), disposition).into_parts();
        assert!(!result.has_output());
        assert_eq!(retained, disposition);
    }
}

#[test]
fn cancellation_and_callback_errors_fail_the_whole_batch_without_later_work() {
    let calls = Arc::new(Mutex::new(Vec::new()));
    let token = Token::new();
    let callback_token = token.clone();
    let callback_calls = Arc::clone(&calls);
    let hook = CallbackHook::new(move |scope| {
        callback_calls
            .lock()
            .unwrap()
            .push(scope.call().id().as_str().to_owned());
        if scope.call().id().as_str() == "second" {
            callback_token.cancel();
        }
        ToolCallDecision::Continue
    });
    let cancel_registry = registry(vec![hook::Registration::new("cancel".into()).tool(hook)]);
    let session = Session::new("session".into(), None);
    let reader = session.state();
    let coord = Coord::at_run("session".into(), "run".into()).unwrap();
    let states = [run_state::Store::new()];
    let emitter = NoopEmitter;
    let resources = resources(&coord, &states, &reader, &emitter);
    let result = prepare_tool_calls(
        vec![
            call("first", "a", b"{}"),
            call("second", "b", b"{}"),
            call("third", "c", b"{}"),
        ],
        &cancel_registry,
        &resources,
        snapshot(),
        &token,
    );
    assert!(matches!(result, Err(DispatchError::Cancelled)));
    assert_eq!(*calls.lock().unwrap(), ["first", "second"]);

    let pre_cancelled = Token::new();
    pre_cancelled.cancel();
    let before = calls.lock().unwrap().len();
    assert!(matches!(
        prepare_tool_calls(
            vec![call("never", "x", b"{}")],
            &cancel_registry,
            &resources,
            snapshot(),
            &pre_cancelled,
        ),
        Err(DispatchError::Cancelled)
    ));
    assert_eq!(calls.lock().unwrap().len(), before);

    let error_token = Token::new();
    let callback_token = error_token.clone();
    let failing = FallibleCallbackHook::new(move |_scope| {
        callback_token.cancel();
        Err(HookError::new(TestError))
    });
    let failing_registry = registry(vec![
        hook::Registration::new("failing".into()).tool(failing),
    ]);
    let error = prepare_tool_calls(
        vec![call("error", "x", b"{}")],
        &failing_registry,
        &resources,
        snapshot(),
        &error_token,
    )
    .err()
    .unwrap();
    match error {
        DispatchError::Callback(failure) => {
            assert_eq!(failure.name(), "failing");
            assert_eq!(failure.error().to_string(), "callback failed");
        }
        DispatchError::Cancelled => panic!("callback error must outrank cancellation"),
    }
}

#[test]
fn callback_resources_remain_isolated_at_full_registration_indexes() {
    let key = run_state::Key::<String>::new();
    let observations = Arc::new(Mutex::new(Vec::new()));
    let first_key = key.clone();
    let first_observations = Arc::clone(&observations);
    let first = CallbackHook::new(move |scope| {
        first_observations
            .lock()
            .unwrap()
            .push(scope.run_state().load(&first_key).is_none());
        scope.run_state().set(&first_key, Arc::new("first".into()));
        ToolCallDecision::Continue
    });
    let second_key = key.clone();
    let second_observations = Arc::clone(&observations);
    let second = CallbackHook::new(move |scope| {
        second_observations
            .lock()
            .unwrap()
            .push(scope.run_state().load(&second_key).is_none());
        scope
            .run_state()
            .set(&second_key, Arc::new("second".into()));
        ToolCallDecision::Continue
    });
    let registry = registry(vec![
        hook::Registration::new("metadata-only".into()),
        hook::Registration::new("first".into()).tool(first),
        hook::Registration::new("second".into()).tool(second),
    ]);
    let session = Session::new("session".into(), None);
    let reader = session.state();
    let coord = Coord::at_run("session".into(), "run".into()).unwrap();
    let states = [
        run_state::Store::new(),
        run_state::Store::new(),
        run_state::Store::new(),
    ];
    let emitter = NoopEmitter;
    let resources = resources(&coord, &states, &reader, &emitter);
    let plan = prepare_tool_calls(
        vec![call("one", "tool", b"{}")],
        &registry,
        &resources,
        snapshot(),
        &Token::new(),
    )
    .unwrap();

    assert_eq!(*observations.lock().unwrap(), [true, true]);
    assert!(states[0].load(&key).is_none());
    assert_eq!(states[1].load(&key).unwrap().as_str(), "first");
    assert_eq!(states[2].load(&key).unwrap().as_str(), "second");
    assert_eq!(plan.entries().len(), 1);
}