rig-compose 0.3.0

Composable agent kernel: stateless skills, transport-agnostic tools, registry-driven agents, signal-routing coordinator. Companion crate for rig.
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
//! Integration tests for [`rig_compose::normalizer`].
//!
//! These tests exercise the normalizer through the public API surface
//! (re-exported from the crate root) to validate the full end-to-end path
//! from raw model output to structured tool invocations.

use rig_compose::normalizer::{LfmNormalizer, StructuredToolCallNormalizer, ToolCallNormalizer};
use rig_compose::{
    AtomicBudget, DispatchBudgetHook, KernelError, LocalTool, ToolDispatchAction, ToolDispatchHook,
    ToolInvocation, ToolInvocationResult, ToolRegistry, ToolSchema, dispatch_tool_invocations,
    dispatch_tool_invocations_with_hooks,
};
use serde_json::json;
use std::sync::{Arc, Mutex};

use async_trait::async_trait;

// ── Realistic LFM output patterns ────────────────────────────────────────────

#[test]
fn full_llm_response_with_preamble_and_postamble() {
    // Real model output often wraps the marker in surrounding text.
    let raw = concat!(
        "I'll look up the weather for you.\n",
        "<|tool_call_start|>[get_weather(city='Berlin', units='metric')]<|tool_call_end|>\n",
        "Let me know if you need anything else.",
    );
    let calls = LfmNormalizer.normalize(raw).unwrap();
    assert_eq!(calls.len(), 1);
    assert_eq!(calls[0].name, "get_weather");
    assert_eq!(calls[0].args, json!({"city": "Berlin", "units": "metric"}));
}

#[test]
fn chained_tool_calls_two_separate_blocks() {
    // Model emits two sequential tool calls as separate blocks.
    let raw = concat!(
        "<|tool_call_start|>[fetch_url(url='https://example.com')]<|tool_call_end|>\n",
        "<|tool_call_start|>[parse_html(selector='h1')]<|tool_call_end|>",
    );
    let calls = LfmNormalizer.normalize(raw).unwrap();
    assert_eq!(calls.len(), 2);
    assert_eq!(calls[0].name, "fetch_url");
    assert_eq!(calls[1].name, "parse_html");
}

#[test]
fn parallel_tool_calls_in_one_block() {
    // Model batches multiple calls in a single marker.
    let raw = "<|tool_call_start|>[search(q='rust'), search(q='tokio')]<|tool_call_end|>";
    let calls = LfmNormalizer.normalize(raw).unwrap();
    assert_eq!(calls.len(), 2);
    assert_eq!(calls[0].args, json!({"q": "rust"}));
    assert_eq!(calls[1].args, json!({"q": "tokio"}));
}

#[test]
fn no_tool_call_in_response() {
    let raw = "The answer to your question is 42. No tools are needed.";
    let calls = LfmNormalizer.normalize(raw).unwrap();
    assert!(calls.is_empty());
}

// ── Argument type coverage ────────────────────────────────────────────────────

#[test]
fn mixed_arg_types() {
    let raw = "<|tool_call_start|>[configure(name='agent', limit=100, ratio=0.5, debug=True, ctx=None)]<|tool_call_end|>";
    let calls = LfmNormalizer.normalize(raw).unwrap();
    assert_eq!(calls.len(), 1);
    let args = &calls[0].args;
    assert_eq!(args["name"], json!("agent"));
    assert_eq!(args["limit"], json!(100));
    assert_eq!(args["ratio"].as_f64().unwrap(), 0.5_f64);
    assert_eq!(args["debug"], json!(true));
    assert_eq!(args["ctx"], json!(null));
}

#[test]
fn string_with_comma_in_value() {
    // Comma inside quoted string must not split the kwarg list.
    let raw = "<|tool_call_start|>[translate(text='hello, world', lang='es')]<|tool_call_end|>";
    let calls = LfmNormalizer.normalize(raw).unwrap();
    assert_eq!(calls.len(), 1);
    assert_eq!(calls[0].args["text"], json!("hello, world"));
    assert_eq!(calls[0].args["lang"], json!("es"));
}

#[test]
fn negative_integer_arg() {
    let raw = "<|tool_call_start|>[offset(n=-5)]<|tool_call_end|>";
    let calls = LfmNormalizer.normalize(raw).unwrap();
    assert_eq!(calls[0].args["n"], json!(-5));
}

#[test]
fn nested_list_and_object_args() {
    let raw = "<|tool_call_start|>[plan(items=['a,b', 'c'], meta={'city': 'Berlin', 'coords': [52.52, 13.405], 'active': True})]<|tool_call_end|>";
    let calls = LfmNormalizer.normalize(raw).unwrap();
    assert_eq!(calls.len(), 1);
    assert_eq!(
        calls[0].args,
        json!({
            "items": ["a,b", "c"],
            "meta": {
                "city": "Berlin",
                "coords": [52.52, 13.405],
                "active": true
            }
        })
    );
}

// ── Structured standards ─────────────────────────────────────────────────────

#[test]
fn openai_responses_output_normalizes_to_invocation() {
    let value = json!({
        "id": "resp_123",
        "output": [{
            "type": "function_call",
            "id": "fc_123",
            "call_id": "call_123",
            "name": "get_weather",
            "arguments": "{\"city\":\"Berlin\"}",
            "status": "completed"
        }]
    });

    let calls = StructuredToolCallNormalizer::normalize_openai_responses(&value).unwrap();
    assert_eq!(calls.len(), 1);
    assert_eq!(calls[0].name, "get_weather");
    assert_eq!(calls[0].args, json!({"city": "Berlin"}));
}

#[test]
fn openai_chat_completions_tool_calls_normalize_to_invocation() {
    let value = json!({
        "choices": [{
            "message": {
                "role": "assistant",
                "content": null,
                "tool_calls": [{
                    "id": "call_123",
                    "type": "function",
                    "function": {
                        "name": "get_weather",
                        "arguments": {"city": "Berlin"}
                    }
                }]
            }
        }]
    });

    let calls = StructuredToolCallNormalizer::normalize_openai_chat_completions(&value).unwrap();
    assert_eq!(calls.len(), 1);
    assert_eq!(calls[0].name, "get_weather");
    assert_eq!(calls[0].args, json!({"city": "Berlin"}));
}

#[test]
fn unsupported_structured_payload_returns_empty() {
    let value = json!({"output": [{"type": "message", "content": []}]});
    let calls = StructuredToolCallNormalizer::normalize(&value).unwrap();
    assert!(calls.is_empty());
}

// ── Error paths ───────────────────────────────────────────────────────────────

#[test]
fn unclosed_start_marker_is_an_error() {
    let raw = "<|tool_call_start|>[get_weather(city='Berlin')]";
    let err = LfmNormalizer.normalize(raw).unwrap_err();
    assert!(
        matches!(err, KernelError::NormalizerFailed(_)),
        "expected NormalizerFailed, got: {err:?}"
    );
}

#[test]
fn error_message_mentions_unclosed() {
    let raw = "<|tool_call_start|>[incomplete(";
    let err = LfmNormalizer.normalize(raw).unwrap_err();
    assert!(err.to_string().contains("unclosed"), "got: {err}");
}

#[test]
fn kwarg_without_equals_is_an_error() {
    let raw = "<|tool_call_start|>[fn(positional_only)]<|tool_call_end|>";
    let err = LfmNormalizer.normalize(raw).unwrap_err();
    assert!(
        matches!(err, KernelError::NormalizerFailed(_)),
        "expected NormalizerFailed, got: {err:?}"
    );
}

#[test]
fn malformed_identifiers_are_errors() {
    let raw = "<|tool_call_start|>[bad/name(arg=1)]<|tool_call_end|>";
    let err = LfmNormalizer.normalize(raw).unwrap_err();
    assert!(
        matches!(err, KernelError::NormalizerFailed(_)),
        "expected NormalizerFailed, got: {err:?}"
    );
    assert!(err.to_string().contains("invalid tool name"));
}

#[test]
fn duplicate_kwargs_are_errors() {
    let raw = "<|tool_call_start|>[fn(city='Berlin', city='Paris')]<|tool_call_end|>";
    let err = LfmNormalizer.normalize(raw).unwrap_err();
    assert!(
        matches!(err, KernelError::NormalizerFailed(_)),
        "expected NormalizerFailed, got: {err:?}"
    );
    assert!(err.to_string().contains("duplicate kwarg"));
}

#[tokio::test]
async fn normalized_invocations_dispatch_through_tool_registry() {
    let tools = ToolRegistry::new();
    tools.register(Arc::new(LocalTool::new(
        ToolSchema {
            name: "get_weather".into(),
            description: "gets weather".into(),
            args_schema: json!({"type": "object"}),
            result_schema: json!({"type": "object"}),
        },
        |args| async move { Ok(json!({"forecast": "sunny", "args": args})) },
    )));

    let invocations = LfmNormalizer
        .normalize("<|tool_call_start|>[get_weather(city='Berlin')]<|tool_call_end|>")
        .unwrap();
    let results = dispatch_tool_invocations(&tools, &invocations)
        .await
        .unwrap();

    assert_eq!(results.len(), 1);
    assert_eq!(results[0].invocation.name, "get_weather");
    assert_eq!(
        results[0].output,
        json!({"forecast": "sunny", "args": {"city": "Berlin"}})
    );
}

#[tokio::test]
async fn structured_standard_invocations_dispatch_through_tool_registry() {
    let tools = ToolRegistry::new();
    tools.register(Arc::new(LocalTool::new(
        ToolSchema {
            name: "get_weather".into(),
            description: "gets weather".into(),
            args_schema: json!({"type": "object"}),
            result_schema: json!({"type": "object"}),
        },
        |args| async move { Ok(json!({"forecast": "clear", "args": args})) },
    )));

    let value = json!({
        "output": [{
            "type": "function_call",
            "name": "get_weather",
            "arguments": "{\"city\":\"Berlin\"}"
        }]
    });
    let invocations = StructuredToolCallNormalizer::normalize(&value).unwrap();
    let results = dispatch_tool_invocations(&tools, &invocations)
        .await
        .unwrap();

    assert_eq!(results.len(), 1);
    assert_eq!(results[0].invocation.name, "get_weather");
    assert_eq!(
        results[0].output,
        json!({"forecast": "clear", "args": {"city": "Berlin"}})
    );
}

#[tokio::test]
async fn dispatch_hooks_record_after_invocation() {
    let tools = weather_registry("clear");
    let hook = RecordingHook::default();
    let invocations = LfmNormalizer
        .normalize("<|tool_call_start|>[get_weather(city='Berlin')]<|tool_call_end|>")
        .unwrap();

    let results = dispatch_tool_invocations_with_hooks(&tools, &invocations, &[&hook])
        .await
        .unwrap();

    assert_eq!(results.len(), 1);
    assert_eq!(
        hook.events(),
        vec!["before:get_weather", "after:get_weather"]
    );
}

#[tokio::test]
async fn dispatch_hooks_can_skip_with_synthetic_output() {
    let tools = weather_registry("clear");
    let hook = SkipWeatherHook;
    let invocations = LfmNormalizer
        .normalize("<|tool_call_start|>[get_weather(city='Berlin')]<|tool_call_end|>")
        .unwrap();

    let results = dispatch_tool_invocations_with_hooks(&tools, &invocations, &[&hook])
        .await
        .unwrap();

    assert_eq!(results.len(), 1);
    assert_eq!(
        results[0].output,
        json!({"city": "Berlin", "forecast": "policy-supplied"})
    );
}

#[tokio::test]
async fn dispatch_hooks_can_terminate_before_tool_invocation() {
    let tools = weather_registry("clear");
    let hook = TerminateHook;
    let invocations = LfmNormalizer
        .normalize("<|tool_call_start|>[get_weather(city='Berlin')]<|tool_call_end|>")
        .unwrap();

    let err = dispatch_tool_invocations_with_hooks(&tools, &invocations, &[&hook])
        .await
        .unwrap_err();

    assert!(matches!(err, KernelError::ToolDispatchTerminated(_)));
    assert!(err.to_string().contains("approval required"));
}

#[tokio::test]
async fn dispatch_budget_hook_releases_after_success() {
    let tools = weather_registry("clear");
    let budget = Arc::new(AtomicBudget::new(1));
    let hook = DispatchBudgetHook::new(budget.clone(), 1);
    let invocations = LfmNormalizer
        .normalize("<|tool_call_start|>[get_weather(city='Berlin')]<|tool_call_end|>")
        .unwrap();

    let results = dispatch_tool_invocations_with_hooks(&tools, &invocations, &[&hook])
        .await
        .unwrap();

    assert_eq!(results.len(), 1);
    assert_eq!(budget.available(), 1);
}

#[tokio::test]
async fn dispatch_budget_hook_terminates_when_budget_is_denied() {
    let tools = weather_registry("clear");
    let budget = Arc::new(AtomicBudget::new(0));
    let hook = DispatchBudgetHook::new(budget, 1);
    let invocations = LfmNormalizer
        .normalize("<|tool_call_start|>[get_weather(city='Berlin')]<|tool_call_end|>")
        .unwrap();

    let err = dispatch_tool_invocations_with_hooks(&tools, &invocations, &[&hook])
        .await
        .unwrap_err();

    assert!(matches!(err, KernelError::ToolDispatchTerminated(_)));
    assert!(err.to_string().contains("budget denied"));
}

#[tokio::test]
async fn dispatch_budget_hook_releases_after_tool_error() {
    let tools = failing_registry();
    let budget = Arc::new(AtomicBudget::new(1));
    let hook = DispatchBudgetHook::new(budget.clone(), 1);
    let invocations = LfmNormalizer
        .normalize("<|tool_call_start|>[get_weather(city='Berlin')]<|tool_call_end|>")
        .unwrap();

    let err = dispatch_tool_invocations_with_hooks(&tools, &invocations, &[&hook])
        .await
        .unwrap_err();

    assert!(matches!(err, KernelError::ToolFailed(_)));
    assert_eq!(budget.available(), 1);
}

#[tokio::test]
async fn dispatch_budget_hook_releases_when_later_hook_errors_in_before_invocation() {
    // Regression: a hook earlier in the chain reserved a slot before a
    // later hook returned `Err` from `before_invocation`. The reservation
    // must be released even though the failing hook never reserved
    // anything and was never given a chance to run `on_invocation_error`.
    let tools = weather_registry("clear");
    let budget = Arc::new(AtomicBudget::new(1));
    let budget_hook = DispatchBudgetHook::new(budget.clone(), 1);
    let failing_hook = ErroringBeforeHook;
    let invocations = LfmNormalizer
        .normalize("<|tool_call_start|>[get_weather(city='Berlin')]<|tool_call_end|>")
        .unwrap();

    let err =
        dispatch_tool_invocations_with_hooks(&tools, &invocations, &[&budget_hook, &failing_hook])
            .await
            .unwrap_err();

    assert!(matches!(err, KernelError::BudgetFailed(_)));
    assert_eq!(
        budget.available(),
        1,
        "earlier hook's reservation must be released"
    );
}

#[tokio::test]
async fn normalized_tool_results_can_drive_a_second_model_turn() {
    let tools = ToolRegistry::new();
    tools.register(Arc::new(LocalTool::new(
        ToolSchema {
            name: "get_weather".into(),
            description: "gets weather".into(),
            args_schema: json!({"type": "object"}),
            result_schema: json!({"type": "object"}),
        },
        |args| async move {
            Ok(json!({
                "city": args.get("city").and_then(|value| value.as_str()).unwrap_or("unknown"),
                "forecast": "clear and cool"
            }))
        },
    )));

    let run = run_deterministic_tool_loop_harness(
        &tools,
        "What is the weather like in Berlin today?",
        "<|tool_call_start|>[get_weather(city='Berlin')]<|tool_call_end|>",
    )
    .await
    .unwrap();

    assert_eq!(run.task, "What is the weather like in Berlin today?");
    assert!(run.first_model_output.contains("<|tool_call_start|>"));
    assert_eq!(run.invocations.len(), 1);
    assert_eq!(run.dispatch_results.len(), 1);
    assert_eq!(run.dispatch_results[0].invocation.name, "get_weather");
    assert!(run.final_answer.contains("Berlin"));
    assert!(run.final_answer.contains("clear and cool"));
    assert_eq!(
        run.passed_assertions,
        vec![
            "model-output-normalized",
            "tool-dispatched",
            "final-answer-grounded"
        ]
    );
}

struct DeterministicToolLoopHarnessRun {
    task: String,
    first_model_output: String,
    invocations: Vec<ToolInvocation>,
    dispatch_results: Vec<ToolInvocationResult>,
    final_answer: String,
    passed_assertions: Vec<&'static str>,
}

async fn run_deterministic_tool_loop_harness(
    tools: &ToolRegistry,
    task: &str,
    first_model_output: &str,
) -> Result<DeterministicToolLoopHarnessRun, KernelError> {
    let invocations = LfmNormalizer.normalize(first_model_output)?;
    let dispatch_results = dispatch_tool_invocations(tools, &invocations).await?;
    let final_answer = fake_second_model_turn(&dispatch_results);
    let passed_assertions = harness_assertions(&invocations, &dispatch_results, &final_answer);

    Ok(DeterministicToolLoopHarnessRun {
        task: task.to_string(),
        first_model_output: first_model_output.to_string(),
        invocations,
        dispatch_results,
        final_answer,
        passed_assertions,
    })
}

fn harness_assertions(
    invocations: &[ToolInvocation],
    dispatch_results: &[ToolInvocationResult],
    final_answer: &str,
) -> Vec<&'static str> {
    let mut passed = Vec::new();

    if !invocations.is_empty() {
        passed.push("model-output-normalized");
    }
    if dispatch_results
        .iter()
        .any(|result| result.invocation.name == "get_weather")
    {
        passed.push("tool-dispatched");
    }
    if final_answer.contains("Berlin") && final_answer.contains("clear and cool") {
        passed.push("final-answer-grounded");
    }

    passed
}

fn fake_second_model_turn(results: &[ToolInvocationResult]) -> String {
    results
        .first()
        .and_then(|result| {
            let city = result.output.get("city")?.as_str()?;
            let forecast = result.output.get("forecast")?.as_str()?;
            Some(format!("The weather in {city} is {forecast}."))
        })
        .unwrap_or_else(|| "No tool result was available.".to_string())
}

fn weather_registry(forecast: &'static str) -> ToolRegistry {
    let tools = ToolRegistry::new();
    tools.register(Arc::new(LocalTool::new(
        ToolSchema {
            name: "get_weather".into(),
            description: "gets weather".into(),
            args_schema: json!({"type": "object"}),
            result_schema: json!({"type": "object"}),
        },
        move |args| async move {
            Ok(json!({
                "city": args.get("city").and_then(|value| value.as_str()).unwrap_or("unknown"),
                "forecast": forecast
            }))
        },
    )));
    tools
}

fn failing_registry() -> ToolRegistry {
    let tools = ToolRegistry::new();
    tools.register(Arc::new(LocalTool::new(
        ToolSchema {
            name: "get_weather".into(),
            description: "fails weather lookup".into(),
            args_schema: json!({"type": "object"}),
            result_schema: json!({"type": "object"}),
        },
        |_args| async move { Err(KernelError::ToolFailed("weather offline".into())) },
    )));
    tools
}

#[derive(Default)]
struct RecordingHook {
    events: Mutex<Vec<String>>,
}

impl RecordingHook {
    fn events(&self) -> Vec<String> {
        self.events.lock().unwrap().clone()
    }
}

#[async_trait]
impl ToolDispatchHook for RecordingHook {
    async fn before_invocation(
        &self,
        invocation: &ToolInvocation,
    ) -> Result<ToolDispatchAction, KernelError> {
        self.events
            .lock()
            .unwrap()
            .push(format!("before:{}", invocation.name));
        Ok(ToolDispatchAction::Continue)
    }

    async fn after_invocation(&self, result: &ToolInvocationResult) -> Result<(), KernelError> {
        self.events
            .lock()
            .unwrap()
            .push(format!("after:{}", result.invocation.name));
        Ok(())
    }
}

struct SkipWeatherHook;

#[async_trait]
impl ToolDispatchHook for SkipWeatherHook {
    async fn before_invocation(
        &self,
        invocation: &ToolInvocation,
    ) -> Result<ToolDispatchAction, KernelError> {
        let city = invocation
            .args
            .get("city")
            .and_then(|value| value.as_str())
            .unwrap_or("unknown");
        Ok(ToolDispatchAction::Skip {
            output: json!({"city": city, "forecast": "policy-supplied"}),
        })
    }
}

struct TerminateHook;

#[async_trait]
impl ToolDispatchHook for TerminateHook {
    async fn before_invocation(
        &self,
        _invocation: &ToolInvocation,
    ) -> Result<ToolDispatchAction, KernelError> {
        Ok(ToolDispatchAction::Terminate {
            reason: "approval required".into(),
        })
    }
}

struct ErroringBeforeHook;

#[async_trait]
impl ToolDispatchHook for ErroringBeforeHook {
    async fn before_invocation(
        &self,
        _invocation: &ToolInvocation,
    ) -> Result<ToolDispatchAction, KernelError> {
        Err(KernelError::BudgetFailed("simulated denial".into()))
    }
}

// ── is_applicable guard ───────────────────────────────────────────────────────

#[test]
fn is_applicable_matches_exactly_when_marker_present() {
    assert!(LfmNormalizer.is_applicable("<|tool_call_start|>[fn()]<|tool_call_end|>"));
    assert!(!LfmNormalizer.is_applicable("plain prose with no markers"));
    assert!(!LfmNormalizer.is_applicable("<|tool_call_end|> only end marker"));
}