agent-base 0.13.0

A lightweight Agent Runtime Kernel for building AI agents in Rust
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
use super::*;

#[tokio::test]
async fn truncation_guard_blocks_tool_calls_on_length_finish_reason() {
    // First call: tool call with finish_reason="length" — should be blocked by guard.
    // Second call: model retries with corrected approach (text response).
    let runtime = AgentBuilder::new(Arc::new(ScriptedProvider::new(vec![
        // Turn 1: truncated tool call
        vec![
            StreamChunk::ToolCall(serde_json::json!({
                "delta": {
                    "tool_calls": [{
                        "id": "call_trunc",
                        "function": {
                            "name": "shell",
                            "arguments": "{\"cmd\": \"rm -rf /inco"
                        }
                    }]
                }
            })),
            StreamChunk::Stop {
                finish_reason: Some("length".to_string()),
            },
        ],
        // Turn 2: model sees the error and retries
        vec![
            StreamChunk::Text(
                "I see the previous call was truncated. Let me re-issue it.".to_string(),
            ),
            StreamChunk::Stop {
                finish_reason: Some("stop".to_string()),
            },
        ],
    ])))
    .system_prompt("You are a careful assistant.")
    .build()
    .expect("build runtime");

    let sid = runtime.create_session().await;

    let events = Arc::new(Mutex::new(Vec::new()));
    let events_clone = events.clone();
    let result = runtime
        .run_turn(sid.clone(), "run a command", move |event| {
            events_clone.lock().unwrap().push(event);
            Ok(())
        })
        .await;

    assert!(
        result.is_ok(),
        "run_turn should complete: {:?}",
        result.err()
    );

    // Verify the session messages contain the truncation error, not the
    // partial argument that would have been executed.
    let session = runtime.session(&sid).await.expect("session exists");
    let messages = session.chat_messages().to_vec();

    let has_truncation_error = messages.iter().any(|m| {
        if let ChatMessage::Tool { content, .. } = m {
            content.contains("Tool call was not executed") && content.contains("output token limit")
        } else {
            false
        }
    });
    assert!(
        has_truncation_error,
        "session should contain truncation error tool result. Messages: {:#?}",
        messages
            .iter()
            .map(|m| format!("{:?}", m))
            .collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn truncation_guard_blocks_tool_calls_on_finish_tool_calls_mimo() {
    // mimo-v2.5-pro truncates the tool-call argument stream mid-generation
    // under load but reports `finish_reason=tool_calls` (NOT `length`), so the
    // length-only guard lets these fall through to tool execution as
    // ToolArgsInvalid — which feeds ConsecutiveFailureRecovery and aborts the
    // run ("failed 3 consecutive times"). The widened guard must detect the
    // structurally-incomplete JSON args regardless of the claimed finish reason
    // and route through the clean re-issue path instead.
    let runtime = AgentBuilder::new(Arc::new(ScriptedProvider::new(vec![
        // Turn 1: named tool call with a dangling, non-JSON argument string,
        // provider claims a normal tool_calls finish.
        vec![
            StreamChunk::ToolCall(serde_json::json!({
                "delta": {
                    "tool_calls": [{
                        "id": "call_trunc_1",
                        "function": {
                            "name": "spawn_agent",
                            "arguments": "{\"agent_path\": "
                        }
                    }]
                }
            })),
            StreamChunk::Stop {
                finish_reason: Some("tool_calls".to_string()),
            },
        ],
        // Turn 2: model sees the re-issue instruction and replies in text.
        vec![
            StreamChunk::Text("Re-issuing the call with complete arguments.".to_string()),
            StreamChunk::Stop {
                finish_reason: Some("stop".to_string()),
            },
        ],
    ])))
    .system_prompt("You are a careful assistant.")
    .build()
    .expect("build runtime");

    let sid = runtime.create_session().await;

    let events = Arc::new(Mutex::new(Vec::new()));
    let events_clone = events.clone();
    let result = runtime
        .run_turn(sid.clone(), "spawn a sub-agent", move |event| {
            events_clone.lock().unwrap().push(event);
            Ok(())
        })
        .await;

    assert!(
        result.is_ok(),
        "run_turn should complete: {:?}",
        result.err()
    );

    let session = runtime.session(&sid).await.expect("session exists");
    let messages = session.chat_messages().to_vec();

    // The truncated call must NOT have been executed / recorded as a parse
    // failure; it must have been routed to the re-issue guard.
    let has_reissue = messages.iter().any(|m| {
        if let ChatMessage::Tool { content, .. } = m {
            content.contains("Tool call was not executed")
                && content.contains("provider truncated the argument stream")
        } else {
            false
        }
    });
    assert!(
        has_reissue,
        "session should contain a re-issue tool result for the truncated call. Messages: {:#?}",
        messages
            .iter()
            .map(|m| format!("{:?}", m))
            .collect::<Vec<_>>()
    );

    // And crucially the raw malformed args must never appear as an executed
    // ToolArgsInvalid failure (the death-spiral trigger).
    let has_args_invalid = messages.iter().any(|m| {
        let s = format!("{:?}", m);
        s.contains("argument parsing failed") || s.contains("EOF while parsing")
    });
    assert!(
        !has_args_invalid,
        "truncated args must not surface as a ToolArgsInvalid failure. Messages: {:#?}",
        messages
            .iter()
            .map(|m| format!("{:?}", m))
            .collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn truncation_guard_salvages_call_from_leaked_text_markup() {
    // mimo-v2.6-flash (session 20260923_263149bf) emits the SAME tool call on
    // two channels: the native tool_call argument stream dies mid-JSON with a
    // bogus "stop" finish, while the content channel leaks the chat-template
    // markup carrying the full parameter values. The guard must harvest the
    // leaked copy (name match + schema-valid) and EXECUTE it, not burn a
    // re-issue strike — the re-issue truncated again on the real session.
    let leaked = "我来派一个子代理。<tool_call><function=spawn_agent>\
<parameter=task_name>research<parameter=message>只读调研 codex,不改文件。";
    let runtime = AgentBuilder::new(Arc::new(ScriptedProvider::new(vec![
        vec![
            StreamChunk::Text(leaked.to_string()),
            StreamChunk::ToolCall(serde_json::json!({
                "delta": {
                    "tool_calls": [{
                        "id": "call_leak_1",
                        "function": {
                            "name": "spawn_agent",
                            "arguments": "{\"task_name\":\"res"
                        }
                    }]
                }
            })),
            StreamChunk::Stop {
                finish_reason: Some("stop".to_string()),
            },
        ],
        vec![
            StreamChunk::Text("Should never be reached.".to_string()),
            StreamChunk::Stop {
                finish_reason: Some("stop".to_string()),
            },
        ],
    ])))
    .system_prompt("You are a careful assistant.")
    .register_tool(SpawnLikeTool)
    .build()
    .expect("build runtime");

    let sid = runtime.create_session().await;
    let events = Arc::new(Mutex::new(Vec::new()));
    let events_clone = events.clone();
    let result = runtime
        .run_turn(sid.clone(), "spawn a sub-agent", move |event| {
            events_clone.lock().unwrap().push(event);
            Ok(())
        })
        .await;
    assert!(
        result.is_ok(),
        "run_turn should complete: {:?}",
        result.err()
    );

    let session = runtime.session(&sid).await.expect("session exists");
    let messages = session.chat_messages().to_vec();

    // The salvaged call must have executed exactly once.
    let spawned_count = messages
        .iter()
        .filter(|m| {
            if let ChatMessage::Tool { content, .. } = m {
                content.contains("spawned")
            } else {
                false
            }
        })
        .count();
    assert_eq!(
        spawned_count,
        1,
        "leaked call must be salvaged and executed. Messages: {:#?}",
        messages
            .iter()
            .map(|m| format!("{:?}", m))
            .collect::<Vec<_>>()
    );

    // No re-issue guidance, and no ToolArgsInvalid death-spiral residue.
    let bad = messages.iter().any(|m| {
        if let ChatMessage::Tool { content, .. } = m {
            content.contains("Tool call was not executed")
                || content.contains("argument parsing failed")
                || content.contains("EOF while parsing")
        } else {
            false
        }
    });
    assert!(
        !bad,
        "salvaged call must not surface re-issue guidance or parse failure. Messages: {:#?}",
        messages
            .iter()
            .map(|m| format!("{:?}", m))
            .collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn salvage_rejects_leak_missing_required_field() {
    // A leak that omits a schema-required field must NOT be salvaged: executing
    // it would fail typed parsing (ToolArgsInvalid — the death-spiral trigger).
    // The call stays on the re-issue path instead.
    let leaked = "<tool_call><function=spawn_agent><parameter=task_name>research</tool_call>";
    let runtime = AgentBuilder::new(Arc::new(ScriptedProvider::new(vec![
        vec![
            StreamChunk::Text(leaked.to_string()),
            StreamChunk::ToolCall(serde_json::json!({
                "delta": {
                    "tool_calls": [{
                        "id": "call_leak_2",
                        "function": {
                            "name": "spawn_agent",
                            "arguments": "{\"task_name\":\"res"
                        }
                    }]
                }
            })),
            StreamChunk::Stop {
                finish_reason: Some("stop".to_string()),
            },
        ],
        vec![
            StreamChunk::Text("Re-issuing with complete arguments.".to_string()),
            StreamChunk::Stop {
                finish_reason: Some("stop".to_string()),
            },
        ],
    ])))
    .system_prompt("You are a careful assistant.")
    .register_tool(SpawnLikeTool)
    .build()
    .expect("build runtime");

    let sid = runtime.create_session().await;
    let events = Arc::new(Mutex::new(Vec::new()));
    let events_clone = events.clone();
    let result = runtime
        .run_turn(sid.clone(), "spawn a sub-agent", move |event| {
            events_clone.lock().unwrap().push(event);
            Ok(())
        })
        .await;
    assert!(
        result.is_ok(),
        "run_turn should complete: {:?}",
        result.err()
    );

    let session = runtime.session(&sid).await.expect("session exists");
    let messages = session.chat_messages().to_vec();

    let executed = messages.iter().any(|m| {
        if let ChatMessage::Tool { content, .. } = m {
            content.contains("spawned")
        } else {
            false
        }
    });
    assert!(
        !executed,
        "incomplete leak must not execute. Messages: {:#?}",
        messages
            .iter()
            .map(|m| format!("{:?}", m))
            .collect::<Vec<_>>()
    );
    let has_reissue = messages.iter().any(|m| {
        if let ChatMessage::Tool { content, .. } = m {
            content.contains("Tool call was not executed")
        } else {
            false
        }
    });
    assert!(
        has_reissue,
        "incomplete leak must fall back to re-issue guidance. Messages: {:#?}",
        messages
            .iter()
            .map(|m| format!("{:?}", m))
            .collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn truncation_guard_recognizes_wrapper_echo() {
    // mimo, having seen a `{error:"tool_call_arguments_truncated",...}` object
    // in its history, replays it VERBATIM as the next call's arguments. That
    // payload is valid JSON, so the raw-args structural guard can't catch it —
    // but it is unmistakably truncation residue. The guard must recognise the
    // wrapper marker and re-issue instead of executing it (which would surface
    // as a downstream ToolArgsInvalid, the send_message slip seen in the field).
    let wrapper = serde_json::json!({
        "error": "tool_call_arguments_truncated",
        "message": "The tool call arguments were truncated or invalid. Please retry with complete arguments.",
        "original_args_preview": "{\"agent_path\": "
    })
    .to_string();

    let runtime = AgentBuilder::new(Arc::new(ScriptedProvider::new(vec![
        vec![
            StreamChunk::ToolCall(serde_json::json!({
                "delta": {
                    "tool_calls": [{
                        "id": "call_echo",
                        "function": {
                            "name": "send_message",
                            "arguments": wrapper
                        }
                    }]
                }
            })),
            StreamChunk::Stop {
                finish_reason: Some("tool_calls".to_string()),
            },
        ],
        vec![
            StreamChunk::Text("Now sending a real message.".to_string()),
            StreamChunk::Stop {
                finish_reason: Some("stop".to_string()),
            },
        ],
    ])))
    .system_prompt("You are a careful assistant.")
    .build()
    .expect("build runtime");

    let sid = runtime.create_session().await;
    let events = Arc::new(Mutex::new(Vec::new()));
    let events_clone = events.clone();
    let result = runtime
        .run_turn(sid.clone(), "continue", move |event| {
            events_clone.lock().unwrap().push(event);
            Ok(())
        })
        .await;
    assert!(
        result.is_ok(),
        "run_turn should complete: {:?}",
        result.err()
    );

    let session = runtime.session(&sid).await.expect("session exists");
    let messages = session.chat_messages().to_vec();

    let has_reissue = messages.iter().any(|m| {
        if let ChatMessage::Tool { content, .. } = m {
            content.contains("Tool call was not executed")
        } else {
            false
        }
    });
    assert!(
        has_reissue,
        "echoed wrapper args must be routed to the re-issue guard. Messages: {:#?}",
        messages
            .iter()
            .map(|m| format!("{:?}", m))
            .collect::<Vec<_>>()
    );

    let has_args_invalid = messages.iter().any(|m| {
        let s = format!("{:?}", m);
        s.contains("argument parsing failed")
    });
    assert!(
        !has_args_invalid,
        "echoed wrapper must not reach tool execution. Messages: {:#?}",
        messages
            .iter()
            .map(|m| format!("{:?}", m))
            .collect::<Vec<_>>()
    );
}

/// Minimal tool whose schema has no required fields — mirrors `list_agents`.
struct NoArgTool;

#[async_trait]
impl Tool for NoArgTool {
    fn name(&self) -> &'static str {
        "list_agents"
    }

    fn description(&self) -> &'static str {
        "List running agents"
    }

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

    async fn call(&self, _args: &Value, _ctx: &ToolContext) -> AgentResult<Vec<Content>> {
        Ok(vec![Content::text("no agents")])
    }
}

#[tokio::test]
async fn truncation_guard_blocks_empty_args_for_required_field_tool() {
    // The model, having seen sanitized `spawn_agent {}` entries in its history,
    // echoes the shape: one real spawn + one empty `{}` in the same turn.
    // `{}` is valid JSON (case 2 skips it) but the tool's schema requires
    // task_name + message — case 4 must detect this as degenerate and re-issue
    // the whole turn, avoiding a ToolArgsInvalid execution failure.
    let runtime = AgentBuilder::new(Arc::new(ScriptedProvider::new(vec![
        // Turn 1: two spawn_agent buckets — one complete, one empty `{}`.
        vec![
            StreamChunk::ToolCall(serde_json::json!({
                "delta": {
                    "tool_calls": [
                        {
                            "index": 0,
                            "id": "call_real",
                            "function": {
                                "name": "spawn_agent",
                                "arguments": "{\"task_name\":\"foo\",\"message\":\"do stuff\"}"
                            }
                        },
                        {
                            "index": 1,
                            "id": "call_empty",
                            "function": {
                                "name": "spawn_agent",
                                "arguments": "{}"
                            }
                        }
                    ]
                }
            })),
            StreamChunk::Stop {
                finish_reason: Some("tool_calls".to_string()),
            },
        ],
        // Turn 2: model sees the re-issue instruction and replies.
        vec![
            StreamChunk::Text("Re-issuing with complete arguments.".to_string()),
            StreamChunk::Stop {
                finish_reason: Some("stop".to_string()),
            },
        ],
    ])))
    .system_prompt("You are a careful assistant.")
    .register_tool(SpawnLikeTool)
    .build()
    .expect("build runtime");

    let sid = runtime.create_session().await;
    let events = Arc::new(Mutex::new(Vec::new()));
    let events_clone = events.clone();
    let result = runtime
        .run_turn(sid.clone(), "spawn two agents", move |event| {
            events_clone.lock().unwrap().push(event);
            Ok(())
        })
        .await;

    assert!(
        result.is_ok(),
        "run_turn should complete: {:?}",
        result.err()
    );

    let session = runtime.session(&sid).await.expect("session exists");
    let messages = session.chat_messages().to_vec();

    // Must contain a re-issue tool result for the empty-required case.
    let has_reissue = messages.iter().any(|m| {
        if let ChatMessage::Tool { content, .. } = m {
            content.contains("Tool call was not executed")
                && content.contains("empty argument object")
                && content.contains("requires fields")
        } else {
            false
        }
    });
    assert!(
        has_reissue,
        "empty {{}} for a required-field tool must be caught by case 4 guard. Messages: {:#?}",
        messages
            .iter()
            .map(|m| format!("{:?}", m))
            .collect::<Vec<_>>()
    );

    // Crucially the empty args must NOT have reached tool execution as a
    // ToolArgsInvalid failure.
    let has_args_invalid = messages.iter().any(|m| {
        let s = format!("{:?}", m);
        s.contains("argument parsing failed") || s.contains("EOF while parsing")
    });
    assert!(
        !has_args_invalid,
        "empty {{}} args must not surface as a ToolArgsInvalid failure. Messages: {:#?}",
        messages
            .iter()
            .map(|m| format!("{:?}", m))
            .collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn no_arg_tool_with_empty_object_args_executes_normally() {
    // A tool with no required fields (like `list_agents`) legitimately receives
    // `{}` as arguments. The case 4 guard must NOT fire — the tool should
    // execute normally.
    let runtime = AgentBuilder::new(Arc::new(ScriptedProvider::new(vec![
        // Turn 1: list_agents with `{}` — should execute.
        vec![
            StreamChunk::ToolCall(serde_json::json!({
                "delta": {
                    "tool_calls": [{
                        "index": 0,
                        "id": "call_list",
                        "function": {
                            "name": "list_agents",
                            "arguments": "{}"
                        }
                    }]
                }
            })),
            StreamChunk::Stop {
                finish_reason: Some("tool_calls".to_string()),
            },
        ],
        // Turn 2: model reports the result.
        vec![
            StreamChunk::Text("No agents running.".to_string()),
            StreamChunk::Stop {
                finish_reason: Some("stop".to_string()),
            },
        ],
    ])))
    .system_prompt("test")
    .register_tool(NoArgTool)
    .build()
    .expect("build runtime");

    let sid = runtime.create_session().await;
    let events = Arc::new(Mutex::new(Vec::new()));
    let events_clone = events.clone();
    let result = runtime
        .run_turn(sid.clone(), "list agents", move |event| {
            events_clone.lock().unwrap().push(event);
            Ok(())
        })
        .await;

    assert!(
        result.is_ok(),
        "run_turn should complete: {:?}",
        result.err()
    );

    let session = runtime.session(&sid).await.expect("session exists");
    let messages = session.chat_messages().to_vec();

    // Must NOT contain a re-issue guidance — no required fields, so {} is valid.
    let has_reissue = messages.iter().any(|m| {
        if let ChatMessage::Tool { content, .. } = m {
            content.contains("Tool call was not executed")
                && content.contains("empty argument object")
        } else {
            false
        }
    });
    assert!(
        !has_reissue,
        "no-arg tool with {{}} must execute, not be re-issued. Messages: {:#?}",
        messages
            .iter()
            .map(|m| format!("{:?}", m))
            .collect::<Vec<_>>()
    );

    // And must contain the tool's actual output (execution succeeded).
    let has_output = messages.iter().any(|m| {
        if let ChatMessage::Tool { content, .. } = m {
            content.contains("no agents")
        } else {
            false
        }
    });
    assert!(
        has_output,
        "no-arg tool must have executed and returned output. Messages: {:#?}",
        messages
            .iter()
            .map(|m| format!("{:?}", m))
            .collect::<Vec<_>>()
    );
}