gadk-engine 0.5.2

The gadk runtime: LLM agent and flow, workflow agents and graphs, and the runner
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
// Copyright 2026 Chris Olson
// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Port of Go tool/agenttool/agent_tool_test.go.

use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use futures::StreamExt;

use gadk_agent::{
    Agent, AgentConfig, Context, ContextDelta, EventStream, InvocationContext, Tool, ToolError,
};
use gadk_genai::{
    CodeExecutionResult, Content, ExecutableCode, FunctionCall, FunctionDeclaration, Part,
    PartialArg, ROLE_MODEL, Schema, Type,
};
use gadk_model::{Llm, LlmRequest};
use gadk_session::{CreateRequest, Event, InMemorySessionService, SessionService};
use pretty_assertions::assert_eq;
use serde_json::{Map, Value, json};

use crate::llm::{LlmAgentConfig, agent as llm_agent};
use crate::testutil::MockModel;
use crate::tool::{AgentTool, AgentToolConfig, FunctionTool, FunctionToolConfig};

fn obj(v: Value) -> Map<String, Value> {
    let Value::Object(m) = v else {
        panic!("not an object")
    };
    m
}

fn schema_props(props: &[(&str, Type)], required: &[&str]) -> Schema {
    Schema {
        r#type: Some(Type::Object),
        properties: props
            .iter()
            .map(|(k, t)| {
                (
                    (*k).to_string(),
                    Schema {
                        r#type: Some(t.clone()),
                        ..Default::default()
                    },
                )
            })
            .collect::<BTreeMap<_, _>>(),
        required: required.iter().map(|s| (*s).to_string()).collect(),
        ..Default::default()
    }
}

fn output_schema() -> Schema {
    schema_props(
        &[("is_valid", Type::Boolean), ("message", Type::String)],
        &["is_valid", "message"],
    )
}

fn create_agent_with_model(
    input: Option<Schema>,
    output: Option<Schema>,
    model: Arc<dyn Llm>,
) -> Arc<dyn Agent> {
    llm_agent::new(LlmAgentConfig {
        name: "math_agent".into(),
        model: Some(model),
        description: "Solves math problems.".into(),
        instruction: "You solve math problems.".into(),
        input_schema: input,
        output_schema: output,
        ..Default::default()
    })
    .unwrap()
}

// parity: adapted: Go builds a Gemini client with a fake key that is never called; a MockModel
// with no replies stands in.
fn create_agent(input: Option<Schema>, output: Option<Schema>) -> Arc<dyn Agent> {
    create_agent_with_model(input, output, MockModel::from_contents(vec![]))
}

/// Go createToolContext: a tool context over a fresh in-memory session "testApp"/"testUser"/"testSession".
async fn create_tool_context() -> Context {
    let svc = InMemorySessionService::new();
    let sess = svc
        .create(CreateRequest {
            app_name: "testApp".into(),
            user_id: "testUser".into(),
            session_id: Some("testSession".into()),
            state: None,
        })
        .await
        .unwrap();
    // Go agent.NewToolContext(ctx, "", &session.EventActions{}, nil): the function_call_id delta
    // gives the context its own actions, so update_actions from the run is not dropped.
    Context::builder()
        .session(sess)
        .build()
        .with_delta(ContextDelta {
            function_call_id: Some(String::new()),
            ..Default::default()
        })
}

async fn run_tool(
    tool: &Arc<dyn Tool>,
    ctx: &Context,
    args: Value,
) -> Result<Map<String, Value>, ToolError> {
    tool.as_runnable()
        .expect("AgentTool is runnable")
        .run(ctx.clone(), args)
        .await
}

fn request_decl() -> FunctionDeclaration {
    FunctionDeclaration {
        name: "math_agent".into(),
        description: "Solves math problems.".into(),
        parameters: Some(schema_props(&[("request", Type::String)], &["request"])),
        ..Default::default()
    }
}

fn model_content(parts: Vec<Part>) -> Content {
    Content {
        role: ROLE_MODEL.into(),
        parts,
    }
}

fn thought(text: &str) -> Part {
    Part {
        text: text.into(),
        thought: true,
        ..Default::default()
    }
}

#[test]
fn test_agent_tool_declaration() {
    let agent = create_agent(
        Some(schema_props(&[("request", Type::String)], &["request"])),
        None,
    );
    let tool = AgentTool::new(agent, None);
    assert!(
        tool.as_runnable().is_some(),
        "agentTool does not implement FunctionTool"
    );
    assert_eq!(tool.declaration(), Some(request_decl()));
}

#[test]
fn test_agent_tool_declaration_without_schema() {
    let tool = AgentTool::new(create_agent(None, None), None);
    assert!(
        tool.as_runnable().is_some(),
        "agentTool does not implement FunctionTool"
    );
    assert_eq!(tool.declaration(), Some(request_decl()));
}

#[tokio::test]
async fn test_agent_tool_run_input_validation() {
    let input = schema_props(
        &[("is_magic", Type::Boolean), ("name", Type::String)],
        &["is_magic", "name"],
    );
    let tool = AgentTool::new(create_agent(Some(input), None), None);
    let ctx = create_tool_context().await;
    let cases = [
        (
            "extra_field",
            json!({"is_magic": true, "name_invalid": "test_name", "name": "test"}),
        ),
        (
            "invalid_type",
            json!({"is_magic": "invalid_type", "name": "test_name"}),
        ),
        ("missing_required", json!({"is_magic": true})),
    ];
    for (name, args) in cases {
        let res = run_tool(&tool, &ctx, args.clone()).await;
        assert!(
            res.is_err(),
            "{name}: Run({args}) succeeded unexpectedly, wanted error"
        );
    }
}

#[tokio::test]
async fn test_agent_tool_run_output_validation() {
    let model = MockModel::from_contents(vec![Content::from_text(
        r#"{"is_valid": "invalid type", "message": "success"}"#,
        ROLE_MODEL,
    )]);
    let tool = AgentTool::new(
        create_agent_with_model(None, Some(output_schema()), model),
        None,
    );
    let ctx = create_tool_context().await;
    let res = run_tool(&tool, &ctx, json!({"request": "test"})).await;
    assert!(res.is_err(), "Run() succeeded unexpectedly, want error");
}

#[tokio::test]
async fn test_agent_tool_run_successful() {
    let input = schema_props(&[("is_magic", Type::Boolean)], &["is_magic"]);
    let model = MockModel::from_contents(vec![Content::from_text(
        r#"{"is_valid": true, "message": "success"}"#,
        ROLE_MODEL,
    )]);
    let tool = AgentTool::new(
        create_agent_with_model(Some(input), Some(output_schema()), model),
        None,
    );
    let ctx = create_tool_context().await;
    let got = run_tool(&tool, &ctx, json!({"is_magic": true}))
        .await
        .expect("Run() failed unexpectedly");
    assert_eq!(got, obj(json!({"is_valid": true, "message": "success"})));
}

// TestAgentTool_Run_CompositeAgentInputSchema checks that a wrapped workflow
// agent whose first sub-agent has an InputSchema takes the arguments its
// declaration advertises, as adk-python's AgentTool does with
// _get_input_schema.
#[tokio::test]
async fn test_agent_tool_run_composite_agent_input_schema() {
    let input_schema = schema_props(&[("is_magic", Type::Boolean)], &["is_magic"]);
    let cases = [
        (
            "valid_arguments",
            json!({"is_magic": true}),
            Some(json!({"result": "magic"})),
        ),
        ("invalid_arguments", json!({"is_magic": "yes"}), None),
    ];
    for (name, args, want) in cases {
        let model = MockModel::from_contents(vec![Content::from_text("magic", ROLE_MODEL)]);
        let pipeline = crate::agents::sequential_agent::new(
            crate::agents::sequential_agent::SequentialAgentConfig {
                agent: AgentConfig {
                    name: "pipeline".into(),
                    description: "Runs the math agent.".into(),
                    sub_agents: vec![create_agent_with_model(
                        Some(input_schema.clone()),
                        None,
                        model,
                    )],
                    ..Default::default()
                },
            },
        )
        .unwrap_or_else(|e| panic!("{name}: sequentialagent.New() failed: {e}"));
        let tool = AgentTool::new(pipeline, None);
        assert_eq!(
            tool.declaration().and_then(|d| d.parameters),
            Some(input_schema.clone()),
            "{name}: Declaration().Parameters"
        );
        let ctx = create_tool_context().await;
        let got = run_tool(&tool, &ctx, args.clone()).await;
        match want {
            None => {
                // The schema rejects the arguments, rather than the missing
                // "request" the declaration never asked for.
                let err = got.expect_err("want an argument validation error");
                assert!(
                    err.to_string().contains("argument validation failed"),
                    "{name}: Run({args}) error = {err}, want an argument validation error"
                );
            }
            Some(want) => {
                let got = got.unwrap_or_else(|e| panic!("{name}: Run({args}) failed: {e}"));
                assert_eq!(got, obj(want), "{name}: Run() result");
            }
        }
    }
}

#[tokio::test]
async fn test_agent_tool_run_without_schema() {
    let model = MockModel::from_contents_streaming(
        vec![model_content(vec![
            Part::from_text("First text part is returned"),
            Part::from_text(" This should not be ignored"),
        ])],
        1,
    );
    let tool = AgentTool::new(create_agent_with_model(None, None, model), None);
    let ctx = create_tool_context().await;
    let got = run_tool(&tool, &ctx, json!({"request": "magic"}))
        .await
        .expect("Run() failed unexpectedly");
    assert_eq!(
        got,
        obj(json!({"result": "First text part is returned This should not be ignored"}))
    );
}

fn cer(output: &str) -> Option<CodeExecutionResult> {
    Some(CodeExecutionResult {
        output: output.into(),
        ..Default::default()
    })
}

fn code(code: &str) -> Option<ExecutableCode> {
    Some(ExecutableCode {
        code: code.into(),
        ..Default::default()
    })
}

/// A custom agent "calculator" yielding one model event with `parts`.
fn calculator(parts: Vec<Part>) -> Arc<dyn Agent> {
    gadk_agent::new_agent(AgentConfig {
        name: "calculator".into(),
        run: Some(Arc::new(move |ctx: InvocationContext| -> EventStream {
            let parts = parts.clone();
            Box::pin(async_stream::stream! {
                let mut event = Event::new(ctx.platform(), ctx.invocation_id());
                event.author = "calculator".into();
                event.response.content = Some(model_content(parts));
                yield Ok(event);
            })
        })),
        ..Default::default()
    })
    .expect("agent.New failed")
}

#[tokio::test]
async fn test_agent_tool_run_code_parts() {
    let cases: Vec<(&str, Vec<Part>, Value)> = vec![
        (
            "code execution output",
            vec![Part {
                code_execution_result: cer("\n 42 \n\n"),
                ..Default::default()
            }],
            json!({"result": "\n 42 "}),
        ),
        (
            "executable code",
            vec![Part {
                executable_code: code("print(42)\n"),
                ..Default::default()
            }],
            json!({"result": "print(42)\n"}),
        ),
        (
            "mixed content",
            vec![
                Part::from_text("Calculating."),
                Part {
                    executable_code: code("print(42)"),
                    ..Default::default()
                },
                Part {
                    code_execution_result: cer("42\n"),
                    ..Default::default()
                },
                Part::from_text("Done."),
            ],
            json!({"result": "Calculating.\nprint(42)\n42\nDone."}),
        ),
        (
            "empty and thought parts",
            vec![
                // parity: adapted: Go's nil part has no Rust equivalent; a default part stands in.
                Part::default(),
                Part::default(),
                Part {
                    code_execution_result: cer(""),
                    ..Default::default()
                },
                Part {
                    code_execution_result: cer("\n\n"),
                    ..Default::default()
                },
                Part {
                    executable_code: code(""),
                    ..Default::default()
                },
                Part {
                    thought: true,
                    code_execution_result: cer("hidden"),
                    ..Default::default()
                },
                Part {
                    thought: true,
                    executable_code: code("hidden"),
                    ..Default::default()
                },
            ],
            json!({"result": ""}),
        ),
        (
            "text and code precedence",
            vec![
                Part {
                    text: "text".into(),
                    code_execution_result: cer("unused"),
                    executable_code: code("unused"),
                    ..Default::default()
                },
                Part {
                    code_execution_result: cer("output"),
                    executable_code: code("unused"),
                    ..Default::default()
                },
                Part {
                    code_execution_result: cer(""),
                    executable_code: code("code"),
                    ..Default::default()
                },
            ],
            json!({"result": "text\noutput\ncode"}),
        ),
    ];
    for (name, parts, want) in cases {
        let wrapped = AgentTool::new(calculator(parts), None);
        let ctx = create_tool_context().await;
        let got = run_tool(&wrapped, &ctx, json!({"request": "calculate"}))
            .await
            .unwrap_or_else(|e| panic!("{name}: Run failed: {e}"));
        assert_eq!(
            got,
            obj(want),
            "{name}: Run returned an unexpected tool result"
        );
    }
}

#[tokio::test]
async fn test_agent_tool_run_filters_thought_parts() {
    let model = MockModel::from_contents_streaming(
        vec![model_content(vec![
            thought("Let me think about this..."),
            thought(""), // edge case: empty text + thought
            Part::from_text("The answer is 42"),
            thought("Still reasoning..."),
        ])],
        1,
    );
    let tool = AgentTool::new(create_agent_with_model(None, None, model), None);
    let ctx = create_tool_context().await;
    let got = run_tool(&tool, &ctx, json!({"request": "what is the answer?"}))
        .await
        .expect("Run() failed unexpectedly");
    assert_eq!(got, obj(json!({"result": "The answer is 42"})));
}

#[tokio::test]
async fn test_agent_tool_run_all_thought_parts_returns_empty() {
    let model = MockModel::from_contents_streaming(
        vec![model_content(vec![thought("Just thinking...")])],
        1,
    );
    let tool = AgentTool::new(create_agent_with_model(None, None, model), None);
    let ctx = create_tool_context().await;
    let got = run_tool(&tool, &ctx, json!({"request": "think only"}))
        .await
        .expect("Run() failed unexpectedly");
    assert_eq!(got, obj(json!({"result": ""})));
}

// A reply without text is an empty result even when the agent has an output
// schema, where adk-python validates the empty text and raises.
#[tokio::test]
async fn test_agent_tool_run_all_thought_parts_returns_empty_with_output_schema() {
    let output_schema = schema_props(&[("is_valid", Type::Boolean)], &["is_valid"]);
    let model = MockModel::from_contents_streaming(
        vec![model_content(vec![thought("Just thinking...")])],
        1,
    );
    let tool = AgentTool::new(
        create_agent_with_model(None, Some(output_schema), model),
        None,
    );
    let ctx = create_tool_context().await;
    let got = run_tool(&tool, &ctx, json!({"request": "think only"}))
        .await
        .expect("Run() failed unexpectedly");
    assert_eq!(got, obj(json!({"result": ""})));
}

#[tokio::test]
async fn test_agent_tool_run_filters_thought_parts_with_output_schema() {
    let model = MockModel::from_contents_streaming(
        vec![model_content(vec![
            thought("Let me validate the input carefully..."),
            Part::from_text(r#"{"is_valid": true, "message": "success"}"#),
        ])],
        1,
    );
    let tool = AgentTool::new(
        create_agent_with_model(None, Some(output_schema()), model),
        None,
    );
    let ctx = create_tool_context().await;
    let got = run_tool(&tool, &ctx, json!({"request": "validate"}))
        .await
        .expect("Run() failed unexpectedly");
    assert_eq!(got, obj(json!({"is_valid": true, "message": "success"})));
}

#[tokio::test]
async fn test_agent_tool_run_empty_model_response() {
    let model = MockModel::from_contents(vec![model_content(vec![])]);
    let tool = AgentTool::new(create_agent_with_model(None, None, model), None);
    let ctx = create_tool_context().await;
    let got = run_tool(&tool, &ctx, json!({"request": "magic"}))
        .await
        .expect("Run() failed unexpectedly");
    assert_eq!(got, obj(json!({"result": ""})));
}

#[tokio::test]
async fn test_agent_tool_run_no_content_returns_empty_result() {
    let child = gadk_agent::new_agent(AgentConfig {
        name: "silent".into(),
        run: Some(Arc::new(|ctx: InvocationContext| -> EventStream {
            Box::pin(async_stream::stream! {
                let mut event = Event::new(ctx.platform(), ctx.invocation_id());
                event.author = "silent".into();
                yield Ok(event);
            })
        })),
        ..Default::default()
    })
    .expect("agent.New failed");
    let wrapped = AgentTool::new(child, None);
    let ctx = create_tool_context().await;
    let got = run_tool(&wrapped, &ctx, json!({"request": "anything"}))
        .await
        .expect("Run() failed unexpectedly");
    assert_eq!(got, obj(json!({"result": ""})));
}

#[tokio::test]
async fn test_agent_tool_run_skip_summarization() {
    let input_schema = schema_props(&[("city", Type::String)], &["city"]);
    let cases = [
        (true, None, json!({"request": "magic"})),
        (false, None, json!({"request": "magic"})),
        (true, Some(input_schema.clone()), json!({"city": "Paris"})),
        (false, Some(input_schema), json!({"city": "Paris"})),
    ];
    for (skip, input, args) in cases {
        let model = MockModel::from_contents(vec![Content::from_text("test response", ROLE_MODEL)]);
        let ag = create_agent_with_model(input, None, model);
        let ctx = create_tool_context().await;
        let tool = AgentTool::new(
            ag,
            Some(AgentToolConfig {
                skip_summarization: skip,
            }),
        );
        run_tool(&tool, &ctx, args)
            .await
            .expect("Run() failed unexpectedly");
        assert_eq!(
            ctx.actions().skip_summarization,
            skip,
            "SkipSummarization propagated to parent tool context"
        );
    }
}

/// Go `transferArgs`.
#[derive(serde::Deserialize, schemars::JsonSchema)]
#[allow(dead_code)] // only its schema matters
struct TransferArgs {
    amount: i64,
}

fn call_part(id: &str, name: &str, args: Value) -> Content {
    model_content(vec![Part {
        function_call: Some(FunctionCall {
            id: id.into(),
            name: name.into(),
            args: obj(args),
            ..Default::default()
        }),
        ..Default::default()
    }])
}

/// A function tool over `TransferArgs` returning `result`.
fn transfer_like_tool(
    name: &str,
    description: &str,
    require_confirmation: bool,
    is_long_running: bool,
    result: Option<Value>,
    ran: Option<Arc<AtomicBool>>,
) -> Arc<dyn Tool> {
    let mut cfg = FunctionToolConfig::new(name, description);
    cfg.require_confirmation = require_confirmation;
    cfg.is_long_running = is_long_running;
    FunctionTool::new(cfg, move |_ctx: Context, _args: TransferArgs| {
        let result = result.clone();
        let ran = ran.clone();
        async move {
            if let Some(r) = ran {
                r.store(true, Ordering::SeqCst);
            }
            Ok::<_, ToolError>(result.map(obj))
        }
    })
    .expect("functiontool.New() failed")
}

fn child_agent(
    name: &str,
    description: &str,
    model: Arc<dyn Llm>,
    tool: Arc<dyn Tool>,
) -> Arc<dyn Agent> {
    llm_agent::new(LlmAgentConfig {
        name: name.into(),
        description: description.into(),
        model: Some(model),
        tools: vec![tool],
        ..Default::default()
    })
    .expect("llmagent.New() failed")
}

#[tokio::test]
async fn test_agent_tool_run_pending_confirmation_returns_error() {
    let ran = Arc::new(AtomicBool::new(false));
    let transfer = transfer_like_tool(
        "transfer",
        "Transfers money.",
        true,
        false,
        Some(json!({"status": "done"})),
        Some(ran.clone()),
    );
    let model = MockModel::from_contents(vec![call_part(
        "call-1",
        "transfer",
        json!({"amount": 100}),
    )]);
    let child = child_agent("payments_agent", "Moves money.", model, transfer);
    let tool = AgentTool::new(child, None);

    let ctx = create_tool_context().await;
    // Something other than the tool's Config, e.g. a BeforeToolCallback, set
    // the flag on this call.
    ctx.update_actions(|a| a.skip_summarization = true);

    let result = run_tool(&tool, &ctx, json!({"request": "send 100"})).await;

    assert!(
        !ctx.actions().skip_summarization,
        "SkipSummarization still set; the parent model would never see the error"
    );
    assert!(
        !ran.load(Ordering::SeqCst),
        "transfer ran without confirmation"
    );
    let err = match result {
        Ok(r) => panic!("Run() = {r:?}, nil; want an error for the unresolved confirmation"),
        Err(e) => e,
    };
    assert!(
        err.to_string()
            .contains("unresolved long-running tool calls"),
        "Run() error = {err:?}, want it to report the unresolved call"
    );
}

#[tokio::test]
async fn test_agent_tool_run_answered_long_running_call_succeeds() {
    let start = transfer_like_tool(
        "start_job",
        "Starts a job.",
        false,
        true,
        Some(json!({"status": "started"})),
        None,
    );
    let model = MockModel::from_contents(vec![
        call_part("call-1", "start_job", json!({"amount": 1})),
        Content::from_text("job started", ROLE_MODEL),
    ]);
    let child = child_agent("jobs_agent", "Starts jobs.", model, start);
    let tool = AgentTool::new(child, None);
    let ctx = create_tool_context().await;
    let result = run_tool(&tool, &ctx, json!({"request": "start"}))
        .await
        .expect("Run() failed unexpectedly");
    assert_eq!(
        result.get("result"),
        Some(&json!("job started")),
        "Run() result = {result:?}, want job started"
    );
}

// With SkipSummarization, the pending-call error must still go back to the
// parent model instead of ending the parent's turn on an empty response.
#[tokio::test]
async fn test_agent_tool_run_skip_summarization_pending_error_reaches_parent() {
    let transfer = transfer_like_tool(
        "transfer",
        "Transfers money.",
        true,
        false,
        Some(json!({"status": "done"})),
        None,
    );
    let child_model =
        MockModel::from_contents(vec![call_part("call-1", "transfer", json!({"amount": 1}))]);
    let child = child_agent("payments_agent", "Moves money.", child_model, transfer);
    let parent_llm = MockModel::from_contents(vec![
        call_part("p-1", "payments_agent", json!({"request": "send"})),
        Content::from_text("handled the error", ROLE_MODEL),
    ]);
    let parent = llm_agent::new(LlmAgentConfig {
        name: "root".into(),
        model: Some(parent_llm.clone()),
        tools: vec![AgentTool::new(
            child,
            Some(AgentToolConfig {
                skip_summarization: true,
            }),
        )],
        ..Default::default()
    })
    .expect("llmagent.New() failed");
    let runner = crate::testutil::TestAgentRunner::new(parent).await;
    let mut stream = runner.run("pay");
    while let Some(item) = stream.next().await {
        item.unwrap_or_else(|e| panic!("Run() failed: {e}"));
    }

    let requests = parent_llm.requests();
    assert_eq!(
        requests.len(),
        2,
        "parent model requests = {}, want 2 (the second carrying the agent tool's error)",
        requests.len()
    );
    assert!(
        request_has_function_response_error(&requests[1], "unresolved long-running tool calls"),
        "second parent model request does not carry the agent tool's pending-call error"
    );
}

/// Go `requestHasFunctionResponseError`.
fn request_has_function_response_error(req: &LlmRequest, want: &str) -> bool {
    req.contents
        .iter()
        .flat_map(|c| c.parts.iter())
        .filter_map(|p| p.function_response.as_ref())
        .any(|fr| {
            fr.response
                .get("error")
                .and_then(Value::as_str)
                .is_some_and(|msg| msg.contains(want))
        })
}

/// The two streamed chunks of a `start_job` call whose arguments arrive without an ID.
fn streamed_start_job_call() -> Vec<Content> {
    vec![
        model_content(vec![Part {
            function_call: Some(FunctionCall {
                name: "start_job".into(),
                will_continue: Some(true),
                ..Default::default()
            }),
            ..Default::default()
        }]),
        model_content(vec![Part {
            function_call: Some(FunctionCall {
                partial_args: vec![PartialArg {
                    json_path: "$.amount".into(),
                    number_value: Some(1.0),
                    ..Default::default()
                }],
                will_continue: Some(false),
                ..Default::default()
            }),
            ..Default::default()
        }]),
    ]
}

// A long-running call whose arguments are streamed without an ID gets a
// different generated ID on each partial chunk than on the final event. Only
// the final event's ID is answered, so partial chunks must not count.
#[tokio::test]
async fn test_agent_tool_run_streamed_args_answered_long_running_call_succeeds() {
    let start = transfer_like_tool(
        "start_job",
        "Starts a job.",
        false,
        true,
        Some(json!({"status": "started"})),
        None,
    );
    let mut contents = streamed_start_job_call();
    contents.push(Content::from_text("job started", ROLE_MODEL));
    let model = MockModel::from_contents_streaming(contents, 2);
    let child = child_agent("jobs_agent", "Starts jobs.", model, start);
    let tool = AgentTool::new(child, None);
    let ctx = create_tool_context().await;
    let result = run_tool(&tool, &ctx, json!({"request": "start"}))
        .await
        .expect("Run() failed unexpectedly");
    assert_eq!(
        result.get("result"),
        Some(&json!("job started")),
        "Run() result = {result:?}, want job started"
    );
}

// Skipping partial chunks must not drop the final event's ID when a streamed
// long-running call is never answered.
#[tokio::test]
async fn test_agent_tool_run_streamed_args_unanswered_long_running_call_returns_error() {
    let start = transfer_like_tool("start_job", "Starts a job.", false, true, None, None);
    let model = MockModel::from_contents_streaming(streamed_start_job_call(), 2);
    let child = child_agent("jobs_agent", "Starts jobs.", model, start);
    let tool = AgentTool::new(child, None);
    let ctx = create_tool_context().await;
    let err = match run_tool(&tool, &ctx, json!({"request": "start"})).await {
        Ok(r) => panic!("Run() = {r:?}, nil; want an error for the unanswered call"),
        Err(e) => e,
    };
    assert!(
        err.to_string()
            .contains("unresolved long-running tool calls"),
        "Run() error = {err:?}, want it to report the unresolved call"
    );
}

// With SkipSummarization, invalid arguments must not end the parent turn: the
// error goes back to the parent model so it can retry with corrected args.
#[tokio::test]
async fn test_agent_tool_run_skip_summarization_not_set_on_invalid_args() {
    let input_schema = schema_props(
        &[("city", Type::String), ("days", Type::Integer)],
        &["city", "days"],
    );
    let cases = [
        (
            "input_schema_missing_required",
            Some(input_schema),
            json!({"city": "Paris"}),
        ),
        ("no_schema_missing_request", None, json!({"query": "Paris"})),
    ];
    for (name, input, args) in cases {
        let ag = create_agent(input, None);
        let ctx = create_tool_context().await;
        let tool = AgentTool::new(
            ag,
            Some(AgentToolConfig {
                skip_summarization: true,
            }),
        );
        assert!(
            run_tool(&tool, &ctx, args.clone()).await.is_err(),
            "{name}: Run({args}) succeeded unexpectedly, wanted error"
        );
        assert!(
            !ctx.actions().skip_summarization,
            "{name}: SkipSummarization = true after invalid arguments, want false so the parent model can retry"
        );
    }
}