rig-agent 0.47.0

Rig's classic agent runtime.
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
use super::*;

/// The call the shared test events answer.
fn call_id() -> &'static CallId {
    static CALL: std::sync::OnceLock<CallId> = std::sync::OnceLock::new();
    CALL.get_or_init(|| CallId::from_wire("tc1"))
}

use crate::tool::{ToolErrorKind, ToolExecutionError};

/// Builds a dispatch event for `kind` answering the shared test block.
fn dispatch_event(kind: &EffectKind) -> DispatchEvent<'_> {
    DispatchEvent {
        id: EffectId::from_raw(1),
        kind,
        turn: 1,
        call_id: Some(call_id()),
        context: None,
    }
}

/// Builds an outcome event for `kind` that resolved to `outcome`.
fn outcome_event<'a>(
    kind: &'a EffectKind,
    outcome: &'a Result<Answered, ErrorReport>,
) -> OutcomeEvent<'a> {
    OutcomeEvent {
        id: EffectId::from_raw(1),
        kind,
        outcome,
        turn: 1,
        call_id: Some(call_id()),
        context: None,
    }
}

/// [`outcome_event`] with the context the tool answered with, beside the
/// outcome as the engine carries it (format 5).
fn outcome_event_with<'a>(
    kind: &'a EffectKind,
    outcome: &'a Result<Answered, ErrorReport>,
    context: &'a ToolContext,
) -> OutcomeEvent<'a> {
    OutcomeEvent {
        context: Some(context),
        ..outcome_event(kind, outcome)
    }
}

/// The arguments a `Patch` carries, parsed; `None` for anything else.
fn patched_args(action: &DispatchAction) -> Option<Value> {
    match action {
        DispatchAction::Patch(EffectKind::ToolCall { args, .. }) => {
            Some(serde_json::from_str(args).expect("patched args are JSON"))
        }
        _ => None,
    }
}

/// Asserts `action` skips the tool call with `reason`.
fn assert_skipped(action: &DispatchAction, reason: &str) {
    match action {
        DispatchAction::Deny(report) => {
            assert_eq!(report.kind, ErrorKind::Other);
            assert_eq!(report.message, reason);
        }
        other => panic!("expected a skip, got {other:?}"),
    }
}

/// The tool result a `Replace` carries; `None` for anything else.
fn replaced_result(action: &OutcomeAction) -> Option<&ToolResult> {
    match action {
        OutcomeAction::Replace(Ok(Answered::ToolResult { result, .. })) => Some(result),
        _ => None,
    }
}

#[derive(Clone)]
struct CallRewriter {
    seen: Arc<std::sync::Mutex<Vec<String>>>,
    replacement: serde_json::Value,
}

impl AgentHook for CallRewriter {
    async fn on_dispatch(&self, _ctx: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        let Some(args) = event.tool_args() else {
            return DispatchAction::proceed();
        };
        self.seen.lock().unwrap().push(args.to_string());
        DispatchAction::rewrite_tool_args(event.kind, self.replacement.clone())
    }
}

#[tokio::test]
async fn tool_call_rewrites_chain_in_registration_order() {
    let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
    let mut stack = HookStack::new();
    stack.push(CallRewriter {
        seen: seen.clone(),
        replacement: serde_json::json!({"step": 1}),
    });
    stack.push(CallRewriter {
        seen: seen.clone(),
        replacement: serde_json::json!({"step": 2}),
    });

    let kind = EffectKind::ToolCall {
        name: "tool".into(),
        args: r#"{"step":0}"#.into(),
    };
    let action = stack
        .on_dispatch(
            &HookContext::new(false, crate::handlers::Handlers::default()),
            dispatch_event(&kind),
        )
        .await;

    assert_eq!(
        *seen.lock().unwrap(),
        vec![r#"{"step":0}"#.to_string(), r#"{"step":1}"#.to_string()]
    );
    assert_eq!(patched_args(&action), Some(serde_json::json!({"step": 2})));
}

#[derive(Clone)]
struct ResultRewriter {
    seen: Arc<std::sync::Mutex<Vec<(String, ToolErrorKind, String)>>>,
    replacement: String,
}

#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)]
struct RequestMetadata(String);

impl rig_core::tool::ContextValue for RequestMetadata {
    const KEY: &'static str = "test.request_metadata";
}

impl AgentHook for ResultRewriter {
    async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
        let Some(result) = event.tool_result() else {
            return OutcomeAction::proceed();
        };
        self.seen.lock().unwrap().push((
            result.output().render(),
            result.error().unwrap().kind(),
            event
                .tool_context()
                .unwrap()
                .result::<RequestMetadata>()
                .unwrap()
                .unwrap()
                .0,
        ));
        OutcomeAction::rewrite_tool_result(&event, self.replacement.clone())
    }
}

#[tokio::test]
async fn result_rewrites_chain_without_mutating_raw_result_or_context() {
    let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
    let mut stack = HookStack::new();
    stack.push(ResultRewriter {
        seen: seen.clone(),
        replacement: "redacted".into(),
    });
    stack.push(ResultRewriter {
        seen: seen.clone(),
        replacement: "truncated".into(),
    });
    let raw = ToolResult::failed(ToolExecutionError::timeout("raw failure"));
    let mut context = ToolContext::new();
    context
        .insert_result(RequestMetadata("request-metadata".to_string()))
        .unwrap();

    let kind = tool_call_kind();
    let outcome = Ok(Answered::ToolResult {
        result: raw.clone(),
    });
    let action = stack
        .on_outcome(
            &HookContext::new(false, crate::handlers::Handlers::default()),
            outcome_event_with(&kind, &outcome, &context),
        )
        .await;

    let replaced = replaced_result(&action).expect("a rewritten tool result");
    assert_eq!(replaced.output().as_text(), Some("truncated"));
    // The rewrite keeps the result's status.
    assert_eq!(replaced.error().unwrap().kind(), ToolErrorKind::Timeout);
    assert_eq!(
        *seen.lock().unwrap(),
        vec![
            (
                "raw failure".into(),
                ToolErrorKind::Timeout,
                "request-metadata".into()
            ),
            (
                "redacted".into(),
                ToolErrorKind::Timeout,
                "request-metadata".into()
            ),
        ]
    );
    assert_eq!(raw.output().as_text(), Some("raw failure"));
    assert_eq!(
        context
            .result::<RequestMetadata>()
            .unwrap()
            .map(|m| m.0)
            .as_deref(),
        Some("request-metadata")
    );
}

// ---- hook stack composition and model-selection routing ----

use std::sync::{
    Arc, Mutex,
    atomic::{AtomicUsize, Ordering},
};

use serde_json::{Value, json};

fn ctx() -> HookContext {
    HookContext::new(false, crate::handlers::Handlers::default())
}

struct InvalidResponder {
    action: InvalidToolCallAction,
    calls: Arc<AtomicUsize>,
}
impl AgentHook for InvalidResponder {
    async fn on_invalid_tool_call(
        &self,
        _ctx: &HookContext,
        _event: &InvalidToolCallContext,
    ) -> Option<InvalidToolCallAction> {
        self.calls.fetch_add(1, Ordering::Relaxed);
        Some(self.action.clone())
    }
}

fn tool_call_kind() -> EffectKind {
    EffectKind::ToolCall {
        name: "add".into(),
        args: "{}".into(),
    }
}

fn invalid_tool_call_context() -> InvalidToolCallContext {
    let call = rig_core::message::ToolCall::from_wire(
        "tc1",
        rig_core::message::ToolFunction::new(
            rig_core::message::ToolName::new("unknown").expect("tool name"),
            serde_json::json!({}),
        ),
    );
    crate::run::TurnPolicy::new(["add".to_string()].into(), None, None)
        .expect("policy")
        .invalid_call_context(
            &call,
            Some("{}".into()),
            vec![],
            false,
            crate::run::policy::InvalidToolCallReason::UnknownTool,
        )
}

#[tokio::test]
async fn no_invalid_tool_decision_defers_to_later_hooks() {
    let retry_calls = Arc::new(AtomicUsize::new(0));
    let mut stack = HookStack::new();
    stack.push(());
    stack.push(InvalidResponder {
        action: InvalidToolCallAction::retry("try another tool"),
        calls: retry_calls.clone(),
    });

    let action = stack
        .on_invalid_tool_call(&ctx(), &invalid_tool_call_context())
        .await;

    assert_eq!(
        action,
        Some(InvalidToolCallAction::retry("try another tool"))
    );
    assert_eq!(retry_calls.load(Ordering::Relaxed), 1);
}

#[test]
fn unit_hook_observes_no_event_kind() {
    for kind in [
        StepEventKind::RunStart,
        StepEventKind::RunSettled,
        StepEventKind::TextDelta,
        StepEventKind::ReasoningDelta,
        StepEventKind::ToolCallDelta,
        StepEventKind::CompletionDispatch,
        StepEventKind::ToolDispatch,
        StepEventKind::EmbedDispatch,
        StepEventKind::RerankDispatch,
        StepEventKind::RetrieveDispatch,
        StepEventKind::CustomDispatch,
    ] {
        assert!(!<() as AgentHook>::observes(&(), kind));
    }
}

#[test]
fn merge_shallow_merges_additional_params_later_wins() {
    let merged = RequestPatch::new()
        .additional_params(json!({"x":1,"y":2}))
        .merge(RequestPatch::new().additional_params(json!({"y":3,"z":4})));
    assert_eq!(merged.additional_params, Some(json!({"x":1,"y":3,"z":4})));
}

#[test]
fn merge_scalar_last_writer_wins() {
    assert_eq!(
        RequestPatch::new()
            .temperature(0.1)
            .merge(RequestPatch::new().temperature(0.9))
            .temperature,
        Some(0.9)
    );
}

#[test]
fn merge_active_tools_intersects() {
    let merged = RequestPatch::new()
        .active_tools(["add", "sub"])
        .merge(RequestPatch::new().active_tools(["sub", "mul"]));
    assert_eq!(merged.active_tools, Some(vec!["sub".into()]));
}

#[test]
fn scratchpad_insert_get_update_remove() {
    #[derive(Clone, Default, Debug, PartialEq)]
    struct Count(u32);
    let pad = Scratchpad::default();
    pad.update(|c: &mut Count| c.0 += 1);
    pad.update(|c: &mut Count| c.0 += 1);
    assert_eq!(pad.get::<Count>(), Some(Count(2)));
    assert_eq!(pad.remove::<Count>(), Some(Count(2)));
}

#[test]
fn scratchpad_is_shared_across_clones() {
    let pad = Scratchpad::default();
    let clone = pad.clone();
    pad.insert(7u32);
    assert_eq!(clone.get::<u32>(), Some(7));
}

#[test]
fn hook_context_reports_identity_and_turn() {
    let context = HookContext::new(true, crate::handlers::Handlers::default());
    assert!(context.is_streaming());
    context.set_turn(3);
    assert_eq!(context.turn(), 3);
    let next = HookContext::new(false, crate::handlers::Handlers::default());
    assert!(next.run_id() > context.run_id(), "each run gets a new id");
}

struct RewriteHook(Value);
impl AgentHook for RewriteHook {
    async fn on_dispatch(&self, _: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        if event.tool_name().is_none() {
            return DispatchAction::proceed();
        }
        DispatchAction::rewrite_tool_args(event.kind, self.0.clone())
    }
}
struct SkipHook;
impl AgentHook for SkipHook {
    async fn on_dispatch(&self, _: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        if event.tool_name().is_none() {
            return DispatchAction::proceed();
        }
        DispatchAction::skip("denied")
    }
}
#[derive(Clone, Default)]
struct ArgsSpy(Arc<Mutex<Vec<String>>>);
impl AgentHook for ArgsSpy {
    async fn on_dispatch(&self, _: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        let Some(args) = event.tool_args() else {
            return DispatchAction::proceed();
        };
        self.0.lock().unwrap().push(args.into());
        DispatchAction::proceed()
    }
}

struct OnDispatchOnly(Arc<AtomicUsize>);
impl AgentHook for OnDispatchOnly {
    async fn on_dispatch(&self, _: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        if event.tool_name().is_none() {
            return DispatchAction::proceed();
        }
        self.0.fetch_add(1, Ordering::Relaxed);
        DispatchAction::skip("called")
    }
}

async fn resolve(stack: &HookStack) -> DispatchAction {
    let kind = tool_call_kind();
    stack.on_dispatch(&ctx(), dispatch_event(&kind)).await
}

#[tokio::test]
async fn outer_rewrite_threads_into_nested_stack() {
    let spy = ArgsSpy::default();
    let mut inner = HookStack::new();
    inner.push(spy.clone());
    inner.push(SkipHook);
    let mut outer = HookStack::new();
    outer.push(RewriteHook(json!({"x":1})));
    outer.push(inner);
    let action = resolve(&outer).await;
    assert_skipped(&action, "denied");
    assert_eq!(
        spy.0.lock().unwrap().as_slice(),
        [serde_json::to_string(&json!({"x":1})).unwrap()]
    );
}

/// The patch a stack had accumulated when it denied: what the engine reads
/// for the skipped result's arguments (`HookContext::take_salvaged_patch`).
fn salvaged_args(context: &HookContext, id: EffectId) -> Option<Value> {
    context.take_salvaged_patch(id).and_then(|kind| match kind {
        EffectKind::ToolCall { args, .. } => serde_json::from_str(&args).ok(),
        _ => None,
    })
}

struct ChangeToolFamilyHook;
impl AgentHook for ChangeToolFamilyHook {
    async fn on_dispatch(&self, _: &HookContext, _: DispatchEvent<'_>) -> DispatchAction {
        DispatchAction::Patch(EffectKind::Custom {
            kind: "invalid-tool-replacement".into(),
            payload: json!({}),
        })
    }
}

#[tokio::test]
async fn nested_wrong_family_patch_preserves_valid_tool_and_stops_later_hooks() {
    let calls = Arc::new(AtomicUsize::new(0));
    let mut inner = HookStack::new();
    inner.push(RewriteHook(json!({"x": 3})));
    inner.push(ChangeToolFamilyHook);
    inner.push(OnDispatchOnly(calls.clone()));
    let mut outer = HookStack::new();
    outer.push(RewriteHook(json!({"x": 1})));
    outer.push(inner);
    outer.push(OnDispatchOnly(calls.clone()));
    let context = ctx();
    let kind = tool_call_kind();
    let event = dispatch_event(&kind);
    let action = outer.on_dispatch(&context, event).await;
    assert!(
        matches!(action, DispatchAction::Deny(ref report) if report.kind == ErrorKind::Internal)
    );
    assert_eq!(calls.load(Ordering::Relaxed), 0);
    assert_eq!(salvaged_args(&context, event.id), Some(json!({"x": 3})));
}

/// Counts its run-start, run-settled and delta calls, and observes none of them.
struct NotObserving(Arc<AtomicUsize>);

impl AgentHook for NotObserving {
    async fn on_run_start(&self, _ctx: &HookContext, _event: RunStart<'_>) -> RunStartAction {
        self.0.fetch_add(1, Ordering::Relaxed);
        RunStartAction::Continue
    }
    async fn on_run_settled(&self, _ctx: &HookContext, _event: RunSettled<'_>) {
        self.0.fetch_add(1, Ordering::Relaxed);
    }
    async fn on_text_delta(&self, _ctx: &HookContext, _event: TextDelta<'_>) -> ObservationAction {
        self.0.fetch_add(1, Ordering::Relaxed);
        ObservationAction::Continue
    }
    async fn on_reasoning_delta(
        &self,
        _ctx: &HookContext,
        _event: ReasoningDelta<'_>,
    ) -> ObservationAction {
        self.0.fetch_add(1, Ordering::Relaxed);
        ObservationAction::Continue
    }
    async fn on_tool_call_delta(
        &self,
        _ctx: &HookContext,
        _event: ToolCallDelta<'_>,
    ) -> ObservationAction {
        self.0.fetch_add(1, Ordering::Relaxed);
        ObservationAction::Continue
    }
    fn observes(&self, kind: StepEventKind) -> bool {
        !matches!(
            kind,
            StepEventKind::RunStart
                | StepEventKind::RunSettled
                | StepEventKind::TextDelta
                | StepEventKind::ReasoningDelta
                | StepEventKind::ToolCallDelta
        )
    }
}

/// A stack skips a member that does not observe an event, even when a sibling
/// with the default interest makes the stack observe it.
#[tokio::test]
async fn a_stack_skips_a_hook_that_does_not_observe_the_event() {
    struct Listener;
    impl AgentHook for Listener {}

    let calls = Arc::new(AtomicUsize::new(0));
    let mut stack = HookStack::new();
    stack.push(NotObserving(calls.clone()));
    stack.push(Listener);
    let prompt = Message::user("hi");

    let _ = stack
        .on_run_start(
            &ctx(),
            RunStart {
                prompt: &prompt,
                history: &[],
            },
        )
        .await;
    stack
        .on_run_settled(
            &ctx(),
            RunSettled {
                outcome: SettledOutcome::Error("x"),
                messages: None,
            },
        )
        .await;
    let _ = stack
        .on_text_delta(
            &ctx(),
            TextDelta {
                delta: "a",
                aggregated: "a",
            },
        )
        .await;
    let _ = stack
        .on_reasoning_delta(
            &ctx(),
            ReasoningDelta {
                part: Part::new(0),
                delta: "a",
                aggregated: "a",
            },
        )
        .await;
    let _ = stack
        .on_tool_call_delta(
            &ctx(),
            ToolCallDelta {
                part: Part::new(1),
                tool_name: "t",
                delta: "{",
                aggregated: "{",
            },
        )
        .await;

    assert_eq!(calls.load(Ordering::Relaxed), 0);
}