rig-agent 0.43.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
use std::{
    future::{Future, pending, poll_fn},
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    task::Poll,
    time::Duration,
};

use super::*;
use rig_core::message::{ImageMediaType, ToolResultContent};
use rig_core::tool::{ContextValue, ToolErrorKind, ToolOutput};

#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
struct Counter(u32);
impl ContextValue for Counter {
    const KEY: &'static str = "test.counter";
}

#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
struct Note(String);
impl ContextValue for Note {
    const KEY: &'static str = "test.note";
}

fn rich_error_output(label: &str) -> ToolOutput {
    ToolOutput::content(vec![
        ToolResultContent::text(label),
        ToolResultContent::image_base64("base64data==", Some(ImageMediaType::PNG), None),
    ])
    .expect("fixture content is non-empty")
}

fn assert_rich_error_output(result: &ToolResult, label: &str) {
    let content = result.output().as_content();
    assert_eq!(content.len(), 2);
    assert!(matches!(
        content.first(),
        Some(ToolResultContent::Text(text)) if text.text == label
    ));
    assert!(matches!(content.last(), Some(ToolResultContent::Image(_))));
}

struct Echo;

impl Tool for Echo {
    const NAME: &'static str = "echo";
    type Error = rig::tool::ToolExecutionError;
    type Args = serde_json::Value;
    type Output = serde_json::Value;

    fn description(&self) -> String {
        "echo arguments".into()
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn call(
        &self,
        context: &mut ToolContext,
        args: Self::Args,
    ) -> Result<Self::Output, ToolExecutionError> {
        if let Some(Counter(value)) = context.get::<Counter>()? {
            context.insert(Counter(value + 1))?;
        }
        context.insert_result(Note("result-metadata".to_string()))?;
        Ok(args)
    }
}

#[tokio::test]
async fn toolset_dispatch_snapshot_is_canonical_and_returns_result_metadata() {
    let mut set = ToolSet::default();
    set.add_tool(Echo);
    let definitions = set.tool_definitions();
    assert_eq!(definitions[0].name, "echo");

    let mut context = ToolContext::new();
    context.insert(Counter(7)).unwrap();
    let result = set.execute("echo", r#"{"value":1}"#, &mut context).await;
    assert!(result.is_success());
    assert_eq!(
        result.output(),
        &ToolOutput::json(serde_json::json!({"value": 1}))
    );
    assert_eq!(
        context.get::<Counter>().unwrap(),
        Some(Counter(7)),
        "tool-local inbound mutations must not change the caller's context"
    );
    assert_eq!(
        context.result::<Note>().unwrap(),
        Some(Note("result-metadata".to_string()))
    );
}

struct PendingTool(Arc<AtomicBool>);

impl Tool for PendingTool {
    const NAME: &'static str = "pending";
    type Error = rig::tool::ToolExecutionError;
    type Args = ();
    type Output = ();

    fn description(&self) -> String {
        "never completes".into()
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn call(
        &self,
        context: &mut ToolContext,
        _args: Self::Args,
    ) -> Result<Self::Output, ToolExecutionError> {
        context.insert_result(Note("unpublished".to_string()))?;
        self.0.store(true, Ordering::SeqCst);
        pending().await
    }
}

#[tokio::test]
async fn cancelled_toolset_dispatch_does_not_retain_stale_result_metadata() {
    let mut set = ToolSet::default();
    let started = Arc::new(AtomicBool::new(false));
    set.add_tool(PendingTool(started.clone()));
    let mut context = ToolContext::new();
    context.insert_result(Note("stale".to_string())).unwrap();

    let mut execution = Box::pin(set.execute(PendingTool::NAME, "null", &mut context));
    tokio::time::timeout(
        Duration::from_secs(1),
        poll_fn(|cx| {
            assert!(execution.as_mut().poll(cx).is_pending());
            started.load(Ordering::SeqCst).then_some(()).map_or_else(
                || {
                    cx.waker().wake_by_ref();
                    Poll::Pending
                },
                Poll::Ready,
            )
        }),
    )
    .await
    .expect("pending tool did not start");
    drop(execution);

    assert_eq!(context.result::<Note>().unwrap(), None);
}

/// A tool-family handler that is not a tool adapter: it answers without
/// publishing a context (a replayer for a record without output, a host's
/// own handler).
struct Silent;

impl rig_core::serve::Serve for Silent {
    type Family = family::Tool;

    fn descriptor(&self) -> rig_core::effect::HandlerDescriptor {
        rig_core::effect::HandlerDescriptor {
            key: tool_key("silent"),
            family: FamilyDescriptor::Tool {
                name: "silent".into(),
                description: "answers without publishing".into(),
                parameters: serde_json::json!({"type": "object"}),
                embedding: None,
            },
            layers: Vec::new(),
        }
    }

    async fn serve(
        &self,
        _kind: EffectKind,
        _dispatch: rig_core::serve::Dispatch,
    ) -> rig_core::serve::Reply {
        rig_core::serve::Reply::Outcome(Ok(Outcome::ToolResult {
            result: ToolResult::success(ToolOutput::text("silent")),
        }))
    }
}

/// A tool-family handler whose answer is a report, not a result.
struct Refusing;

impl rig_core::serve::Serve for Refusing {
    type Family = family::Tool;

    fn descriptor(&self) -> rig_core::effect::HandlerDescriptor {
        rig_core::effect::HandlerDescriptor {
            key: tool_key("refusing"),
            family: FamilyDescriptor::Tool {
                name: "refusing".into(),
                description: "refuses every call".into(),
                parameters: serde_json::json!({"type": "object"}),
                embedding: None,
            },
            layers: Vec::new(),
        }
    }

    async fn serve(
        &self,
        _kind: EffectKind,
        _dispatch: rig_core::serve::Dispatch,
    ) -> rig_core::serve::Reply {
        rig_core::serve::Reply::Outcome(Err(ErrorReport::new(ErrorKind::Other, "refused")))
    }
}

/// The inline registration path keeps the caller's inbound values on every
/// ending: a tool that mutates its inbound slot and publishes, a handler
/// that publishes nothing, a handler that refuses. Only result metadata
/// changes, and only to what the call published.
#[tokio::test]
async fn registered_tool_execute_keeps_inbound_values_on_every_ending() {
    let mut context = ToolContext::new();
    context.insert(Counter(7)).unwrap();
    context.insert_result(Note("stale".to_string())).unwrap();

    let echo = RegisteredTool::from_tool(Echo);
    let result = echo.execute(r#"{"value":1}"#.into(), &mut context).await;
    assert!(result.is_success());
    assert_eq!(
        context.get::<Counter>().unwrap(),
        Some(Counter(7)),
        "the tool's inbound mutation stays in the call"
    );
    assert_eq!(
        context.result::<Note>().unwrap(),
        Some(Note("result-metadata".to_string()))
    );

    let silent = RegisteredTool::from_handler(Silent).expect("a tool-family handler");
    let result = silent.execute("{}".into(), &mut context).await;
    assert!(result.is_success());
    assert_eq!(context.get::<Counter>().unwrap(), Some(Counter(7)));
    assert_eq!(
        context.result::<Note>().unwrap(),
        None,
        "a handler that published nothing leaves no result metadata"
    );

    context.insert_result(Note("stale".to_string())).unwrap();
    let refusing = RegisteredTool::from_handler(Refusing).expect("a tool-family handler");
    let result = refusing.execute("{}".into(), &mut context).await;
    assert_eq!(
        result.error().map(ToolExecutionError::kind),
        Some(ToolErrorKind::Other)
    );
    assert_eq!(context.get::<Counter>().unwrap(), Some(Counter(7)));
    assert_eq!(context.result::<Note>().unwrap(), None);
}

/// Dropping an inline execution mid-call leaves the caller's context exactly
/// as it was: nothing is moved out of it, nothing partial is published.
#[tokio::test]
async fn registered_tool_execute_dropped_mid_call_leaves_the_context_unchanged() {
    let started = Arc::new(AtomicBool::new(false));
    let tool = RegisteredTool::from_tool(PendingTool(started.clone()));
    let mut context = ToolContext::new();
    context.insert(Counter(7)).unwrap();
    context.insert_result(Note("stale".to_string())).unwrap();
    let before = context.clone();

    let mut execution = Box::pin(tool.execute("null".into(), &mut context));
    tokio::time::timeout(
        Duration::from_secs(1),
        poll_fn(|cx| {
            assert!(execution.as_mut().poll(cx).is_pending());
            started.load(Ordering::SeqCst).then_some(()).map_or_else(
                || {
                    cx.waker().wake_by_ref();
                    Poll::Pending
                },
                Poll::Ready,
            )
        }),
    )
    .await
    .expect("pending tool did not start");
    drop(execution);

    assert_eq!(context, before);
}

#[tokio::test]
async fn framework_argument_errors_remain_actionable_to_the_model() {
    let mut set = ToolSet::default();
    set.add_tool(Echo);

    let result = set
        .execute("echo", "{not json", &mut ToolContext::new())
        .await;

    assert!(result.is_error_kind(ToolErrorKind::InvalidArgs));
    assert!(
        result
            .output()
            .as_text()
            .is_some_and(|message| message.starts_with("failed to parse tool arguments:"))
    );
    assert_eq!(
        result.output().as_text(),
        result.error().and_then(ToolExecutionError::model_feedback)
    );
}

struct ForeignErrorTool;

impl Tool for ForeignErrorTool {
    const NAME: &'static str = "foreign_error";
    type Error = std::io::Error;
    type Args = ();
    type Output = ();

    fn description(&self) -> String {
        "returns a foreign error type".into()
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn call(
        &self,
        _context: &mut ToolContext,
        _args: Self::Args,
    ) -> Result<Self::Output, Self::Error> {
        Err(std::io::Error::other("operator-only detail"))
    }
}

#[tokio::test]
async fn typed_foreign_errors_normalize_only_at_dispatch() {
    let direct: std::io::Error = ForeignErrorTool
        .call(&mut ToolContext::new(), ())
        .await
        .expect_err("direct call should retain its typed error");
    assert_eq!(direct.to_string(), "operator-only detail");

    let mut set = ToolSet::default();
    set.add_tool(ForeignErrorTool);
    let result = set
        .execute(ForeignErrorTool::NAME, "null", &mut ToolContext::new())
        .await;
    let error = result.error().expect("dispatch should normalize the error");
    assert_eq!(error.kind(), ToolErrorKind::Other);
    assert_eq!(error.message(), "operator-only detail");
    assert_eq!(error.model_feedback(), Some("the tool failed"));
    assert!(error.is::<std::io::Error>());
}

#[derive(Debug, thiserror::Error)]
#[error("domain timeout")]
struct DomainTimeout;

struct ClassifiedErrorTool;

impl Tool for ClassifiedErrorTool {
    const NAME: &'static str = "classified_error";
    type Error = DomainTimeout;
    type Args = ();
    type Output = ();

    fn description(&self) -> String {
        "classifies a domain error".into()
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    fn map_error(&self, error: Self::Error) -> ToolExecutionError {
        ToolExecutionError::timeout("safe timeout feedback").with_source(error)
    }

    async fn call(
        &self,
        _context: &mut ToolContext,
        _args: Self::Args,
    ) -> Result<Self::Output, Self::Error> {
        Err(DomainTimeout)
    }
}

#[tokio::test]
async fn tools_can_classify_typed_errors_at_the_erased_boundary() {
    let mut set = ToolSet::default();
    set.add_tool(ClassifiedErrorTool);
    let result = set
        .execute(ClassifiedErrorTool::NAME, "null", &mut ToolContext::new())
        .await;
    let error = result.error().expect("dispatch should normalize the error");
    assert_eq!(error.kind(), ToolErrorKind::Timeout);
    assert_eq!(error.retryable(), Some(true));
    assert_eq!(error.model_feedback(), Some("safe timeout feedback"));
    assert!(error.is::<DomainTimeout>());
}

#[tokio::test]
async fn dynamic_tool_preserves_concrete_error() {
    #[derive(Debug, thiserror::Error)]
    #[error("boom")]
    struct Boom;

    let tool = DynamicTool::new(
        "dynamic",
        "fails",
        serde_json::json!({"type":"object"}),
        |_args| Box::pin(async { Err(ToolExecutionError::provider("upstream").with_source(Boom)) }),
    );
    let set = ToolSet::from_dynamic_tools(vec![tool]);
    let result = set.execute("dynamic", "{}", &mut ToolContext::new()).await;
    assert!(result.error().is_some_and(|error| error.is::<Boom>()));
}

struct DirectRichOutput;

impl Tool for DirectRichOutput {
    const NAME: &'static str = "direct_rich_output";
    type Error = rig::tool::ToolExecutionError;
    type Args = serde_json::Value;
    type Output = ToolResultContent;

    fn description(&self) -> String {
        "returns a direct rich-content value".into()
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn call(
        &self,
        _context: &mut ToolContext,
        _args: Self::Args,
    ) -> Result<Self::Output, ToolExecutionError> {
        Ok(ToolResultContent::image_base64(
            "base64data==",
            Some(ImageMediaType::PNG),
            None,
        ))
    }
}

#[tokio::test]
async fn direct_rich_typed_output_is_not_serialized_as_json() {
    let mut set = ToolSet::default();
    set.add_tool(DirectRichOutput);

    let result = set
        .execute(DirectRichOutput::NAME, "{}", &mut ToolContext::new())
        .await;

    assert!(result.is_success());
    assert!(matches!(
        result.output().as_content().first(),
        Some(ToolResultContent::Image(_))
    ));
    assert_eq!(result.output().as_json(), None);
}

struct TypedRichError {
    refuse: bool,
}

impl Tool for TypedRichError {
    const NAME: &'static str = "typed_rich_error";
    type Error = rig::tool::ToolExecutionError;
    type Args = serde_json::Value;
    type Output = String;

    fn description(&self) -> String {
        "returns rich failure feedback".into()
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn call(
        &self,
        _context: &mut ToolContext,
        _args: Self::Args,
    ) -> Result<Self::Output, ToolExecutionError> {
        let error = if self.refuse {
            ToolExecutionError::refused("typed refusal")
        } else {
            ToolExecutionError::provider("typed failure")
        };
        Err(error.with_model_output(rich_error_output("typed feedback")))
    }
}

#[tokio::test]
async fn typed_failures_and_refusals_preserve_rich_model_output() {
    for refuse in [false, true] {
        let mut set = ToolSet::default();
        set.add_tool(TypedRichError { refuse });

        let result = set
            .execute(TypedRichError::NAME, "{}", &mut ToolContext::new())
            .await;

        assert_eq!(result.is_refused(), refuse);
        assert_eq!(result.is_error(), !refuse);
        assert_rich_error_output(&result, "typed feedback");
    }
}

#[tokio::test]
async fn dynamic_failures_and_refusals_preserve_rich_model_output() {
    for refuse in [false, true] {
        let tool = DynamicTool::new(
            "dynamic_rich_error",
            "returns rich failure feedback",
            serde_json::json!({"type": "object"}),
            move |_args| {
                Box::pin(async move {
                    let error = if refuse {
                        ToolExecutionError::refused("dynamic refusal")
                    } else {
                        ToolExecutionError::provider("dynamic failure")
                    };
                    Err(error.with_model_output(rich_error_output("dynamic feedback")))
                })
            },
        );
        let set = ToolSet::from_dynamic_tools(vec![tool]);

        let result = set
            .execute("dynamic_rich_error", "{}", &mut ToolContext::new())
            .await;

        assert_eq!(result.is_refused(), refuse);
        assert_eq!(result.is_error(), !refuse);
        assert_rich_error_output(&result, "dynamic feedback");
    }
}