adk-runner 3.0.0

Agent execution runtime for Rust Agent Development Kit (ADK-Rust) agents
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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
use adk_core::{
    AdkIdentity, Agent, AppName, Artifacts, CallbackContext, Content, Event, ExecutionIdentity,
    InvocationContext as InvocationContextTrait, InvocationId, Memory, Part, ReadonlyContext,
    RequestContext, RunConfig, SecretService, SessionId, UserId,
};
use adk_session::Session as AdkSession;
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::{Arc, PoisonError, RwLock, atomic::AtomicBool};

/// MutableSession wraps a session with shared mutable state.
///
/// This mirrors ADK-Go's MutableSession pattern where state changes from
/// events are immediately visible to all agents sharing the same context.
/// This is critical for SequentialAgent/LoopAgent patterns where downstream
/// agents need to read state set by upstream agents via output_key.
///
/// A panic while another thread holds one of its locks poisons the lock. Every write is a
/// single insert, push or assignment, so the data stays whole, and reads and writes go on
/// using it rather than seeing an empty history or dropping events.
pub struct MutableSession {
    /// The session's ID, app name and user ID, taken from the snapshot it was built from.
    id: String,
    app_name: String,
    user_id: String,
    /// Shared mutable state - updated when events are processed
    /// This is the key difference from the old SessionAdapter which used immutable snapshots
    state: Arc<RwLock<HashMap<String, serde_json::Value>>>,
    /// Accumulated events during this invocation (uses adk_core::Event which is re-exported by adk_session)
    events: Arc<RwLock<Vec<Event>>>,
}

impl MutableSession {
    /// Create a new MutableSession from a session snapshot.
    ///
    /// The state is copied from the session and becomes mutable. The events are moved out of
    /// the snapshot ([`Session::take_events`](AdkSession::take_events)) when this is its only
    /// handle, as it is for the session the runner loads, and copied otherwise. The snapshot
    /// is not kept.
    pub fn new(mut session: Arc<dyn AdkSession>) -> Self {
        let initial_events = match Arc::get_mut(&mut session) {
            Some(owned) => owned.take_events(),
            None => session.events().all(),
        };

        Self {
            id: session.id().to_string(),
            app_name: session.app_name().to_string(),
            user_id: session.user_id().to_string(),
            state: Arc::new(RwLock::new(session.state().all())),
            events: Arc::new(RwLock::new(initial_events)),
        }
    }

    /// Apply state delta from an event to the mutable state.
    /// This is called by the Runner when events are yielded.
    ///
    /// Every key applies, `temp:` keys included, so a later tool, agent or `{temp:key}`
    /// instruction in the same invocation reads them. Session services drop `temp:` keys when
    /// they persist an event.
    pub fn apply_state_delta(&self, delta: &HashMap<String, serde_json::Value>) {
        if delta.is_empty() {
            return;
        }

        let mut state = self.state.write().unwrap_or_else(PoisonError::into_inner);
        // `temp:` keys stay for the rest of the invocation; the session service drops them
        // when it persists the event, so they never outlive it.
        for (key, value) in delta {
            state.insert(key.clone(), value.clone());
        }
    }

    /// Append an event to the session's event list.
    /// This keeps the in-memory view consistent.
    pub fn append_event(&self, event: Event) {
        let mut events = self.events.write().unwrap_or_else(PoisonError::into_inner);
        events.push(event);
    }

    /// Get a snapshot of all events in the session.
    /// Used by the runner for compaction decisions.
    pub fn events_snapshot(&self) -> Vec<Event> {
        let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
        events.clone()
    }

    /// Replace all events with a new list (used by intra-invocation compaction).
    pub fn replace_events(&self, new_events: Vec<Event>) {
        let mut events = self.events.write().unwrap_or_else(PoisonError::into_inner);
        *events = new_events;
    }

    /// Runs `read` over the events without copying them.
    pub(crate) fn read_events<R>(&self, read: impl FnOnce(&[Event]) -> R) -> R {
        let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
        read(&events)
    }

    /// Return the number of accumulated events without cloning the full list.
    pub fn events_len(&self) -> usize {
        let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
        events.len()
    }

    /// Build conversation history, optionally filtered for a specific agent.
    ///
    /// When `agent_name` is `Some`, events authored by other agents (not "user",
    /// not the named agent, and not function/tool responses) are excluded. This
    /// prevents a transferred sub-agent from seeing the parent's tool calls
    /// mapped as "model" role, which would cause the LLM to think work is
    /// already done.
    ///
    /// When `agent_name` is `None`, all events are included (backward-compatible).
    ///
    /// A system notice ([`system_notice_event`](adk_core::history::system_notice_event)) is
    /// kept as a user-role turn either way.
    ///
    /// `branch` additionally scopes history to a conversation branch: an event is
    /// kept when its branch equals `branch` or is an ancestor of it, so
    /// concurrent `ParallelAgent` branches do not read each other's output. An
    /// empty `branch`, or an event without one, matches everything. Events a tool
    /// published on its own branch below `branch`
    /// ([`tool_branch`](adk_core::history::tool_branch)) are left out.
    pub fn conversation_history_for_agent_impl(
        &self,
        agent_name: Option<&str>,
        branch: &str,
    ) -> Vec<adk_core::Content> {
        match agent_name {
            Some(name) => self.project_history(Some(name), OtherAgents::Exclude, branch),
            None => self.project_history(None, OtherAgents::AsOwnTurns, branch),
        }
    }

    fn project_history(
        &self,
        agent_name: Option<&str>,
        others: OtherAgents,
        branch: &str,
    ) -> Vec<adk_core::Content> {
        let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
        let mut history = Vec::new();
        let call_ids = adk_core::history::function_call_ids(&events);

        // Find the most recent compaction event — everything before its
        // end_timestamp has been summarized and should be replaced by the
        // compacted content.
        let mut compaction_boundary = None;
        // Turns the compaction kept were answered with the history before it; a provider binds
        // thinking to that history, so their thinking is not replayed after the summary, unless
        // the provider wrote the summary itself and accepts it.
        let mut compacted_at = None;
        for event in events.iter().rev() {
            if let Some(ref compaction) = event.actions.compaction {
                let mut content = compaction.compacted_content.clone();
                // A provider's own compaction keeps its signed copy for the provider and model
                // the runner recorded on the event; any other summary carries no native item.
                let origin = adk_core::intra_compaction::is_native_compaction(&content)
                    .then(|| {
                        adk_core::history::ProviderOrigin::of_response(
                            event.llm_response.provider_metadata.as_ref(),
                        )
                    })
                    .flatten();
                match &origin {
                    Some(origin) => adk_core::history::mark_origin(&mut content, Some(origin)),
                    None => adk_core::history::strip_native(&mut content),
                }
                let keeps_thinking = origin.is_some()
                    && event
                        .llm_response
                        .provider_metadata
                        .as_ref()
                        .and_then(|metadata| {
                            metadata.get(crate::intra_compaction::KEEPS_THINKING_KEY)
                        })
                        .and_then(serde_json::Value::as_bool)
                        == Some(true);
                if !keeps_thinking {
                    compacted_at = Some(event.timestamp);
                }
                history.push(HistoryContent { content, invocation_id: None });
                compaction_boundary = Some(compaction.end_timestamp);
                break;
            }
        }

        for event in events.iter() {
            // Skip the compaction event itself
            if event.actions.compaction.is_some() {
                continue;
            }

            // Streamed deltas are superseded by their terminal event, which carries the
            // complete response; the persisted session holds only that terminal event.
            if event.llm_response.partial {
                continue;
            }

            // A confirmation interrupt's text is a notice to the caller, not model output; in
            // the history it would end the conversation on an assistant turn after the call's
            // response, which providers without assistant prefill reject.
            if event.actions.tool_confirmation.is_some() {
                continue;
            }

            // Skip events that were already compacted
            if let Some(boundary) = compaction_boundary
                && event.timestamp <= boundary
            {
                continue;
            }

            // Skip events from sibling branches (and from branches nested below
            // this one). Ancestor branches stay visible so a sub-agent still sees
            // the conversation that led to it.
            if !adk_core::event_belongs_to_branch(branch, &event.branch) {
                continue;
            }

            // What a tool published on its own branch is progress for observers; the
            // caller's model gets the tool's response.
            if adk_core::history::is_tool_branch_event(branch, &event.branch, &call_ids) {
                continue;
            }

            let Some(content) = &event.llm_response.content else {
                continue;
            };
            // The runtime's notice is addressed to every agent: not another agent's context to
            // quote or leave out, and never a model turn.
            if adk_core::history::is_system_notice_event(event) {
                history.push(HistoryContent {
                    content: content.clone(),
                    invocation_id: Some(event.invocation_id.clone()),
                });
                continue;
            }
            let other_agent =
                agent_name.is_some_and(|name| event.author != "user" && event.author != name);
            let mapped_content = match others {
                // A transferred sub-agent sees only the user's turns and its own, so it
                // never sees responses whose calls another agent made.
                OtherAgents::Exclude if other_agent => continue,
                OtherAgents::AsContext if other_agent => {
                    match adk_core::history::other_agent_context(&event.author, content) {
                        Some(context) => context,
                        None => continue,
                    }
                }
                OtherAgents::Exclude | OtherAgents::AsContext | OtherAgents::AsOwnTurns => {
                    let mut mapped_content = content.clone();
                    mapped_content.role = match (event.author.as_str(), content.role.as_str()) {
                        ("user", _) => "user",
                        (_, "function" | "tool") => content.role.as_str(),
                        _ => "model",
                    }
                    .to_string();
                    // Native items replay only from a model turn, to the provider and model
                    // whose origin the event recorded; user turns (A2A input included) never
                    // carry them.
                    if compacted_at.is_some_and(|at| event.timestamp < at) {
                        mapped_content.parts.retain(|part| !matches!(part, Part::Thinking { .. }));
                        if mapped_content.parts.is_empty() {
                            continue;
                        }
                    }
                    if mapped_content.role == "model" {
                        adk_core::history::mark_origin(
                            &mut mapped_content,
                            adk_core::history::ProviderOrigin::of_response(
                                event.llm_response.provider_metadata.as_ref(),
                            )
                            .as_ref(),
                        );
                    } else {
                        adk_core::history::strip_native(&mut mapped_content);
                    }
                    mapped_content
                }
            };
            history.push(HistoryContent {
                content: mapped_content,
                invocation_id: Some(event.invocation_id.clone()),
            });
        }

        let long_running = long_running_call_ids(&events);
        close_interrupted_tool_calls(answer_resumed_calls(history, &long_running))
    }
}

/// The ids of the calls `events` mark long-running. An agent lists a long-running call in
/// [`Event::long_running_tool_ids`] by its id or, as `LlmAgent` does, by its tool's name.
fn long_running_call_ids(events: &[Event]) -> std::collections::HashSet<String> {
    let mut ids = std::collections::HashSet::new();
    for event in events.iter().filter(|event| !event.long_running_tool_ids.is_empty()) {
        for part in event.llm_response.content.iter().flat_map(|content| &content.parts) {
            if let Part::FunctionCall { name, id: Some(id), .. } = part
                && event.long_running_tool_ids.iter().any(|listed| listed == id || listed == name)
            {
                ids.insert(id.clone());
            }
        }
    }
    ids
}

/// How a history view presents events other agents authored.
#[derive(Clone, Copy)]
enum OtherAgents {
    /// Leave them out.
    Exclude,
    /// Render them as user-role context.
    AsContext,
    /// Keep them as model turns, as an unscoped view always has.
    AsOwnTurns,
}

struct HistoryContent {
    content: Content,
    invocation_id: Option<String>,
}

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct PartLocation {
    content: usize,
    part: usize,
}

struct PendingFunctionCall {
    location: PartLocation,
    id: Option<String>,
    name: String,
    user_turn: usize,
    invocation_id: Option<String>,
}

/// A call whose current answer is a confirmation-pending response.
struct HeldAnswer {
    /// Where the pending response sits in the source history.
    response: PartLocation,
    id: Option<String>,
    name: String,
}

/// Makes persisted conversation history valid for the next model turn without
/// rewriting the source events.
///
/// A cancelled run persists an outcome-unknown response for each call still in
/// flight, but a crash can leave a model function call persisted without its
/// tool response. Responses from overlapping runs may also be persisted after a
/// later user message, so known responses are paired first. An unmatched call is
/// closed only when a later user turn exists and has no durable response in the
/// retained history. Such calls are omitted from the model projection rather
/// than assigned a result that did not occur.
///
/// A function response whose call is not in the retained history is omitted: a
/// `history_max_events` window or a compaction may have cut the call away, and providers
/// reject a response without its call.
///
/// A call held for confirmation is answered with a confirmation-pending response,
/// and a later run that resumes the call persists its real response. The later
/// response supersedes the pending one in place, so every call keeps exactly one
/// response and providers that reject duplicates accept the history.
fn close_interrupted_tool_calls(history: Vec<HistoryContent>) -> Vec<Content> {
    let mut pending = Vec::<PendingFunctionCall>::new();
    let mut removed_parts = std::collections::HashSet::<PartLocation>::new();
    let mut responses_after = HashMap::<usize, Vec<(usize, String, PartLocation, Part)>>::new();
    let mut held_answers = Vec::<HeldAnswer>::new();
    let mut superseded = HashMap::<PartLocation, Part>::new();
    let mut user_turn = 0;

    // Reconcile against the complete retained history first. Concurrent runs can
    // persist a response after another run's user event, and that response still
    // completes the original call.
    for (content_index, history_content) in history.iter().enumerate() {
        let content = &history_content.content;
        for (part_index, part) in content.parts.iter().enumerate() {
            match part {
                Part::FunctionCall { name, id, .. } => {
                    pending.push(PendingFunctionCall {
                        location: PartLocation { content: content_index, part: part_index },
                        id: id.clone(),
                        name: name.clone(),
                        user_turn,
                        invocation_id: history_content.invocation_id.clone(),
                    });
                }
                Part::FunctionResponse { function_response, id, .. } => {
                    // Idless responses prefer their own invocation. Fall back
                    // by name only when provenance is missing and unambiguous.
                    let matching_index = match id.as_deref() {
                        Some(response_id) => {
                            pending.iter().position(|call| call.id.as_deref() == Some(response_id))
                        }
                        None => pending
                            .iter()
                            .position(|call| {
                                call.name == function_response.name
                                    && history_content.invocation_id.is_some()
                                    && call.invocation_id.as_deref()
                                        == history_content.invocation_id.as_deref()
                            })
                            .or_else(|| {
                                let mut same_name =
                                    pending.iter().enumerate().filter(|(_, call)| {
                                        call.name == function_response.name
                                            && (call.invocation_id.is_none()
                                                || history_content.invocation_id.is_none())
                                    });
                                let first = same_name.next().map(|(index, _)| index);
                                match (first, same_name.next()) {
                                    (Some(index), None) => Some(index),
                                    _ => None,
                                }
                            }),
                    };
                    let location = PartLocation { content: content_index, part: part_index };
                    if let Some(index) = matching_index {
                        let call = pending.remove(index);
                        if adk_core::is_confirmation_pending(&function_response.response) {
                            held_answers.push(HeldAnswer {
                                response: location,
                                id: id.clone(),
                                name: function_response.name.clone(),
                            });
                        }
                        if call.user_turn < user_turn {
                            removed_parts.insert(location);
                            let mut insertion_index = call.location.content;
                            while let Some(next) = history.get(insertion_index + 1) {
                                if next.content.parts.is_empty()
                                    || !next
                                        .content
                                        .parts
                                        .iter()
                                        .all(|part| matches!(part, Part::FunctionResponse { .. }))
                                {
                                    break;
                                }
                                insertion_index += 1;
                            }
                            responses_after.entry(insertion_index).or_default().push((
                                call.location.part,
                                content.role.clone(),
                                location,
                                part.clone(),
                            ));
                        }
                    } else if let Some(index) = held_answers.iter().rposition(|held| match id {
                        Some(response_id) => held.id.as_deref() == Some(response_id.as_str()),
                        None => held.id.is_none() && held.name == function_response.name,
                    }) {
                        // The resumed call's response takes the pending response's place.
                        removed_parts.insert(location);
                        superseded.insert(held_answers[index].response, part.clone());
                        if !adk_core::is_confirmation_pending(&function_response.response) {
                            held_answers.remove(index);
                        }
                    } else {
                        // A response whose call is not in the retained history — cut by a
                        // history window or a compaction, or answered twice — is rejected by
                        // every provider, so it is left out.
                        tracing::debug!(
                            function.name = %function_response.name,
                            "dropping a function response that answers no retained call"
                        );
                        removed_parts.insert(location);
                    }
                }
                _ => {}
            }
        }
        if content.role == "user"
            && content.parts.iter().any(|part| !matches!(part, Part::FunctionResponse { .. }))
        {
            user_turn += 1;
        }
    }

    for call in pending {
        if call.user_turn == user_turn {
            continue;
        }
        removed_parts.insert(call.location);
    }

    let mut normalized = Vec::with_capacity(history.len());
    for (content_index, history_content) in history.into_iter().enumerate() {
        let mut content = history_content.content;
        content.parts = content
            .parts
            .into_iter()
            .enumerate()
            .filter_map(|(part_index, part)| {
                let location = PartLocation { content: content_index, part: part_index };
                if removed_parts.contains(&location) {
                    return None;
                }
                Some(superseded.remove(&location).unwrap_or(part))
            })
            .collect();
        if !content.parts.is_empty() {
            normalized.push(content);
        }
        if let Some(mut responses) = responses_after.remove(&content_index) {
            responses.sort_by_key(|(call_part, _, _, _)| *call_part);
            normalized.extend(responses.into_iter().map(|(_, role, location, response)| {
                let response = superseded.remove(&location).unwrap_or(response);
                Content { role, parts: vec![response] }
            }));
        }
    }

    normalized
}

/// Rearranges a history whose newest turn answers long-running calls after something else
/// followed them, the way a caller resumes such a call: the call's interim response and
/// the model's reply to it sit between the call and the caller's answer.
///
/// The history then ends on the turn with the calls and one response per call, the
/// newest; what came between is left out, so the model answers the caller's result.
/// Without this, the caller's answer reads as a second response to its call, which every
/// provider rejects, and [`close_interrupted_tool_calls`] drops it. ADK Python and ADK Go
/// rearrange the same way (`_rearrange_events_for_latest_function_response`).
///
/// Only calls in `long_running` are answered this way: a second response to an ordinary
/// call is still left out, and an ordinary late response still keeps the turns around it.
/// The history is also returned unchanged when its newest turn is not only function
/// responses with ids, when those responses follow their calls directly, or when they
/// answer calls from more than one turn.
fn answer_resumed_calls(
    mut history: Vec<HistoryContent>,
    long_running: &std::collections::HashSet<String>,
) -> Vec<HistoryContent> {
    let Some(newest) = history.len().checked_sub(1) else { return history };
    let mut answered = std::collections::HashSet::new();
    for part in &history[newest].content.parts {
        match part {
            Part::FunctionResponse { id: Some(id), .. } => {
                answered.insert(id.clone());
            }
            _ => return history,
        }
    }
    if answered.is_empty() || !answered.iter().all(|id| long_running.contains(id)) {
        return history;
    }

    let Some(call_turn) = history[..newest].iter().rposition(|entry| {
        entry.content.parts.iter().any(
            |part| matches!(part, Part::FunctionCall { id: Some(id), .. } if answered.contains(id)),
        )
    }) else {
        return history;
    };
    let call_ids: Vec<String> = history[call_turn]
        .content
        .parts
        .iter()
        .filter_map(|part| match part {
            Part::FunctionCall { id: Some(id), .. } => Some(id.clone()),
            _ => None,
        })
        .collect();
    if !answered.iter().all(|id| call_ids.contains(id)) {
        return history;
    }

    // Responses to the turn's other calls may sit in between, as parallel calls answer
    // one at a time. Anything else, or an earlier response to a call answered now, means
    // the run moved on before this answer came.
    let moved_on = history[call_turn + 1..newest]
        .iter()
        .flat_map(|entry| &entry.content.parts)
        .any(|part| match part {
            Part::FunctionResponse { id: Some(id), .. } => {
                answered.contains(id) || !call_ids.contains(id)
            }
            _ => true,
        });
    if !moved_on {
        return history;
    }

    // One response per call, the newest, in the order of the calls.
    let mut responses: Vec<Option<Part>> = vec![None; call_ids.len()];
    for part in history[call_turn + 1..].iter().flat_map(|entry| &entry.content.parts) {
        if let Part::FunctionResponse { id: Some(id), .. } = part
            && let Some(position) = call_ids.iter().position(|call_id| call_id == id)
        {
            responses[position] = Some(part.clone());
        }
    }
    let answer = history.swap_remove(newest);
    history.truncate(call_turn + 1);
    // A tool-result turn, whoever sent the result: model clients carry function responses
    // in the `function` role, and a user turn holds only the person's input.
    history.push(HistoryContent {
        content: Content {
            role: "function".to_string(),
            parts: responses.into_iter().flatten().collect(),
        },
        invocation_id: answer.invocation_id,
    });
    history
}

impl adk_core::Session for MutableSession {
    fn id(&self) -> &str {
        &self.id
    }

    fn app_name(&self) -> &str {
        &self.app_name
    }

    fn user_id(&self) -> &str {
        &self.user_id
    }

    fn state(&self) -> &dyn adk_core::State {
        self
    }

    fn conversation_history(&self) -> Vec<adk_core::Content> {
        self.conversation_history_for_agent_impl(None, "")
    }

    fn conversation_history_for_agent(&self, agent_name: &str) -> Vec<adk_core::Content> {
        self.conversation_history_for_agent_impl(Some(agent_name), "")
    }

    fn conversation_history_scoped(
        &self,
        agent_name: Option<&str>,
        branch: &str,
    ) -> Vec<adk_core::Content> {
        self.conversation_history_for_agent_impl(agent_name, branch)
    }

    fn conversation_history_with_context(
        &self,
        agent_name: &str,
        branch: &str,
    ) -> Vec<adk_core::Content> {
        self.project_history(Some(agent_name), OtherAgents::AsContext, branch)
    }

    fn records_invocation_events(&self) -> bool {
        true
    }

    fn held_tool_calls(&self, agent_name: &str, branch: &str) -> Vec<adk_core::HeldToolCall> {
        let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
        adk_core::held_tool_calls(&events, agent_name, branch)
    }

    fn workflow_resume_positions(
        &self,
        workflow: &str,
        branch: &str,
    ) -> Vec<adk_core::WorkflowPosition> {
        let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
        adk_core::workflow_resume_positions(&events, workflow, branch)
    }
}

impl adk_core::State for MutableSession {
    fn get(&self, key: &str) -> Option<serde_json::Value> {
        let state = self.state.read().unwrap_or_else(PoisonError::into_inner);
        state.get(key).cloned()
    }

    fn set(&mut self, key: String, value: serde_json::Value) {
        if let Err(msg) = adk_core::validate_state_key(&key) {
            tracing::warn!(key = %key, "rejecting invalid state key: {msg}");
            return;
        }
        let mut state = self.state.write().unwrap_or_else(PoisonError::into_inner);
        state.insert(key, value);
    }

    fn all(&self) -> HashMap<String, serde_json::Value> {
        let state = self.state.read().unwrap_or_else(PoisonError::into_inner);
        state.clone()
    }
}

/// Runtime context for a single agent invocation.
///
/// Holds the agent, session, identity, and optional services (artifacts, memory,
/// secrets) needed during execution. Created by the [`Runner`](crate::Runner) for
/// each `run()` call.
pub struct InvocationContext {
    identity: ExecutionIdentity,
    agent: Arc<dyn Agent>,
    user_content: Content,
    artifacts: Option<Arc<dyn Artifacts>>,
    memory: Option<Arc<dyn Memory>>,
    run_config: RunConfig,
    ended: Arc<AtomicBool>,
    /// Mutable session that allows state to be updated during execution.
    /// This is shared across all agents in a workflow, enabling state
    /// propagation between sequential/parallel agents.
    session: Arc<MutableSession>,
    /// Optional request context from the server's auth middleware bridge.
    /// When present, `user_id()` returns `request_context.user_id` and
    /// `user_scopes()` returns `request_context.scopes`.
    request_context: Option<RequestContext>,
    /// Optional shared state for parallel agent coordination.
    shared_state: Option<Arc<adk_core::SharedState>>,
    /// Optional secret service for retrieving secrets at runtime.
    /// When present, `get_secret()` delegates to this service.
    secret_service: Option<Arc<dyn SecretService>>,
    /// Optional cooperative cancellation token.
    ///
    /// When present, `is_cancelled()` reflects this token, letting agents and
    /// tools detect external cancellation (`Runner::interrupt()` or
    /// `RunConfig::cancellation_token`) during long-running work.
    cancellation_token: Option<tokio_util::sync::CancellationToken>,
    /// Stable root invocation for a multi-hop orchestration tree.
    orchestration_root_invocation_id: String,
    /// The run's queue of steering messages, shared by every agent the run hands control to.
    steering_inbox: Option<adk_core::SteeringInbox>,
}

impl InvocationContext {
    /// Create a new invocation context from validated typed identifiers.
    pub fn new_typed(
        invocation_id: String,
        agent: Arc<dyn Agent>,
        user_id: UserId,
        app_name: AppName,
        session_id: SessionId,
        user_content: Content,
        session: Arc<dyn AdkSession>,
    ) -> adk_core::Result<Self> {
        let orchestration_root_invocation_id = invocation_id.clone();
        let identity = ExecutionIdentity {
            adk: AdkIdentity { app_name, user_id, session_id },
            invocation_id: InvocationId::try_from(invocation_id)?,
            branch: String::new(),
            agent_name: agent.name().to_string(),
        };
        Ok(Self {
            identity,
            agent,
            user_content,
            artifacts: None,
            memory: None,
            run_config: RunConfig::default(),
            ended: Arc::new(AtomicBool::new(false)),
            session: Arc::new(MutableSession::new(session)),
            request_context: None,
            shared_state: None,
            secret_service: None,
            cancellation_token: None,
            orchestration_root_invocation_id,
            steering_inbox: None,
        })
    }

    /// Create a new invocation context from raw string identifiers.
    ///
    /// Validates and converts the string identifiers into typed wrappers.
    /// Prefer [`new_typed`](Self::new_typed) when you already have validated types.
    pub fn new(
        invocation_id: String,
        agent: Arc<dyn Agent>,
        user_id: String,
        app_name: String,
        session_id: String,
        user_content: Content,
        session: Arc<dyn AdkSession>,
    ) -> adk_core::Result<Self> {
        Self::new_typed(
            invocation_id,
            agent,
            UserId::try_from(user_id)?,
            AppName::try_from(app_name)?,
            SessionId::try_from(session_id)?,
            user_content,
            session,
        )
    }

    /// Create an invocation context that reuses an existing mutable session and
    /// validated typed identifiers.
    pub fn with_mutable_session_typed(
        invocation_id: String,
        agent: Arc<dyn Agent>,
        user_id: UserId,
        app_name: AppName,
        session_id: SessionId,
        user_content: Content,
        session: Arc<MutableSession>,
    ) -> adk_core::Result<Self> {
        let orchestration_root_invocation_id = invocation_id.clone();
        let identity = ExecutionIdentity {
            adk: AdkIdentity { app_name, user_id, session_id },
            invocation_id: InvocationId::try_from(invocation_id)?,
            branch: String::new(),
            agent_name: agent.name().to_string(),
        };
        Ok(Self {
            identity,
            agent,
            user_content,
            artifacts: None,
            memory: None,
            run_config: RunConfig::default(),
            ended: Arc::new(AtomicBool::new(false)),
            session,
            request_context: None,
            shared_state: None,
            secret_service: None,
            cancellation_token: None,
            orchestration_root_invocation_id,
            steering_inbox: None,
        })
    }

    /// Create an InvocationContext with an existing MutableSession.
    /// This allows sharing the same mutable session across multiple contexts
    /// (e.g., for agent transfers).
    pub fn with_mutable_session(
        invocation_id: String,
        agent: Arc<dyn Agent>,
        user_id: String,
        app_name: String,
        session_id: String,
        user_content: Content,
        session: Arc<MutableSession>,
    ) -> adk_core::Result<Self> {
        Self::with_mutable_session_typed(
            invocation_id,
            agent,
            UserId::try_from(user_id)?,
            AppName::try_from(app_name)?,
            SessionId::try_from(session_id)?,
            user_content,
            session,
        )
    }

    /// Set the event branch identifier for this context.
    pub fn with_branch(mut self, branch: String) -> Self {
        self.identity.branch = branch;
        self
    }

    /// Attach an artifact storage service to this context.
    pub fn with_artifacts(mut self, artifacts: Arc<dyn Artifacts>) -> Self {
        self.artifacts = Some(artifacts);
        self
    }

    /// Attach a memory service for RAG/semantic search.
    pub fn with_memory(mut self, memory: Arc<dyn Memory>) -> Self {
        self.memory = Some(memory);
        self
    }

    /// Set the run configuration (streaming mode, history limits, etc.).
    pub fn with_run_config(mut self, config: RunConfig) -> Self {
        self.run_config = config;
        self
    }

    /// Set the request context from the server's auth middleware bridge.
    ///
    /// When set, `user_id()` returns `request_context.user_id` (overriding
    /// the session-scoped identity), and `user_scopes()` returns
    /// `request_context.scopes`. This is the explicit authenticated user
    /// override — `RequestContext` remains separate from `ExecutionIdentity`
    /// and `AdkIdentity` (it does not carry session or invocation IDs).
    pub fn with_request_context(mut self, ctx: RequestContext) -> Self {
        self.request_context = Some(ctx);
        self
    }

    /// Set the shared state for parallel agent coordination.
    pub fn with_shared_state(mut self, shared: Arc<adk_core::SharedState>) -> Self {
        self.shared_state = Some(shared);
        self
    }

    /// Set the secret service for runtime secret retrieval.
    ///
    /// When configured, tools can call `ctx.get_secret("name")` to retrieve
    /// secrets from the configured provider (e.g., AWS Secrets Manager,
    /// Azure Key Vault, GCP Secret Manager).
    pub fn with_secret_service(mut self, service: Arc<dyn SecretService>) -> Self {
        self.secret_service = Some(service);
        self
    }

    /// Attach a cooperative cancellation token.
    ///
    /// When set, [`is_cancelled`](adk_core::InvocationContext::is_cancelled)
    /// reflects this token, so agents and tools can detect external
    /// cancellation during long-running work.
    pub fn with_cancellation_token(mut self, token: tokio_util::sync::CancellationToken) -> Self {
        self.cancellation_token = Some(token);
        self
    }

    /// Preserve the stable orchestration root across a Runner handoff.
    pub fn with_orchestration_root_invocation_id(mut self, invocation_id: String) -> Self {
        self.orchestration_root_invocation_id = invocation_id;
        self
    }

    /// Attach the run's steering inbox, which
    /// [`steering_inbox`](adk_core::InvocationContext::steering_inbox) returns.
    ///
    /// The [`Runner`](crate::Runner) installs one per run, so every agent the run hands
    /// control to takes the messages [`Runner::steer`](crate::Runner::steer) queues.
    pub fn with_steering_inbox(mut self, inbox: adk_core::SteeringInbox) -> Self {
        self.steering_inbox = Some(inbox);
        self
    }

    /// Get a reference to the mutable session.
    /// This allows the Runner to apply state deltas when events are processed.
    pub fn mutable_session(&self) -> &Arc<MutableSession> {
        &self.session
    }

    /// A copy of this context, sharing its session and services, whose user message is
    /// `content`.
    pub(crate) fn with_user_content(&self, content: Content) -> Self {
        Self {
            identity: self.identity.clone(),
            agent: self.agent.clone(),
            user_content: content,
            artifacts: self.artifacts.clone(),
            memory: self.memory.clone(),
            run_config: self.run_config.clone(),
            ended: self.ended.clone(),
            session: self.session.clone(),
            request_context: self.request_context.clone(),
            shared_state: self.shared_state.clone(),
            secret_service: self.secret_service.clone(),
            cancellation_token: self.cancellation_token.clone(),
            orchestration_root_invocation_id: self.orchestration_root_invocation_id.clone(),
            steering_inbox: self.steering_inbox.clone(),
        }
    }
}

#[async_trait]
impl ReadonlyContext for InvocationContext {
    fn invocation_id(&self) -> &str {
        self.identity.invocation_id.as_ref()
    }

    fn agent_name(&self) -> &str {
        self.agent.name()
    }

    fn user_id(&self) -> &str {
        // Explicit authenticated user override: when a RequestContext is
        // present (set via with_request_context from the auth middleware
        // bridge), the authenticated user_id takes precedence over the
        // session-scoped identity. This keeps auth binding explicit and
        // ensures the runtime reflects the verified caller identity.
        self.request_context.as_ref().map_or(self.identity.adk.user_id.as_ref(), |rc| &rc.user_id)
    }

    fn app_name(&self) -> &str {
        self.identity.adk.app_name.as_ref()
    }

    fn session_id(&self) -> &str {
        self.identity.adk.session_id.as_ref()
    }

    fn branch(&self) -> &str {
        &self.identity.branch
    }

    fn user_content(&self) -> &Content {
        &self.user_content
    }

    fn acting_context(&self) -> adk_core::ActingContext {
        self.run_config.acting_context_for(self.app_name(), self.agent_name(), self.user_id())
    }

    /// `true` when the run carries a [`RequestContext`] (spec 3.1 §10 F5) and its subject
    /// is not a [`Visitor`](adk_core::SubjectKind::Visitor), whom no credential identifies.
    fn is_authenticated(&self) -> bool {
        self.request_context.is_some()
            && self.run_config.acting.subject_kind != adk_core::SubjectKind::Visitor
    }

    fn state(&self) -> Option<&dyn adk_core::State> {
        // Expose the runner's mutable session view so a toolset can observe a
        // state delta emitted by an earlier tool result on the next model turn.
        Some(adk_core::Session::state(self.session.as_ref()))
    }
}

#[async_trait]
impl CallbackContext for InvocationContext {
    fn artifacts(&self) -> Option<Arc<dyn Artifacts>> {
        self.artifacts.clone()
    }

    fn shared_state(&self) -> Option<Arc<adk_core::SharedState>> {
        self.shared_state.clone()
    }
}

#[async_trait]
impl InvocationContextTrait for InvocationContext {
    fn agent(&self) -> Arc<dyn Agent> {
        self.agent.clone()
    }

    fn memory(&self) -> Option<Arc<dyn Memory>> {
        self.memory.clone()
    }

    fn session(&self) -> &dyn adk_core::Session {
        self.session.as_ref()
    }

    fn run_config(&self) -> &RunConfig {
        &self.run_config
    }

    fn end_invocation(&self) {
        self.ended.store(true, std::sync::atomic::Ordering::SeqCst);
    }

    fn ended(&self) -> bool {
        self.ended.load(std::sync::atomic::Ordering::SeqCst)
    }

    fn is_cancelled(&self) -> bool {
        self.cancellation_token
            .as_ref()
            .is_some_and(tokio_util::sync::CancellationToken::is_cancelled)
    }

    fn user_scopes(&self) -> Vec<String> {
        self.request_context.as_ref().map_or_else(Vec::new, |rc| rc.scopes.clone())
    }

    fn request_metadata(&self) -> HashMap<String, serde_json::Value> {
        // The authenticated request context's entries are written last, so an
        // unauthenticated entry never replaces one of them.
        self.run_config
            .request_metadata
            .iter()
            .chain(self.request_context.iter().flat_map(|rc| rc.metadata.iter()))
            .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
            .collect()
    }

    fn orchestration_root_invocation_id(&self) -> &str {
        &self.orchestration_root_invocation_id
    }

    fn steering_inbox(&self) -> Option<adk_core::SteeringInbox> {
        self.steering_inbox.clone()
    }

    async fn get_secret(&self, name: &str) -> adk_core::Result<Option<String>> {
        let request = adk_core::SecretRequest::new(name)
            .with_identity(self.app_name(), self.user_id(), self.session_id())
            .with_invocation_id(self.invocation_id());
        self.get_secret_for(&request).await
    }

    async fn get_secret_for(
        &self,
        request: &adk_core::SecretRequest,
    ) -> adk_core::Result<Option<String>> {
        match &self.secret_service {
            Some(service) => service.get_secret_for(request).await.map(Some),
            None => Ok(None),
        }
    }
}

#[cfg(test)]
mod poisoned_lock_tests {
    use super::*;
    use adk_session::{CreateRequest, InMemorySessionService, SessionService};

    #[tokio::test]
    async fn a_poisoned_lock_keeps_the_history_and_state() {
        let service = InMemorySessionService::new();
        let stored = service
            .create(CreateRequest {
                app_name: "app".to_string(),
                user_id: "user".to_string(),
                session_id: Some("session".to_string()),
                state: HashMap::new(),
            })
            .await
            .unwrap();
        let session = Arc::new(MutableSession::new(Arc::from(stored)));
        let mut event = Event::new("inv-1");
        event.author = "user".to_string();
        event.llm_response.content = Some(Content::new("user").with_text("hello"));
        session.append_event(event);
        session.apply_state_delta(&HashMap::from([(
            "topic".to_string(),
            serde_json::json!("billing"),
        )]));

        // A thread that panics while it holds the write guards poisons both locks.
        let holder = Arc::clone(&session);
        let _ = std::thread::spawn(move || {
            let _events = holder.events.write().unwrap();
            let _state = holder.state.write().unwrap();
            panic!("poison the session locks");
        })
        .join();
        assert!(session.events.is_poisoned() && session.state.is_poisoned());

        let history = adk_core::Session::conversation_history(session.as_ref());
        let texts: Vec<_> = history
            .iter()
            .map(|content| {
                (
                    content.role.as_str(),
                    content.parts.iter().filter_map(Part::text).collect::<String>(),
                )
            })
            .collect();
        assert_eq!(texts, [("user", "hello".to_string())]);
        assert_eq!(
            adk_core::State::get(session.as_ref(), "topic"),
            Some(serde_json::json!("billing"))
        );
        let mut later = Event::new("inv-1");
        later.author = "agent".to_string();
        later.llm_response.content = Some(Content::new("model").with_text("hi"));
        session.append_event(later);
        assert_eq!(session.events_len(), 2, "a write after the panic is kept");
    }
}

#[cfg(test)]
mod snapshot_tests {
    use super::*;
    use adk_session::{Events, State};
    use std::sync::atomic::{AtomicUsize, Ordering};

    /// A loaded session that counts how its history leaves it.
    struct CountingSession {
        events: Vec<Event>,
        state: HashMap<String, serde_json::Value>,
        copies: Arc<AtomicUsize>,
        takes: Arc<AtomicUsize>,
    }

    impl CountingSession {
        fn new(copies: &Arc<AtomicUsize>, takes: &Arc<AtomicUsize>) -> Self {
            let events = ["first", "second"]
                .into_iter()
                .map(|text| {
                    let mut event = Event::new("inv-1");
                    event.author = "user".to_string();
                    event.llm_response.content = Some(Content::new("user").with_text(text));
                    event
                })
                .collect();
            Self {
                events,
                state: HashMap::from([("topic".to_string(), serde_json::json!("billing"))]),
                copies: Arc::clone(copies),
                takes: Arc::clone(takes),
            }
        }
    }

    impl Events for CountingSession {
        fn all(&self) -> Vec<Event> {
            self.copies.fetch_add(1, Ordering::SeqCst);
            self.events.clone()
        }
        fn len(&self) -> usize {
            self.events.len()
        }
        fn at(&self, index: usize) -> Option<&Event> {
            self.events.get(index)
        }
    }

    impl State for CountingSession {
        fn get(&self, key: &str) -> Option<serde_json::Value> {
            self.state.get(key).cloned()
        }
        fn set(&mut self, key: String, value: serde_json::Value) {
            self.state.insert(key, value);
        }
        fn all(&self) -> HashMap<String, serde_json::Value> {
            self.state.clone()
        }
    }

    impl AdkSession for CountingSession {
        fn id(&self) -> &str {
            "session"
        }
        fn app_name(&self) -> &str {
            "app"
        }
        fn user_id(&self) -> &str {
            "user"
        }
        fn state(&self) -> &dyn State {
            self
        }
        fn events(&self) -> &dyn Events {
            self
        }
        fn last_update_time(&self) -> chrono::DateTime<chrono::Utc> {
            chrono::Utc::now()
        }
        fn take_events(&mut self) -> Vec<Event> {
            self.takes.fetch_add(1, Ordering::SeqCst);
            std::mem::take(&mut self.events)
        }
    }

    fn texts(session: &MutableSession) -> Vec<String> {
        session
            .events_snapshot()
            .iter()
            .flat_map(|event| event.llm_response.content.iter().flat_map(|c| c.parts.iter()))
            .filter_map(|part| part.text().map(str::to_string))
            .collect()
    }

    #[test]
    fn a_session_held_once_moves_its_history() {
        let (copies, takes) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
        let session = MutableSession::new(Arc::new(CountingSession::new(&copies, &takes)));

        assert_eq!((copies.load(Ordering::SeqCst), takes.load(Ordering::SeqCst)), (0, 1));
        assert_eq!(texts(&session), ["first", "second"]);
        let identity = (
            adk_core::Session::id(&session),
            adk_core::Session::app_name(&session),
            adk_core::Session::user_id(&session),
        );
        assert_eq!(identity, ("session", "app", "user"));
        assert_eq!(adk_core::State::get(&session, "topic"), Some(serde_json::json!("billing")));
    }

    #[test]
    fn a_shared_session_keeps_its_history() {
        let (copies, takes) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
        let shared: Arc<dyn AdkSession> = Arc::new(CountingSession::new(&copies, &takes));
        let session = MutableSession::new(Arc::clone(&shared));

        assert_eq!((copies.load(Ordering::SeqCst), takes.load(Ordering::SeqCst)), (1, 0));
        assert_eq!(texts(&session), ["first", "second"]);
        assert_eq!(shared.events().len(), 2, "the caller's handle keeps its events");
    }
}