rig-compose 0.4.1

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
//! Reliability primitives for tool dispatch loops.
//!
//! This module groups three small, host-driven utilities that downstream
//! agents combine when wrapping a normalized tool loop:
//!
//! 1. [`RetryClass`] + [`RetryClassifier`] — turn a [`KernelError`] into a
//!    deterministic "should I retry this call?" verdict. The default impl
//!    ([`DefaultRetryClassifier`]) covers every existing
//!    `KernelError` variant; hosts can supply a custom classifier when they
//!    layer in transport-specific errors (timeouts, rate limits, etc.) by
//!    chaining or overriding.
//! 2. [`ToolCallFingerprint`] — a stable, content-addressed hash of a
//!    [`ToolInvocation`] (tool name + canonical JSON args). Used to detect
//!    repeated calls and group retry attempts.
//! 3. [`HistoryEntry`] + [`repair_history`] — deterministic coalescing of
//!    a raw `(invocation, outcome)` sequence into the smallest history the
//!    model should see. Multiple retries of the same fingerprint collapse to
//!    a single canonical entry; the host stays in control of how many
//!    physical retries actually happened.
//!
//! These primitives are intentionally synchronous and infallible: they
//! operate on already-materialized invocations and outcomes, never on live
//! transports.
//!
//! # Example
//!
//! ```no_run
//! use rig_compose::{
//!     DefaultRetryClassifier, HistoryEntry, KernelError, RetryClass,
//!     RetryClassifier, ToolInvocation, repair_history,
//! };
//! use serde_json::json;
//!
//! let classifier = DefaultRetryClassifier;
//! let inv = ToolInvocation::new("search", json!({"q": "rig"})).expect("valid");
//! let history = vec![
//!     HistoryEntry::Failed {
//!         invocation: inv.clone(),
//!         class: classifier.classify(&KernelError::ToolFailed("timeout".into())),
//!         message: "timeout".into(),
//!     },
//!     HistoryEntry::Completed {
//!         invocation: inv,
//!         output: json!({"hits": 3}),
//!     },
//! ];
//! let repaired = repair_history(&history);
//! assert_eq!(repaired.len(), 1);
//! assert!(matches!(repaired[0], HistoryEntry::Completed { .. }));
//! ```

use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

use serde_json::Value;

use crate::normalizer::{ToolInvocation, ToolInvocationResult};
use crate::registry::KernelError;

// ── Retry classification ─────────────────────────────────────────────────────

/// Deterministic verdict on whether an errored tool invocation may be retried.
///
/// `Transient` means the failure was likely environmental (network blip, flaky
/// dependency) and a retry has a real chance of succeeding. `Permanent` means
/// the inputs or policy are wrong and retrying would just waste the budget.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RetryClass {
    /// Retry is allowed; the failure is likely environmental.
    Transient,
    /// Retry is forbidden; the failure is intrinsic to the inputs or policy.
    Permanent,
}

/// Classify a [`KernelError`] as transient or permanent.
///
/// Hosts can implement this trait to inject transport-specific knowledge
/// (e.g. mapping HTTP 5xx onto `Transient` and 4xx onto `Permanent`). The
/// crate ships [`DefaultRetryClassifier`] as a starting point that covers
/// every current `KernelError` variant.
pub trait RetryClassifier: Send + Sync {
    /// Return the retry verdict for `error`.
    fn classify(&self, error: &KernelError) -> RetryClass;
}

/// Default classifier covering every [`KernelError`] variant.
///
/// The mapping is conservative: anything that *could* be a flake (the tool
/// body errored, a skill body errored) is `Transient`. Everything that
/// signals a permanent disagreement (auth, missing names, invalid args,
/// budget exhaustion, dispatch termination, JSON parse errors) is
/// `Permanent`.
#[derive(Debug, Clone, Copy, Default)]
pub struct DefaultRetryClassifier;

impl RetryClassifier for DefaultRetryClassifier {
    fn classify(&self, error: &KernelError) -> RetryClass {
        match error {
            // Body errors — likely environmental, may succeed on retry.
            KernelError::ToolFailed(_) | KernelError::SkillFailed(_) => RetryClass::Transient,

            // Configuration / policy / argument errors — retrying with the
            // same inputs cannot help.
            KernelError::ToolNotFound(_)
            | KernelError::ToolNotAuthorised(_)
            | KernelError::SkillNotFound(_)
            | KernelError::ToolNotApplicable(_)
            | KernelError::InvalidArgument(_)
            | KernelError::NormalizerFailed(_)
            | KernelError::ToolDispatchTerminated(_)
            | KernelError::BudgetFailed(_)
            | KernelError::Serde(_) => RetryClass::Permanent,
        }
    }
}

// ── Fingerprints ─────────────────────────────────────────────────────────────

/// Stable content hash of a [`ToolInvocation`].
///
/// Two invocations with the same tool name and the same canonical JSON
/// arguments produce the same fingerprint, regardless of which dispatch
/// attempt produced them. Uses `std::collections::hash_map::DefaultHasher`,
/// so values are stable within a single process run but should not be
/// persisted across versions.
///
/// Determinism relies on `serde_json::Map`'s default key ordering
/// (`BTreeMap`-backed). If a downstream crate enables the `preserve_order`
/// feature globally, fingerprints will no longer be argument-order-independent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ToolCallFingerprint(pub u64);

impl ToolInvocation {
    /// Return a stable fingerprint over `(name, canonical(args))`.
    ///
    /// Suitable as a hash-map key to group retry attempts of the same
    /// logical call, or to detect a stuck-loop pattern where the model
    /// keeps reissuing identical calls.
    pub fn fingerprint(&self) -> ToolCallFingerprint {
        let mut hasher = DefaultHasher::new();
        self.name.hash(&mut hasher);
        // Serializing through serde_json gives a canonical form because
        // `serde_json::Map` is BTreeMap-backed without `preserve_order`.
        canonicalize_value(&self.args).to_string().hash(&mut hasher);
        ToolCallFingerprint(hasher.finish())
    }
}

/// Re-serialize `value` to a canonical form for hashing.
///
/// `serde_json::Value::to_string` is already deterministic when the
/// `preserve_order` feature is off, but going through a normalize step
/// makes that contract explicit and gives us a single hook to add float
/// canonicalization later if needed.
fn canonicalize_value(value: &Value) -> Value {
    match value {
        Value::Array(items) => Value::Array(items.iter().map(canonicalize_value).collect()),
        Value::Object(map) => {
            let mut out = serde_json::Map::new();
            for (key, inner) in map {
                out.insert(key.clone(), canonicalize_value(inner));
            }
            Value::Object(out)
        }
        other => other.clone(),
    }
}

// ── History repair ───────────────────────────────────────────────────────────

/// One entry in a tool-call history slice fed back to the model.
#[derive(Debug, Clone, PartialEq)]
pub enum HistoryEntry {
    /// The invocation completed and produced `output`.
    Completed {
        /// The invocation that ran.
        invocation: ToolInvocation,
        /// The JSON result the tool returned.
        output: Value,
    },
    /// The invocation failed; `class` records the retry verdict and
    /// `message` carries the error rendering.
    Failed {
        /// The invocation that failed.
        invocation: ToolInvocation,
        /// Retry verdict from a [`RetryClassifier`].
        class: RetryClass,
        /// `error.to_string()` of the underlying [`KernelError`].
        message: String,
    },
}

impl HistoryEntry {
    /// Return the fingerprint of this entry's invocation.
    pub fn fingerprint(&self) -> ToolCallFingerprint {
        match self {
            HistoryEntry::Completed { invocation, .. }
            | HistoryEntry::Failed { invocation, .. } => invocation.fingerprint(),
        }
    }

    /// Convenience: build a `Completed` entry from a [`ToolInvocationResult`].
    pub fn completed(result: ToolInvocationResult) -> Self {
        HistoryEntry::Completed {
            invocation: result.invocation,
            output: result.output,
        }
    }

    /// Convenience: classify `error` with `classifier` and build a `Failed`
    /// entry that records the verdict and the error rendering.
    pub fn failed<C: RetryClassifier>(
        invocation: ToolInvocation,
        error: &KernelError,
        classifier: &C,
    ) -> Self {
        HistoryEntry::Failed {
            invocation,
            class: classifier.classify(error),
            message: error.to_string(),
        }
    }
}

/// Deterministically coalesce a tool-call history.
///
/// The repair rule is:
///
/// 1. Walk `entries` in order, grouping by [`ToolCallFingerprint`].
/// 2. For each group, if **any** entry is [`HistoryEntry::Completed`],
///    keep the **first** completion (idempotent: once we have a real
///    answer, later retries don't change the story).
/// 3. Otherwise keep the **last** [`HistoryEntry::Failed`] for that
///    fingerprint (most recent verdict wins for terminal failures).
/// 4. Emit results in **first-occurrence order** of each fingerprint.
///
/// The transform is total, deterministic, and idempotent
/// (`repair_history(repair_history(x)) == repair_history(x)`).
pub fn repair_history(entries: &[HistoryEntry]) -> Vec<HistoryEntry> {
    // Track first-seen position per fingerprint so output preserves order,
    // and the chosen entry index per fingerprint.
    let mut order: Vec<ToolCallFingerprint> = Vec::new();
    let mut chosen: std::collections::HashMap<ToolCallFingerprint, usize> =
        std::collections::HashMap::new();
    let mut has_completed: std::collections::HashSet<ToolCallFingerprint> =
        std::collections::HashSet::new();

    for (idx, entry) in entries.iter().enumerate() {
        let fp = entry.fingerprint();
        if let std::collections::hash_map::Entry::Vacant(slot) = chosen.entry(fp) {
            order.push(fp);
            slot.insert(idx);
            if matches!(entry, HistoryEntry::Completed { .. }) {
                has_completed.insert(fp);
            }
            continue;
        }
        match entry {
            HistoryEntry::Completed { .. } => {
                // Rule 2: keep the *first* completion. If we already have
                // one chosen and it's a completion, skip. If the chosen
                // one is a failure, replace it.
                if !has_completed.contains(&fp) {
                    chosen.insert(fp, idx);
                    has_completed.insert(fp);
                }
            }
            HistoryEntry::Failed { .. } => {
                // Rule 3: last failure wins, but only if we don't already
                // have a completion locked in.
                if !has_completed.contains(&fp) {
                    chosen.insert(fp, idx);
                }
            }
        }
    }

    order
        .into_iter()
        .filter_map(|fp| chosen.get(&fp).and_then(|&i| entries.get(i)).cloned())
        .collect()
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::indexing_slicing
)]
mod tests {
    use super::*;
    use serde_json::json;

    fn inv(name: &str, args: Value) -> ToolInvocation {
        ToolInvocation::new(name, args).unwrap()
    }

    // ── Classifier ───────────────────────────────────────────────────────

    #[test]
    fn default_classifier_marks_tool_failed_transient() {
        let c = DefaultRetryClassifier;
        assert_eq!(
            c.classify(&KernelError::ToolFailed("boom".into())),
            RetryClass::Transient,
        );
        assert_eq!(
            c.classify(&KernelError::SkillFailed("boom".into())),
            RetryClass::Transient,
        );
    }

    #[test]
    fn default_classifier_marks_policy_errors_permanent() {
        let c = DefaultRetryClassifier;
        for err in [
            KernelError::ToolNotFound("x".into()),
            KernelError::ToolNotAuthorised("x".into()),
            KernelError::SkillNotFound("x".into()),
            KernelError::ToolNotApplicable("x".into()),
            KernelError::InvalidArgument("x".into()),
            KernelError::NormalizerFailed("x".into()),
            KernelError::ToolDispatchTerminated("x".into()),
            KernelError::BudgetFailed("x".into()),
        ] {
            assert_eq!(c.classify(&err), RetryClass::Permanent, "{err:?}");
        }
    }

    // ── Fingerprints ────────────────────────────────────────────────────

    #[test]
    fn fingerprint_is_stable_for_same_invocation() {
        let a = inv("search", json!({"q": "rig", "limit": 5}));
        let b = inv("search", json!({"q": "rig", "limit": 5}));
        assert_eq!(a.fingerprint(), b.fingerprint());
    }

    #[test]
    fn fingerprint_is_order_independent_for_object_args() {
        let a = inv("search", json!({"q": "rig", "limit": 5}));
        let b = inv("search", json!({"limit": 5, "q": "rig"}));
        assert_eq!(a.fingerprint(), b.fingerprint());
    }

    #[test]
    fn fingerprint_differs_when_args_differ() {
        let a = inv("search", json!({"q": "rig"}));
        let b = inv("search", json!({"q": "tokio"}));
        assert_ne!(a.fingerprint(), b.fingerprint());
    }

    #[test]
    fn fingerprint_differs_when_tool_name_differs() {
        let a = inv("search", json!({"q": "rig"}));
        let b = inv("lookup", json!({"q": "rig"}));
        assert_ne!(a.fingerprint(), b.fingerprint());
    }

    // ── History repair ──────────────────────────────────────────────────

    #[test]
    fn repair_keeps_first_completion_after_retries() {
        let i = inv("search", json!({"q": "rig"}));
        let history = vec![
            HistoryEntry::Failed {
                invocation: i.clone(),
                class: RetryClass::Transient,
                message: "timeout".into(),
            },
            HistoryEntry::Completed {
                invocation: i.clone(),
                output: json!({"hits": 1}),
            },
            HistoryEntry::Completed {
                invocation: i,
                output: json!({"hits": 99}),
            },
        ];
        let repaired = repair_history(&history);
        assert_eq!(repaired.len(), 1);
        match &repaired[0] {
            HistoryEntry::Completed { output, .. } => assert_eq!(output, &json!({"hits": 1})),
            other => panic!("expected Completed, got {other:?}"),
        }
    }

    #[test]
    fn repair_keeps_last_failure_when_no_completion() {
        let i = inv("search", json!({"q": "rig"}));
        let history = vec![
            HistoryEntry::Failed {
                invocation: i.clone(),
                class: RetryClass::Transient,
                message: "first".into(),
            },
            HistoryEntry::Failed {
                invocation: i,
                class: RetryClass::Permanent,
                message: "last".into(),
            },
        ];
        let repaired = repair_history(&history);
        assert_eq!(repaired.len(), 1);
        match &repaired[0] {
            HistoryEntry::Failed { message, class, .. } => {
                assert_eq!(message, "last");
                assert_eq!(*class, RetryClass::Permanent);
            }
            other => panic!("expected Failed, got {other:?}"),
        }
    }

    #[test]
    fn repair_preserves_first_occurrence_order_across_fingerprints() {
        let a = inv("a", json!({"k": 1}));
        let b = inv("b", json!({"k": 2}));
        let history = vec![
            HistoryEntry::Completed {
                invocation: a.clone(),
                output: json!(null),
            },
            HistoryEntry::Completed {
                invocation: b.clone(),
                output: json!(null),
            },
            HistoryEntry::Completed {
                invocation: a,
                output: json!("ignored"),
            },
        ];
        let repaired = repair_history(&history);
        assert_eq!(repaired.len(), 2);
        // First entry is the first occurrence of `a`.
        assert_eq!(
            repaired[0].fingerprint(),
            inv("a", json!({"k": 1})).fingerprint()
        );
        assert_eq!(
            repaired[1].fingerprint(),
            inv("b", json!({"k": 2})).fingerprint()
        );
    }

    #[test]
    fn repair_is_idempotent() {
        let i = inv("search", json!({"q": "rig"}));
        let history = vec![
            HistoryEntry::Failed {
                invocation: i.clone(),
                class: RetryClass::Transient,
                message: "x".into(),
            },
            HistoryEntry::Completed {
                invocation: i,
                output: json!({"ok": true}),
            },
        ];
        let once = repair_history(&history);
        let twice = repair_history(&once);
        assert_eq!(once, twice);
    }

    #[test]
    fn repair_on_empty_history_returns_empty() {
        assert!(repair_history(&[]).is_empty());
    }

    #[test]
    fn history_entry_failed_helper_records_classifier_verdict() {
        let entry = HistoryEntry::failed(
            inv("search", json!({"q": "rig"})),
            &KernelError::ToolFailed("flake".into()),
            &DefaultRetryClassifier,
        );
        match entry {
            HistoryEntry::Failed { class, message, .. } => {
                assert_eq!(class, RetryClass::Transient);
                assert!(message.contains("flake"));
            }
            other => panic!("expected Failed, got {other:?}"),
        }
    }
}