gadk-engine 0.5.30

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
// 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 ADK-Go `internal/llminternal/request_confirmation_processor_test.go`.

use std::any::Any;
use std::sync::Arc;

use async_trait::async_trait;
use gadk_agent::{
    Agent, Context, InvocationContext, REQUEST_CONFIRMATION_FUNCTION_CALL_NAME, RunnableTool, Tool,
    ToolError,
};
use gadk_genai::{Content, FunctionCall, FunctionDeclaration, FunctionResponse, Part, ROLE_USER};
use gadk_model::LlmRequest;
use gadk_session::{Event, ToolConfirmation};
use pretty_assertions::assert_eq;
use serde_json::{Map, Value, json};

use super::internal_llminternal_contents_processor::{FakeSession, ev, llm_agent};
use crate::llm::LlmAgentConfig;
use crate::llm::flow::Flow;
use crate::llm::processors::confirmation::request_confirmation_processor;

const MOCK_TOOL_NAME: &str = "mock_tool";
const MOCK_FUNCTION_CALL_ID: &str = "mock_function_call_id";
const MOCK_CONFIRMATION_FUNCTION_CALL_ID: &str = "mock_confirmation_function_call_id";

fn obj(v: Value) -> Map<String, Value> {
    v.as_object().cloned().unwrap()
}

/// Port of Go `mockTool`.
struct MockTool;
impl Tool for MockTool {
    fn name(&self) -> &str {
        MOCK_TOOL_NAME
    }
    fn description(&self) -> &str {
        "mock tool"
    }
    fn declaration(&self) -> Option<FunctionDeclaration> {
        Some(FunctionDeclaration {
            name: MOCK_TOOL_NAME.into(),
            ..Default::default()
        })
    }
    fn as_runnable(&self) -> Option<&dyn RunnableTool> {
        Some(self)
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
}
#[async_trait]
impl RunnableTool for MockTool {
    async fn run(&self, ctx: Context, _args: Value) -> Result<Map<String, Value>, ToolError> {
        if !ctx.tool_confirmation().is_some_and(|c| c.confirmed) {
            return Ok(obj(json!({"error": "Tool execution not confirmed"})));
        }
        Ok(obj(json!({"result": "Mock tool result with test"})))
    }
}

/// Port of Go `amountEchoTool`.
struct AmountEchoTool(&'static str);
impl Tool for AmountEchoTool {
    fn name(&self) -> &str {
        self.0
    }
    fn description(&self) -> &str {
        "transfers the given amount of funds"
    }
    fn declaration(&self) -> Option<FunctionDeclaration> {
        Some(FunctionDeclaration {
            name: self.0.into(),
            ..Default::default()
        })
    }
    fn as_runnable(&self) -> Option<&dyn RunnableTool> {
        Some(self)
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
}
#[async_trait]
impl RunnableTool for AmountEchoTool {
    async fn run(&self, ctx: Context, args: Value) -> Result<Map<String, Value>, ToolError> {
        if !ctx.tool_confirmation().is_some_and(|c| c.confirmed) {
            return Ok(obj(json!({"error": "tool execution not confirmed"})));
        }
        Ok(obj(
            json!({"executed_amount": args.get("amount").cloned().unwrap_or(Value::Null)}),
        ))
    }
}

/// Port of Go `newMockLlmAgent`: agent "testAgent" with the mock tool; returns the agent and its tools.
fn new_mock_llm_agent() -> (Arc<dyn Agent>, Vec<Arc<dyn Tool>>) {
    let tools: Vec<Arc<dyn Tool>> = vec![Arc::new(MockTool)];
    let agent = llm_agent(LlmAgentConfig {
        name: "testAgent".into(),
        tools: tools.clone(),
        ..Default::default()
    });
    (agent, tools)
}

/// Port of Go `createInvocationContext(t, agnt, &fakeSession{events})`.
fn create_invocation_context(agent: &Arc<dyn Agent>, events: Vec<Event>) -> InvocationContext {
    InvocationContext::builder()
        .session(FakeSession::shared(events))
        .agent(agent.clone())
        .build_invocation()
}

/// Go's loop over `llminternal.RequestConfirmationRequestProcessor(ctx, req, &llminternal.Flow{Tools: tools})`.
async fn run_processor(
    agent: &Arc<dyn Agent>,
    tools: Vec<Arc<dyn Tool>>,
    events: Vec<Event>,
) -> Vec<Event> {
    try_run_processor(agent, tools, events)
        .await
        .unwrap_or_else(|e| panic!("RequestConfirmationRequestProcessor() unexpected error: {e}"))
}

/// [`run_processor`] that returns the processor's error instead of failing.
async fn try_run_processor(
    agent: &Arc<dyn Agent>,
    tools: Vec<Arc<dyn Tool>>,
    events: Vec<Event>,
) -> Result<Vec<Event>, gadk_agent::AgentError> {
    let ctx = create_invocation_context(agent, events);
    let mut req = LlmRequest::default();
    let flow = Flow {
        tools: parking_lot::RwLock::new(tools),
        ..Default::default()
    };
    request_confirmation_processor(&ctx, &mut req, &flow).await
}

/// The fields Go ignores (ID, Timestamp, InvocationID, StateDelta, ArtifactDelta) are cleared.
fn normalize(mut e: Event) -> Event {
    e.id.clear();
    e.timestamp = gadk_session::zero_time();
    e.invocation_id.clear();
    e.actions.state_delta = None;
    e.actions.artifact_delta = None;
    e
}

fn user_confirmation(confirmed: bool) -> Map<String, Value> {
    let tc = ToolConfirmation {
        confirmed,
        ..Default::default()
    };
    obj(json!({"response": serde_json::to_string(&tc).unwrap()}))
}

fn confirmation_request(id: &str, original_id: &str, original_args: Value) -> Part {
    confirmation_request_for(MOCK_TOOL_NAME, id, original_id, original_args, "test hint")
}

/// An `adk_request_confirmation` call embedding `{name: tool, args, id: original_id}`.
fn confirmation_request_for(
    tool: &str,
    id: &str,
    original_id: &str,
    original_args: Value,
    hint: &str,
) -> Part {
    Part {
        function_call: Some(FunctionCall {
            name: REQUEST_CONFIRMATION_FUNCTION_CALL_NAME.into(),
            id: id.into(),
            args: obj(json!({
                "originalFunctionCall": {"name": tool, "args": original_args, "id": original_id},
                "toolConfirmation": ToolConfirmation { hint: hint.into(), confirmed: false, payload: None },
            })),
            ..Default::default()
        }),
        ..Default::default()
    }
}

fn confirmation_response(id: &str, confirmed: bool) -> Part {
    Part {
        function_response: Some(FunctionResponse {
            name: REQUEST_CONFIRMATION_FUNCTION_CALL_NAME.into(),
            id: id.into(),
            response: user_confirmation(confirmed),
            ..Default::default()
        }),
        ..Default::default()
    }
}

#[tokio::test]
async fn test_request_confirmation_request_processor() {
    let confirmation_events = |confirmed: bool| {
        vec![
            ev(
                "testAgent",
                Content {
                    parts: vec![confirmation_request(
                        MOCK_CONFIRMATION_FUNCTION_CALL_ID,
                        MOCK_FUNCTION_CALL_ID,
                        json!({"param1": "test"}),
                    )],
                    role: String::new(),
                },
            ),
            ev(
                "user",
                Content {
                    parts: vec![confirmation_response(
                        MOCK_CONFIRMATION_FUNCTION_CALL_ID,
                        confirmed,
                    )],
                    role: String::new(),
                },
            ),
        ]
    };
    let fr_event = |response: Value| {
        ev(
            "testAgent",
            Content::from_function_response(
                FunctionResponse {
                    name: MOCK_TOOL_NAME.into(),
                    id: MOCK_FUNCTION_CALL_ID.into(),
                    response: obj(response),
                    ..Default::default()
                },
                ROLE_USER,
            ),
        )
    };
    let other_fr = Content {
        parts: vec![Part {
            function_response: Some(FunctionResponse {
                name: "other_function".into(),
                ..Default::default()
            }),
            ..Default::default()
        }],
        role: String::new(),
    };
    // The confirmation events with the user's response wrapper replaced by `response`.
    let with_wrapper = |response: Value| {
        let mut events = confirmation_events(true);
        events[1].response.content.as_mut().unwrap().parts[0]
            .function_response
            .as_mut()
            .unwrap()
            .response = obj(response);
        events
    };
    // (name, events, want events; None = want an error)
    type ProcessorCase = (&'static str, Vec<Event>, Option<Vec<Event>>);
    let cases: Vec<ProcessorCase> = vec![
        ("NoEvents", vec![], Some(vec![])),
        (
            "NoFunctionResponses",
            vec![ev("user", Content::default())],
            Some(vec![]),
        ),
        (
            "NoConfirmationFunctionResponse",
            vec![ev("user", other_fr)],
            Some(vec![]),
        ),
        (
            "Success",
            confirmation_events(true),
            Some(vec![fr_event(
                json!({"result": "Mock tool result with test"}),
            )]),
        ),
        // A client that has already decoded the JSON sends the wrapper's value as an
        // object rather than a string. adk-python accepts it (tool_confirmation.py,
        // ToolConfirmation.from_response_dict).
        (
            "SuccessWithParsedResponseWrapper",
            with_wrapper(json!({"response": {"confirmed": true}})),
            Some(vec![fr_event(
                json!({"result": "Mock tool result with test"}),
            )]),
        ),
        // A decoded "no" must reject the tool just as the string form does.
        (
            "ToolNotConfirmedWithParsedResponseWrapper",
            with_wrapper(json!({"response": {"confirmed": false}})),
            Some(vec![fr_event(
                json!({"error": "Tool execution not confirmed"}),
            )]),
        ),
        (
            "ParsedResponseWrapperScalar",
            with_wrapper(json!({"response": 123})),
            None,
        ),
        (
            "NullResponseWrapper",
            with_wrapper(json!({"response": null})),
            None,
        ),
        (
            "ToolNotConfirmed",
            confirmation_events(false),
            Some(vec![fr_event(
                json!({"error": "Tool execution not confirmed"}),
            )]),
        ),
    ];
    for (name, events, want) in cases {
        let (agent, tools) = new_mock_llm_agent();
        let got = try_run_processor(&agent, tools, events).await;
        let Some(want) = want else {
            assert!(
                got.is_err(),
                "{name}: RequestConfirmationRequestProcessor() error = None, want an error"
            );
            continue;
        };
        let got: Vec<Event> = got
            .unwrap_or_else(|e| {
                panic!("{name}: RequestConfirmationRequestProcessor() unexpected error: {e}")
            })
            .into_iter()
            .map(normalize)
            .collect();
        assert_eq!(
            got.len(),
            want.len(),
            "{name}: RequestConfirmationRequestProcessor() event count"
        );
        if !want.is_empty() {
            assert_eq!(
                want, got,
                "{name}: RequestConfirmationRequestProcessor() event diff"
            );
        }
    }
}

#[tokio::test]
async fn test_request_confirmation_resume_order_is_stable() {
    // Request order intentionally differs from sorted order.
    let want_order = [
        "call_c3", "call_c1", "call_c5", "call_c2", "call_c6", "call_c4",
    ];
    let conf_id = |id: &str| format!("confirmation_{id}");
    let confirmation_parts: Vec<Part> = want_order
        .iter()
        .map(|id| confirmation_request(&conf_id(id), id, json!({"param1": "test"})))
        .collect();
    // Responses arrive in reverse order; re-dispatch must follow the request order.
    let response_order = [
        "call_c4", "call_c6", "call_c2", "call_c5", "call_c1", "call_c3",
    ];
    let response_parts: Vec<Part> = response_order
        .iter()
        .map(|id| confirmation_response(&conf_id(id), true))
        .collect();
    let events = vec![
        ev(
            "testAgent",
            Content {
                parts: confirmation_parts,
                role: String::new(),
            },
        ),
        ev(
            "user",
            Content {
                parts: response_parts,
                role: String::new(),
            },
        ),
    ];
    // Go repeats 10 times to catch map-order dependence; kept (HashMap iteration is randomized too).
    for run in 0..10 {
        let (agent, tools) = new_mock_llm_agent();
        let got = run_processor(&agent, tools, events.clone()).await;
        assert_eq!(
            got.len(),
            1,
            "run {run}: RequestConfirmationRequestProcessor() got {} events, want 1",
            got.len()
        );
        let content = got[0]
            .response
            .content
            .as_ref()
            .unwrap_or_else(|| panic!("run {run}: re-dispatch event or its content is nil"));
        let got_order: Vec<&str> = content
            .parts
            .iter()
            .filter_map(|p| p.function_response.as_ref())
            .map(|fr| fr.id.as_str())
            .collect();
        assert_eq!(
            want_order.to_vec(),
            got_order,
            "run {run}: re-dispatched function call order"
        );
    }
}

/// The FunctionResponse IDs of the single re-dispatch event.
fn redispatched_ids(got: &[Event]) -> Vec<String> {
    assert_eq!(
        got.len(),
        1,
        "RequestConfirmationRequestProcessor() got {} events, want 1",
        got.len()
    );
    let content = got[0]
        .response
        .content
        .as_ref()
        .expect("re-dispatch event or its content is nil");
    content
        .parts
        .iter()
        .filter_map(|p| p.function_response.as_ref())
        .map(|fr| fr.id.clone())
        .collect()
}

#[tokio::test]
async fn test_request_confirmation_resume_skips_already_answered_calls() {
    // Request order is intentionally unsorted; "call_a" is the one that has already been
    // answered and must be skipped, leaving "call_b" and "call_c".
    let request_order = ["call_b", "call_a", "call_c"];
    const ALREADY_ANSWERED: &str = "call_a";
    let conf_id = |id: &str| format!("confirmation_{id}");
    let confirmation_parts: Vec<Part> = request_order
        .iter()
        .map(|id| confirmation_request(&conf_id(id), id, json!({"param1": "test"})))
        .collect();
    let response_parts: Vec<Part> = request_order
        .iter()
        .map(|id| confirmation_response(&conf_id(id), true))
        .collect();
    let events = vec![
        ev(
            "testAgent",
            Content {
                parts: confirmation_parts,
                role: String::new(),
            },
        ),
        ev(
            "user",
            Content {
                parts: response_parts,
                role: String::new(),
            },
        ),
        // A later, agent-authored event that already carries the result for "call_a".
        ev(
            "testAgent",
            Content {
                parts: vec![Part {
                    function_response: Some(FunctionResponse {
                        name: MOCK_TOOL_NAME.into(),
                        id: ALREADY_ANSWERED.into(),
                        response: obj(json!({"result": "already answered"})),
                        ..Default::default()
                    }),
                    ..Default::default()
                }],
                role: String::new(),
            },
        ),
    ];
    let (agent, tools) = new_mock_llm_agent();
    let got = run_processor(&agent, tools, events).await;
    assert_eq!(
        vec!["call_b", "call_c"],
        redispatched_ids(&got),
        "re-dispatched function call order"
    );
}

/// A confirmation response delivered a second time, after the confirmed call already
/// produced a result, does not dispatch the tool again.
#[tokio::test]
async fn test_request_confirmation_repeated_approval_does_not_rerun_tool() {
    const CALL_ID: &str = "call-1";
    const CONFIRMATION_ID: &str = "confirmation_call-1";
    let approval = || {
        ev(
            "user",
            Content {
                parts: vec![confirmation_response(CONFIRMATION_ID, true)],
                role: String::new(),
            },
        )
    };
    let agent_event = |p: Part| {
        ev(
            "testAgent",
            Content {
                parts: vec![p],
                role: String::new(),
            },
        )
    };
    let fr = |response: Value| Part {
        function_response: Some(FunctionResponse {
            name: MOCK_TOOL_NAME.into(),
            id: CALL_ID.into(),
            response: obj(response),
            ..Default::default()
        }),
        ..Default::default()
    };
    let events = vec![
        agent_event(Part {
            function_call: Some(FunctionCall {
                name: MOCK_TOOL_NAME.into(),
                id: CALL_ID.into(),
                args: obj(json!({"param1": "test"})),
                ..Default::default()
            }),
            ..Default::default()
        }),
        agent_event(fr(json!({"error": "requires confirmation"}))),
        agent_event(confirmation_request(
            CONFIRMATION_ID,
            CALL_ID,
            json!({"param1": "test"}),
        )),
        approval(),
        // Result of the first resume.
        agent_event(fr(json!({"result": "done"}))),
        // The same approval delivered again.
        approval(),
    ];
    let (agent, tools) = new_mock_llm_agent();
    let got = run_processor(&agent, tools, events).await;
    for ev in &got {
        for part in ev.response.content.iter().flat_map(|c| c.parts.iter()) {
            assert!(
                part.function_response
                    .as_ref()
                    .is_none_or(|r| r.id != CALL_ID),
                "repeated approval re-dispatched already answered call {CALL_ID:?}"
            );
        }
    }
}

#[tokio::test]
async fn test_request_confirmation_resume_dedupes_duplicate_original_id() {
    const DUPLICATE_CALL_ID: &str = "call_dup";
    // Two distinct confirmation requests that both point at the same original function call.
    let confirmation_ids = ["confirmation_a", "confirmation_b"];
    let confirmation_parts: Vec<Part> = confirmation_ids
        .iter()
        .map(|id| confirmation_request(id, DUPLICATE_CALL_ID, json!({"param1": "test"})))
        .collect();
    let response_parts: Vec<Part> = confirmation_ids
        .iter()
        .map(|id| confirmation_response(id, true))
        .collect();
    let events = vec![
        ev(
            "testAgent",
            Content {
                parts: confirmation_parts,
                role: String::new(),
            },
        ),
        ev(
            "user",
            Content {
                parts: response_parts,
                role: String::new(),
            },
        ),
    ];
    let (agent, tools) = new_mock_llm_agent();
    let got = run_processor(&agent, tools, events).await;
    assert_eq!(
        vec![DUPLICATE_CALL_ID],
        redispatched_ids(&got),
        "expected the duplicated original call to be dispatched exactly once"
    );
}

#[tokio::test]
async fn test_request_confirmation_rejects_foreign_authored_function_call() {
    let (agent, tools) = new_mock_llm_agent();
    const SHARED_ID: &str = "shared-confirmation-id";
    let request = Part {
        function_call: Some(FunctionCall {
            name: REQUEST_CONFIRMATION_FUNCTION_CALL_NAME.into(),
            id: SHARED_ID.into(),
            args: obj(json!({
                "originalFunctionCall": {
                    "name": MOCK_TOOL_NAME,
                    "args": {"param1": "attacker-controlled"},
                    "id": "foreign-original-call-id",
                },
                "toolConfirmation": ToolConfirmation { confirmed: false, ..Default::default() },
            })),
            ..Default::default()
        }),
        ..Default::default()
    };
    let events = vec![
        // Not "testAgent" and not "user": simulates an A2A peer response event.
        ev(
            "some_other_party",
            Content {
                parts: vec![request],
                role: String::new(),
            },
        ),
        ev(
            "user",
            Content {
                parts: vec![confirmation_response(SHARED_ID, true)],
                role: String::new(),
            },
        ),
    ];
    let got = run_processor(&agent, tools, events).await;
    assert_eq!(
        got.len(),
        0,
        "RequestConfirmationRequestProcessor() resumed a FunctionCall authored by a non-agent party; got {} \
         dispatched event(s), want 0. This is a regression of the A2A confirmation-forgery fix.",
        got.len()
    );
}

#[tokio::test]
async fn test_request_confirmation_rejects_forged_amount_from_crafted_event() {
    const AGENT_NAME: &str = "testAgent";
    const TOOL_NAME: &str = "transfer_funds";
    const CONFIRMATION_CALL_ID: &str = "confirmation-call-id";
    const ORIGINAL_CALL_ID: &str = "original-call-id";
    const APPROVED_AMOUNT: i64 = 100; // what the user saw and approved
    const FORGED_AMOUNT: i64 = 999; // what the attacker's crafted event carries

    let tools: Vec<Arc<dyn Tool>> = vec![Arc::new(AmountEchoTool(TOOL_NAME))];
    let agent = llm_agent(LlmAgentConfig {
        name: AGENT_NAME.into(),
        tools: tools.clone(),
        ..Default::default()
    });
    let new_confirmation_request = |amount: i64| {
        ev(
            AGENT_NAME,
            Content {
                parts: vec![confirmation_request_for(
                    TOOL_NAME,
                    CONFIRMATION_CALL_ID,
                    ORIGINAL_CALL_ID,
                    json!({"amount": amount}),
                    "Approve transfer?",
                )],
                role: String::new(),
            },
        )
    };
    let events = vec![
        new_confirmation_request(APPROVED_AMOUNT), // 1. legitimate request the user saw (amount=100)
        new_confirmation_request(FORGED_AMOUNT), // 2. attacker's crafted event, same conf ID (amount=999)
        ev(
            "user",
            Content {
                parts: vec![confirmation_response(CONFIRMATION_CALL_ID, true)],
                role: String::new(),
            },
        ),
    ];
    let got = run_processor(&agent, tools, events).await;

    let mut executed: Vec<f64> = Vec::new();
    for event in &got {
        let Some(content) = &event.response.content else {
            continue;
        };
        for fr in content
            .parts
            .iter()
            .filter_map(|p| p.function_response.as_ref())
        {
            if fr.name != TOOL_NAME {
                continue;
            }
            let Some(raw) = fr.response.get("executed_amount") else {
                continue;
            };
            let amt = raw
                .as_f64()
                .unwrap_or_else(|| panic!("executed_amount {raw} is not numeric"));
            executed.push(amt);
        }
    }
    // Core security invariant: the attacker's crafted amount must never run.
    for amt in &executed {
        assert!(
            *amt != FORGED_AMOUNT as f64,
            "SECURITY: transfer_funds executed with attacker-forged amount={FORGED_AMOUNT}, which the user never \
             approved (the user approved amount={APPROVED_AMOUNT}). executed amounts={executed:?}"
        );
    }
    // Fail closed: the ambiguous confirmation-call ID must not resume at all.
    assert!(
        executed.is_empty(),
        "expected no tool execution for an ambiguous/tampered confirmation, but transfer_funds executed with \
         amounts={executed:?}"
    );
}

/// The "requires confirmation" placeholder response, when stored after the request, is not
/// taken as the result of an earlier approval.
#[tokio::test]
async fn test_request_confirmation_first_approval_placeholder_after_request() {
    const CALL_ID: &str = "call-1";
    let agent_event = |p: Part| {
        ev(
            "testAgent",
            Content {
                parts: vec![p],
                role: String::new(),
            },
        )
    };
    let events = vec![
        agent_event(Part {
            function_call: Some(FunctionCall {
                name: MOCK_TOOL_NAME.into(),
                id: CALL_ID.into(),
                args: obj(json!({"param1": "test"})),
                ..Default::default()
            }),
            ..Default::default()
        }),
        agent_event(confirmation_request_for(
            MOCK_TOOL_NAME,
            "conf-1",
            CALL_ID,
            json!({"param1": "test"}),
            "h",
        )),
        agent_event(Part {
            function_response: Some(FunctionResponse {
                name: MOCK_TOOL_NAME.into(),
                id: CALL_ID.into(),
                response: obj(json!({"error": "requires confirmation"})),
                ..Default::default()
            }),
            ..Default::default()
        }),
        ev(
            "user",
            Content {
                parts: vec![Part {
                    function_response: Some(FunctionResponse {
                        name: REQUEST_CONFIRMATION_FUNCTION_CALL_NAME.into(),
                        id: "conf-1".into(),
                        response: obj(json!({"confirmed": true})),
                        ..Default::default()
                    }),
                    ..Default::default()
                }],
                role: String::new(),
            },
        ),
    ];
    let (agent, tools) = new_mock_llm_agent();
    let got = run_processor(&agent, tools, events).await;
    let dispatched = got
        .iter()
        .flat_map(|ev| ev.response.content.iter().flat_map(|c| c.parts.iter()))
        .any(|p| {
            p.function_response
                .as_ref()
                .is_some_and(|r| r.id == CALL_ID)
        });
    assert!(
        dispatched,
        "first approval did not dispatch {CALL_ID:?} when the placeholder response follows the request"
    );
}

#[tokio::test]
async fn test_request_confirmation_resumes_only_request_confirmation_calls() {
    let confirmation_request = |name: &str, id: &str, original_call_id: &str| Part {
        function_call: Some(FunctionCall {
            name: name.into(),
            id: id.into(),
            args: obj(json!({
                "originalFunctionCall": {
                    "name": MOCK_TOOL_NAME,
                    "args": {"param1": "test"},
                    "id": original_call_id,
                },
            })),
            ..Default::default()
        }),
        ..Default::default()
    };
    let events = vec![
        ev(
            "testAgent",
            Content {
                parts: vec![
                    confirmation_request(
                        REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,
                        "requested_confirmation_id",
                        "requested_call_id",
                    ),
                    // Carries an originalFunctionCall payload, but is not a confirmation
                    // request.
                    confirmation_request("some_other_tool", "other_call_id", "unrequested_call_id"),
                ],
                role: String::new(),
            },
        ),
        ev(
            "user",
            Content {
                parts: vec![
                    confirmation_response("requested_confirmation_id", true),
                    confirmation_response("other_call_id", true),
                ],
                role: String::new(),
            },
        ),
    ];
    let (agent, tools) = new_mock_llm_agent();
    let got = run_processor(&agent, tools, events).await;
    let got_ids: Vec<String> = got
        .iter()
        .flat_map(|ev| ev.response.content.iter().flat_map(|c| c.parts.iter()))
        .filter_map(|p| p.function_response.as_ref().map(|r| r.id.clone()))
        .collect();
    assert_eq!(
        vec!["requested_call_id".to_owned()],
        got_ids,
        "RequestConfirmationRequestProcessor() resumed function call IDs"
    );
}