Skip to main content

adk_runner/
context.rs

1use adk_core::{
2    AdkIdentity, Agent, AppName, Artifacts, CallbackContext, Content, Event, ExecutionIdentity,
3    InvocationContext as InvocationContextTrait, InvocationId, Memory, Part, ReadonlyContext,
4    RequestContext, RunConfig, SecretService, SessionId, UserId,
5};
6use adk_session::Session as AdkSession;
7use async_trait::async_trait;
8use std::collections::HashMap;
9use std::sync::{Arc, PoisonError, RwLock, atomic::AtomicBool};
10
11/// MutableSession wraps a session with shared mutable state.
12///
13/// This mirrors ADK-Go's MutableSession pattern where state changes from
14/// events are immediately visible to all agents sharing the same context.
15/// This is critical for SequentialAgent/LoopAgent patterns where downstream
16/// agents need to read state set by upstream agents via output_key.
17///
18/// A panic while another thread holds one of its locks poisons the lock. Every write is a
19/// single insert, push or assignment, so the data stays whole, and reads and writes go on
20/// using it rather than seeing an empty history or dropping events.
21pub struct MutableSession {
22    /// The session's ID, app name and user ID, taken from the snapshot it was built from.
23    id: String,
24    app_name: String,
25    user_id: String,
26    /// Shared mutable state - updated when events are processed
27    /// This is the key difference from the old SessionAdapter which used immutable snapshots
28    state: Arc<RwLock<HashMap<String, serde_json::Value>>>,
29    /// Accumulated events during this invocation (uses adk_core::Event which is re-exported by adk_session)
30    events: Arc<RwLock<Vec<Event>>>,
31}
32
33impl MutableSession {
34    /// Create a new MutableSession from a session snapshot.
35    ///
36    /// The state is copied from the session and becomes mutable. The events are moved out of
37    /// the snapshot ([`Session::take_events`](AdkSession::take_events)) when this is its only
38    /// handle, as it is for the session the runner loads, and copied otherwise. The snapshot
39    /// is not kept.
40    pub fn new(mut session: Arc<dyn AdkSession>) -> Self {
41        let initial_events = match Arc::get_mut(&mut session) {
42            Some(owned) => owned.take_events(),
43            None => session.events().all(),
44        };
45
46        Self {
47            id: session.id().to_string(),
48            app_name: session.app_name().to_string(),
49            user_id: session.user_id().to_string(),
50            state: Arc::new(RwLock::new(session.state().all())),
51            events: Arc::new(RwLock::new(initial_events)),
52        }
53    }
54
55    /// Apply state delta from an event to the mutable state.
56    /// This is called by the Runner when events are yielded.
57    ///
58    /// Every key applies, `temp:` keys included, so a later tool, agent or `{temp:key}`
59    /// instruction in the same invocation reads them. Session services drop `temp:` keys when
60    /// they persist an event.
61    pub fn apply_state_delta(&self, delta: &HashMap<String, serde_json::Value>) {
62        if delta.is_empty() {
63            return;
64        }
65
66        let mut state = self.state.write().unwrap_or_else(PoisonError::into_inner);
67        // `temp:` keys stay for the rest of the invocation; the session service drops them
68        // when it persists the event, so they never outlive it.
69        for (key, value) in delta {
70            state.insert(key.clone(), value.clone());
71        }
72    }
73
74    /// Append an event to the session's event list.
75    /// This keeps the in-memory view consistent.
76    pub fn append_event(&self, event: Event) {
77        let mut events = self.events.write().unwrap_or_else(PoisonError::into_inner);
78        events.push(event);
79    }
80
81    /// Get a snapshot of all events in the session.
82    /// Used by the runner for compaction decisions.
83    pub fn events_snapshot(&self) -> Vec<Event> {
84        let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
85        events.clone()
86    }
87
88    /// Replace all events with a new list (used by intra-invocation compaction).
89    pub fn replace_events(&self, new_events: Vec<Event>) {
90        let mut events = self.events.write().unwrap_or_else(PoisonError::into_inner);
91        *events = new_events;
92    }
93
94    /// Runs `read` over the events without copying them.
95    pub(crate) fn read_events<R>(&self, read: impl FnOnce(&[Event]) -> R) -> R {
96        let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
97        read(&events)
98    }
99
100    /// Return the number of accumulated events without cloning the full list.
101    pub fn events_len(&self) -> usize {
102        let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
103        events.len()
104    }
105
106    /// Build conversation history, optionally filtered for a specific agent.
107    ///
108    /// When `agent_name` is `Some`, events authored by other agents (not "user",
109    /// not the named agent, and not function/tool responses) are excluded. This
110    /// prevents a transferred sub-agent from seeing the parent's tool calls
111    /// mapped as "model" role, which would cause the LLM to think work is
112    /// already done.
113    ///
114    /// When `agent_name` is `None`, all events are included (backward-compatible).
115    ///
116    /// A system notice ([`system_notice_event`](adk_core::history::system_notice_event)) is
117    /// kept as a user-role turn either way.
118    ///
119    /// `branch` additionally scopes history to a conversation branch: an event is
120    /// kept when its branch equals `branch` or is an ancestor of it, so
121    /// concurrent `ParallelAgent` branches do not read each other's output. An
122    /// empty `branch`, or an event without one, matches everything. Events a tool
123    /// published on its own branch below `branch`
124    /// ([`tool_branch`](adk_core::history::tool_branch)) are left out.
125    pub fn conversation_history_for_agent_impl(
126        &self,
127        agent_name: Option<&str>,
128        branch: &str,
129    ) -> Vec<adk_core::Content> {
130        match agent_name {
131            Some(name) => self.project_history(Some(name), OtherAgents::Exclude, branch),
132            None => self.project_history(None, OtherAgents::AsOwnTurns, branch),
133        }
134    }
135
136    fn project_history(
137        &self,
138        agent_name: Option<&str>,
139        others: OtherAgents,
140        branch: &str,
141    ) -> Vec<adk_core::Content> {
142        let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
143        let mut history = Vec::new();
144        let call_ids = adk_core::history::function_call_ids(&events);
145
146        // Find the most recent compaction event — everything before its
147        // end_timestamp has been summarized and should be replaced by the
148        // compacted content.
149        let mut compaction_boundary = None;
150        // Turns the compaction kept were answered with the history before it; a provider binds
151        // thinking to that history, so their thinking is not replayed after the summary, unless
152        // the provider wrote the summary itself and accepts it.
153        let mut compacted_at = None;
154        for event in events.iter().rev() {
155            if let Some(ref compaction) = event.actions.compaction {
156                let mut content = compaction.compacted_content.clone();
157                // A provider's own compaction keeps its signed copy for the provider and model
158                // the runner recorded on the event; any other summary carries no native item.
159                let origin = adk_core::intra_compaction::is_native_compaction(&content)
160                    .then(|| {
161                        adk_core::history::ProviderOrigin::of_response(
162                            event.llm_response.provider_metadata.as_ref(),
163                        )
164                    })
165                    .flatten();
166                match &origin {
167                    Some(origin) => adk_core::history::mark_origin(&mut content, Some(origin)),
168                    None => adk_core::history::strip_native(&mut content),
169                }
170                let keeps_thinking = origin.is_some()
171                    && event
172                        .llm_response
173                        .provider_metadata
174                        .as_ref()
175                        .and_then(|metadata| {
176                            metadata.get(crate::intra_compaction::KEEPS_THINKING_KEY)
177                        })
178                        .and_then(serde_json::Value::as_bool)
179                        == Some(true);
180                if !keeps_thinking {
181                    compacted_at = Some(event.timestamp);
182                }
183                history.push(HistoryContent { content, invocation_id: None });
184                compaction_boundary = Some(compaction.end_timestamp);
185                break;
186            }
187        }
188
189        for event in events.iter() {
190            // Skip the compaction event itself
191            if event.actions.compaction.is_some() {
192                continue;
193            }
194
195            // Streamed deltas are superseded by their terminal event, which carries the
196            // complete response; the persisted session holds only that terminal event.
197            if event.llm_response.partial {
198                continue;
199            }
200
201            // A confirmation interrupt's text is a notice to the caller, not model output; in
202            // the history it would end the conversation on an assistant turn after the call's
203            // response, which providers without assistant prefill reject.
204            if event.actions.tool_confirmation.is_some() {
205                continue;
206            }
207
208            // Skip events that were already compacted
209            if let Some(boundary) = compaction_boundary
210                && event.timestamp <= boundary
211            {
212                continue;
213            }
214
215            // Skip events from sibling branches (and from branches nested below
216            // this one). Ancestor branches stay visible so a sub-agent still sees
217            // the conversation that led to it.
218            if !adk_core::event_belongs_to_branch(branch, &event.branch) {
219                continue;
220            }
221
222            // What a tool published on its own branch is progress for observers; the
223            // caller's model gets the tool's response.
224            if adk_core::history::is_tool_branch_event(branch, &event.branch, &call_ids) {
225                continue;
226            }
227
228            let Some(content) = &event.llm_response.content else {
229                continue;
230            };
231            // The runtime's notice is addressed to every agent: not another agent's context to
232            // quote or leave out, and never a model turn.
233            if adk_core::history::is_system_notice_event(event) {
234                history.push(HistoryContent {
235                    content: content.clone(),
236                    invocation_id: Some(event.invocation_id.clone()),
237                });
238                continue;
239            }
240            let other_agent =
241                agent_name.is_some_and(|name| event.author != "user" && event.author != name);
242            let mapped_content = match others {
243                // A transferred sub-agent sees only the user's turns and its own, so it
244                // never sees responses whose calls another agent made.
245                OtherAgents::Exclude if other_agent => continue,
246                OtherAgents::AsContext if other_agent => {
247                    match adk_core::history::other_agent_context(&event.author, content) {
248                        Some(context) => context,
249                        None => continue,
250                    }
251                }
252                OtherAgents::Exclude | OtherAgents::AsContext | OtherAgents::AsOwnTurns => {
253                    let mut mapped_content = content.clone();
254                    mapped_content.role = match (event.author.as_str(), content.role.as_str()) {
255                        ("user", _) => "user",
256                        (_, "function" | "tool") => content.role.as_str(),
257                        _ => "model",
258                    }
259                    .to_string();
260                    // Native items replay only from a model turn, to the provider and model
261                    // whose origin the event recorded; user turns (A2A input included) never
262                    // carry them.
263                    if compacted_at.is_some_and(|at| event.timestamp < at) {
264                        mapped_content.parts.retain(|part| !matches!(part, Part::Thinking { .. }));
265                        if mapped_content.parts.is_empty() {
266                            continue;
267                        }
268                    }
269                    if mapped_content.role == "model" {
270                        adk_core::history::mark_origin(
271                            &mut mapped_content,
272                            adk_core::history::ProviderOrigin::of_response(
273                                event.llm_response.provider_metadata.as_ref(),
274                            )
275                            .as_ref(),
276                        );
277                    } else {
278                        adk_core::history::strip_native(&mut mapped_content);
279                    }
280                    mapped_content
281                }
282            };
283            history.push(HistoryContent {
284                content: mapped_content,
285                invocation_id: Some(event.invocation_id.clone()),
286            });
287        }
288
289        let long_running = long_running_call_ids(&events);
290        close_interrupted_tool_calls(answer_resumed_calls(history, &long_running))
291    }
292}
293
294/// The ids of the calls `events` mark long-running. An agent lists a long-running call in
295/// [`Event::long_running_tool_ids`] by its id or, as `LlmAgent` does, by its tool's name.
296fn long_running_call_ids(events: &[Event]) -> std::collections::HashSet<String> {
297    let mut ids = std::collections::HashSet::new();
298    for event in events.iter().filter(|event| !event.long_running_tool_ids.is_empty()) {
299        for part in event.llm_response.content.iter().flat_map(|content| &content.parts) {
300            if let Part::FunctionCall { name, id: Some(id), .. } = part
301                && event.long_running_tool_ids.iter().any(|listed| listed == id || listed == name)
302            {
303                ids.insert(id.clone());
304            }
305        }
306    }
307    ids
308}
309
310/// How a history view presents events other agents authored.
311#[derive(Clone, Copy)]
312enum OtherAgents {
313    /// Leave them out.
314    Exclude,
315    /// Render them as user-role context.
316    AsContext,
317    /// Keep them as model turns, as an unscoped view always has.
318    AsOwnTurns,
319}
320
321struct HistoryContent {
322    content: Content,
323    invocation_id: Option<String>,
324}
325
326#[derive(Clone, Copy, PartialEq, Eq, Hash)]
327struct PartLocation {
328    content: usize,
329    part: usize,
330}
331
332struct PendingFunctionCall {
333    location: PartLocation,
334    id: Option<String>,
335    name: String,
336    user_turn: usize,
337    invocation_id: Option<String>,
338}
339
340/// A call whose current answer is a confirmation-pending response.
341struct HeldAnswer {
342    /// Where the pending response sits in the source history.
343    response: PartLocation,
344    id: Option<String>,
345    name: String,
346}
347
348/// Makes persisted conversation history valid for the next model turn without
349/// rewriting the source events.
350///
351/// A cancelled run persists an outcome-unknown response for each call still in
352/// flight, but a crash can leave a model function call persisted without its
353/// tool response. Responses from overlapping runs may also be persisted after a
354/// later user message, so known responses are paired first. An unmatched call is
355/// closed only when a later user turn exists and has no durable response in the
356/// retained history. Such calls are omitted from the model projection rather
357/// than assigned a result that did not occur.
358///
359/// A function response whose call is not in the retained history is omitted: a
360/// `history_max_events` window or a compaction may have cut the call away, and providers
361/// reject a response without its call.
362///
363/// A call held for confirmation is answered with a confirmation-pending response,
364/// and a later run that resumes the call persists its real response. The later
365/// response supersedes the pending one in place, so every call keeps exactly one
366/// response and providers that reject duplicates accept the history.
367fn close_interrupted_tool_calls(history: Vec<HistoryContent>) -> Vec<Content> {
368    let mut pending = Vec::<PendingFunctionCall>::new();
369    let mut removed_parts = std::collections::HashSet::<PartLocation>::new();
370    let mut responses_after = HashMap::<usize, Vec<(usize, String, PartLocation, Part)>>::new();
371    let mut held_answers = Vec::<HeldAnswer>::new();
372    let mut superseded = HashMap::<PartLocation, Part>::new();
373    let mut user_turn = 0;
374
375    // Reconcile against the complete retained history first. Concurrent runs can
376    // persist a response after another run's user event, and that response still
377    // completes the original call.
378    for (content_index, history_content) in history.iter().enumerate() {
379        let content = &history_content.content;
380        for (part_index, part) in content.parts.iter().enumerate() {
381            match part {
382                Part::FunctionCall { name, id, .. } => {
383                    pending.push(PendingFunctionCall {
384                        location: PartLocation { content: content_index, part: part_index },
385                        id: id.clone(),
386                        name: name.clone(),
387                        user_turn,
388                        invocation_id: history_content.invocation_id.clone(),
389                    });
390                }
391                Part::FunctionResponse { function_response, id, .. } => {
392                    // Idless responses prefer their own invocation. Fall back
393                    // by name only when provenance is missing and unambiguous.
394                    let matching_index = match id.as_deref() {
395                        Some(response_id) => {
396                            pending.iter().position(|call| call.id.as_deref() == Some(response_id))
397                        }
398                        None => pending
399                            .iter()
400                            .position(|call| {
401                                call.name == function_response.name
402                                    && history_content.invocation_id.is_some()
403                                    && call.invocation_id.as_deref()
404                                        == history_content.invocation_id.as_deref()
405                            })
406                            .or_else(|| {
407                                let mut same_name =
408                                    pending.iter().enumerate().filter(|(_, call)| {
409                                        call.name == function_response.name
410                                            && (call.invocation_id.is_none()
411                                                || history_content.invocation_id.is_none())
412                                    });
413                                let first = same_name.next().map(|(index, _)| index);
414                                match (first, same_name.next()) {
415                                    (Some(index), None) => Some(index),
416                                    _ => None,
417                                }
418                            }),
419                    };
420                    let location = PartLocation { content: content_index, part: part_index };
421                    if let Some(index) = matching_index {
422                        let call = pending.remove(index);
423                        if adk_core::is_confirmation_pending(&function_response.response) {
424                            held_answers.push(HeldAnswer {
425                                response: location,
426                                id: id.clone(),
427                                name: function_response.name.clone(),
428                            });
429                        }
430                        if call.user_turn < user_turn {
431                            removed_parts.insert(location);
432                            let mut insertion_index = call.location.content;
433                            while let Some(next) = history.get(insertion_index + 1) {
434                                if next.content.parts.is_empty()
435                                    || !next
436                                        .content
437                                        .parts
438                                        .iter()
439                                        .all(|part| matches!(part, Part::FunctionResponse { .. }))
440                                {
441                                    break;
442                                }
443                                insertion_index += 1;
444                            }
445                            responses_after.entry(insertion_index).or_default().push((
446                                call.location.part,
447                                content.role.clone(),
448                                location,
449                                part.clone(),
450                            ));
451                        }
452                    } else if let Some(index) = held_answers.iter().rposition(|held| match id {
453                        Some(response_id) => held.id.as_deref() == Some(response_id.as_str()),
454                        None => held.id.is_none() && held.name == function_response.name,
455                    }) {
456                        // The resumed call's response takes the pending response's place.
457                        removed_parts.insert(location);
458                        superseded.insert(held_answers[index].response, part.clone());
459                        if !adk_core::is_confirmation_pending(&function_response.response) {
460                            held_answers.remove(index);
461                        }
462                    } else {
463                        // A response whose call is not in the retained history — cut by a
464                        // history window or a compaction, or answered twice — is rejected by
465                        // every provider, so it is left out.
466                        tracing::debug!(
467                            function.name = %function_response.name,
468                            "dropping a function response that answers no retained call"
469                        );
470                        removed_parts.insert(location);
471                    }
472                }
473                _ => {}
474            }
475        }
476        if content.role == "user"
477            && content.parts.iter().any(|part| !matches!(part, Part::FunctionResponse { .. }))
478        {
479            user_turn += 1;
480        }
481    }
482
483    for call in pending {
484        if call.user_turn == user_turn {
485            continue;
486        }
487        removed_parts.insert(call.location);
488    }
489
490    let mut normalized = Vec::with_capacity(history.len());
491    for (content_index, history_content) in history.into_iter().enumerate() {
492        let mut content = history_content.content;
493        content.parts = content
494            .parts
495            .into_iter()
496            .enumerate()
497            .filter_map(|(part_index, part)| {
498                let location = PartLocation { content: content_index, part: part_index };
499                if removed_parts.contains(&location) {
500                    return None;
501                }
502                Some(superseded.remove(&location).unwrap_or(part))
503            })
504            .collect();
505        if !content.parts.is_empty() {
506            normalized.push(content);
507        }
508        if let Some(mut responses) = responses_after.remove(&content_index) {
509            responses.sort_by_key(|(call_part, _, _, _)| *call_part);
510            normalized.extend(responses.into_iter().map(|(_, role, location, response)| {
511                let response = superseded.remove(&location).unwrap_or(response);
512                Content { role, parts: vec![response] }
513            }));
514        }
515    }
516
517    normalized
518}
519
520/// Rearranges a history whose newest turn answers long-running calls after something else
521/// followed them, the way a caller resumes such a call: the call's interim response and
522/// the model's reply to it sit between the call and the caller's answer.
523///
524/// The history then ends on the turn with the calls and one response per call, the
525/// newest; what came between is left out, so the model answers the caller's result.
526/// Without this, the caller's answer reads as a second response to its call, which every
527/// provider rejects, and [`close_interrupted_tool_calls`] drops it. ADK Python and ADK Go
528/// rearrange the same way (`_rearrange_events_for_latest_function_response`).
529///
530/// Only calls in `long_running` are answered this way: a second response to an ordinary
531/// call is still left out, and an ordinary late response still keeps the turns around it.
532/// The history is also returned unchanged when its newest turn is not only function
533/// responses with ids, when those responses follow their calls directly, or when they
534/// answer calls from more than one turn.
535fn answer_resumed_calls(
536    mut history: Vec<HistoryContent>,
537    long_running: &std::collections::HashSet<String>,
538) -> Vec<HistoryContent> {
539    let Some(newest) = history.len().checked_sub(1) else { return history };
540    let mut answered = std::collections::HashSet::new();
541    for part in &history[newest].content.parts {
542        match part {
543            Part::FunctionResponse { id: Some(id), .. } => {
544                answered.insert(id.clone());
545            }
546            _ => return history,
547        }
548    }
549    if answered.is_empty() || !answered.iter().all(|id| long_running.contains(id)) {
550        return history;
551    }
552
553    let Some(call_turn) = history[..newest].iter().rposition(|entry| {
554        entry.content.parts.iter().any(
555            |part| matches!(part, Part::FunctionCall { id: Some(id), .. } if answered.contains(id)),
556        )
557    }) else {
558        return history;
559    };
560    let call_ids: Vec<String> = history[call_turn]
561        .content
562        .parts
563        .iter()
564        .filter_map(|part| match part {
565            Part::FunctionCall { id: Some(id), .. } => Some(id.clone()),
566            _ => None,
567        })
568        .collect();
569    if !answered.iter().all(|id| call_ids.contains(id)) {
570        return history;
571    }
572
573    // Responses to the turn's other calls may sit in between, as parallel calls answer
574    // one at a time. Anything else, or an earlier response to a call answered now, means
575    // the run moved on before this answer came.
576    let moved_on = history[call_turn + 1..newest]
577        .iter()
578        .flat_map(|entry| &entry.content.parts)
579        .any(|part| match part {
580            Part::FunctionResponse { id: Some(id), .. } => {
581                answered.contains(id) || !call_ids.contains(id)
582            }
583            _ => true,
584        });
585    if !moved_on {
586        return history;
587    }
588
589    // One response per call, the newest, in the order of the calls.
590    let mut responses: Vec<Option<Part>> = vec![None; call_ids.len()];
591    for part in history[call_turn + 1..].iter().flat_map(|entry| &entry.content.parts) {
592        if let Part::FunctionResponse { id: Some(id), .. } = part
593            && let Some(position) = call_ids.iter().position(|call_id| call_id == id)
594        {
595            responses[position] = Some(part.clone());
596        }
597    }
598    let answer = history.swap_remove(newest);
599    history.truncate(call_turn + 1);
600    // A tool-result turn, whoever sent the result: model clients carry function responses
601    // in the `function` role, and a user turn holds only the person's input.
602    history.push(HistoryContent {
603        content: Content {
604            role: "function".to_string(),
605            parts: responses.into_iter().flatten().collect(),
606        },
607        invocation_id: answer.invocation_id,
608    });
609    history
610}
611
612impl adk_core::Session for MutableSession {
613    fn id(&self) -> &str {
614        &self.id
615    }
616
617    fn app_name(&self) -> &str {
618        &self.app_name
619    }
620
621    fn user_id(&self) -> &str {
622        &self.user_id
623    }
624
625    fn state(&self) -> &dyn adk_core::State {
626        self
627    }
628
629    fn conversation_history(&self) -> Vec<adk_core::Content> {
630        self.conversation_history_for_agent_impl(None, "")
631    }
632
633    fn conversation_history_for_agent(&self, agent_name: &str) -> Vec<adk_core::Content> {
634        self.conversation_history_for_agent_impl(Some(agent_name), "")
635    }
636
637    fn conversation_history_scoped(
638        &self,
639        agent_name: Option<&str>,
640        branch: &str,
641    ) -> Vec<adk_core::Content> {
642        self.conversation_history_for_agent_impl(agent_name, branch)
643    }
644
645    fn conversation_history_with_context(
646        &self,
647        agent_name: &str,
648        branch: &str,
649    ) -> Vec<adk_core::Content> {
650        self.project_history(Some(agent_name), OtherAgents::AsContext, branch)
651    }
652
653    fn records_invocation_events(&self) -> bool {
654        true
655    }
656
657    fn held_tool_calls(&self, agent_name: &str, branch: &str) -> Vec<adk_core::HeldToolCall> {
658        let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
659        adk_core::held_tool_calls(&events, agent_name, branch)
660    }
661
662    fn workflow_resume_positions(
663        &self,
664        workflow: &str,
665        branch: &str,
666    ) -> Vec<adk_core::WorkflowPosition> {
667        let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
668        adk_core::workflow_resume_positions(&events, workflow, branch)
669    }
670}
671
672impl adk_core::State for MutableSession {
673    fn get(&self, key: &str) -> Option<serde_json::Value> {
674        let state = self.state.read().unwrap_or_else(PoisonError::into_inner);
675        state.get(key).cloned()
676    }
677
678    fn set(&mut self, key: String, value: serde_json::Value) {
679        if let Err(msg) = adk_core::validate_state_key(&key) {
680            tracing::warn!(key = %key, "rejecting invalid state key: {msg}");
681            return;
682        }
683        let mut state = self.state.write().unwrap_or_else(PoisonError::into_inner);
684        state.insert(key, value);
685    }
686
687    fn all(&self) -> HashMap<String, serde_json::Value> {
688        let state = self.state.read().unwrap_or_else(PoisonError::into_inner);
689        state.clone()
690    }
691}
692
693/// Runtime context for a single agent invocation.
694///
695/// Holds the agent, session, identity, and optional services (artifacts, memory,
696/// secrets) needed during execution. Created by the [`Runner`](crate::Runner) for
697/// each `run()` call.
698pub struct InvocationContext {
699    identity: ExecutionIdentity,
700    agent: Arc<dyn Agent>,
701    user_content: Content,
702    artifacts: Option<Arc<dyn Artifacts>>,
703    memory: Option<Arc<dyn Memory>>,
704    run_config: RunConfig,
705    ended: Arc<AtomicBool>,
706    /// Mutable session that allows state to be updated during execution.
707    /// This is shared across all agents in a workflow, enabling state
708    /// propagation between sequential/parallel agents.
709    session: Arc<MutableSession>,
710    /// Optional request context from the server's auth middleware bridge.
711    /// When present, `user_id()` returns `request_context.user_id` and
712    /// `user_scopes()` returns `request_context.scopes`.
713    request_context: Option<RequestContext>,
714    /// Optional shared state for parallel agent coordination.
715    shared_state: Option<Arc<adk_core::SharedState>>,
716    /// Optional secret service for retrieving secrets at runtime.
717    /// When present, `get_secret()` delegates to this service.
718    secret_service: Option<Arc<dyn SecretService>>,
719    /// Optional cooperative cancellation token.
720    ///
721    /// When present, `is_cancelled()` reflects this token, letting agents and
722    /// tools detect external cancellation (`Runner::interrupt()` or
723    /// `RunConfig::cancellation_token`) during long-running work.
724    cancellation_token: Option<tokio_util::sync::CancellationToken>,
725    /// Stable root invocation for a multi-hop orchestration tree.
726    orchestration_root_invocation_id: String,
727    /// The run's queue of steering messages, shared by every agent the run hands control to.
728    steering_inbox: Option<adk_core::SteeringInbox>,
729}
730
731impl InvocationContext {
732    /// Create a new invocation context from validated typed identifiers.
733    pub fn new_typed(
734        invocation_id: String,
735        agent: Arc<dyn Agent>,
736        user_id: UserId,
737        app_name: AppName,
738        session_id: SessionId,
739        user_content: Content,
740        session: Arc<dyn AdkSession>,
741    ) -> adk_core::Result<Self> {
742        let orchestration_root_invocation_id = invocation_id.clone();
743        let identity = ExecutionIdentity {
744            adk: AdkIdentity { app_name, user_id, session_id },
745            invocation_id: InvocationId::try_from(invocation_id)?,
746            branch: String::new(),
747            agent_name: agent.name().to_string(),
748        };
749        Ok(Self {
750            identity,
751            agent,
752            user_content,
753            artifacts: None,
754            memory: None,
755            run_config: RunConfig::default(),
756            ended: Arc::new(AtomicBool::new(false)),
757            session: Arc::new(MutableSession::new(session)),
758            request_context: None,
759            shared_state: None,
760            secret_service: None,
761            cancellation_token: None,
762            orchestration_root_invocation_id,
763            steering_inbox: None,
764        })
765    }
766
767    /// Create a new invocation context from raw string identifiers.
768    ///
769    /// Validates and converts the string identifiers into typed wrappers.
770    /// Prefer [`new_typed`](Self::new_typed) when you already have validated types.
771    pub fn new(
772        invocation_id: String,
773        agent: Arc<dyn Agent>,
774        user_id: String,
775        app_name: String,
776        session_id: String,
777        user_content: Content,
778        session: Arc<dyn AdkSession>,
779    ) -> adk_core::Result<Self> {
780        Self::new_typed(
781            invocation_id,
782            agent,
783            UserId::try_from(user_id)?,
784            AppName::try_from(app_name)?,
785            SessionId::try_from(session_id)?,
786            user_content,
787            session,
788        )
789    }
790
791    /// Create an invocation context that reuses an existing mutable session and
792    /// validated typed identifiers.
793    pub fn with_mutable_session_typed(
794        invocation_id: String,
795        agent: Arc<dyn Agent>,
796        user_id: UserId,
797        app_name: AppName,
798        session_id: SessionId,
799        user_content: Content,
800        session: Arc<MutableSession>,
801    ) -> adk_core::Result<Self> {
802        let orchestration_root_invocation_id = invocation_id.clone();
803        let identity = ExecutionIdentity {
804            adk: AdkIdentity { app_name, user_id, session_id },
805            invocation_id: InvocationId::try_from(invocation_id)?,
806            branch: String::new(),
807            agent_name: agent.name().to_string(),
808        };
809        Ok(Self {
810            identity,
811            agent,
812            user_content,
813            artifacts: None,
814            memory: None,
815            run_config: RunConfig::default(),
816            ended: Arc::new(AtomicBool::new(false)),
817            session,
818            request_context: None,
819            shared_state: None,
820            secret_service: None,
821            cancellation_token: None,
822            orchestration_root_invocation_id,
823            steering_inbox: None,
824        })
825    }
826
827    /// Create an InvocationContext with an existing MutableSession.
828    /// This allows sharing the same mutable session across multiple contexts
829    /// (e.g., for agent transfers).
830    pub fn with_mutable_session(
831        invocation_id: String,
832        agent: Arc<dyn Agent>,
833        user_id: String,
834        app_name: String,
835        session_id: String,
836        user_content: Content,
837        session: Arc<MutableSession>,
838    ) -> adk_core::Result<Self> {
839        Self::with_mutable_session_typed(
840            invocation_id,
841            agent,
842            UserId::try_from(user_id)?,
843            AppName::try_from(app_name)?,
844            SessionId::try_from(session_id)?,
845            user_content,
846            session,
847        )
848    }
849
850    /// Set the event branch identifier for this context.
851    pub fn with_branch(mut self, branch: String) -> Self {
852        self.identity.branch = branch;
853        self
854    }
855
856    /// Attach an artifact storage service to this context.
857    pub fn with_artifacts(mut self, artifacts: Arc<dyn Artifacts>) -> Self {
858        self.artifacts = Some(artifacts);
859        self
860    }
861
862    /// Attach a memory service for RAG/semantic search.
863    pub fn with_memory(mut self, memory: Arc<dyn Memory>) -> Self {
864        self.memory = Some(memory);
865        self
866    }
867
868    /// Set the run configuration (streaming mode, history limits, etc.).
869    pub fn with_run_config(mut self, config: RunConfig) -> Self {
870        self.run_config = config;
871        self
872    }
873
874    /// Set the request context from the server's auth middleware bridge.
875    ///
876    /// When set, `user_id()` returns `request_context.user_id` (overriding
877    /// the session-scoped identity), and `user_scopes()` returns
878    /// `request_context.scopes`. This is the explicit authenticated user
879    /// override — `RequestContext` remains separate from `ExecutionIdentity`
880    /// and `AdkIdentity` (it does not carry session or invocation IDs).
881    pub fn with_request_context(mut self, ctx: RequestContext) -> Self {
882        self.request_context = Some(ctx);
883        self
884    }
885
886    /// Set the shared state for parallel agent coordination.
887    pub fn with_shared_state(mut self, shared: Arc<adk_core::SharedState>) -> Self {
888        self.shared_state = Some(shared);
889        self
890    }
891
892    /// Set the secret service for runtime secret retrieval.
893    ///
894    /// When configured, tools can call `ctx.get_secret("name")` to retrieve
895    /// secrets from the configured provider (e.g., AWS Secrets Manager,
896    /// Azure Key Vault, GCP Secret Manager).
897    pub fn with_secret_service(mut self, service: Arc<dyn SecretService>) -> Self {
898        self.secret_service = Some(service);
899        self
900    }
901
902    /// Attach a cooperative cancellation token.
903    ///
904    /// When set, [`is_cancelled`](adk_core::InvocationContext::is_cancelled)
905    /// reflects this token, so agents and tools can detect external
906    /// cancellation during long-running work.
907    pub fn with_cancellation_token(mut self, token: tokio_util::sync::CancellationToken) -> Self {
908        self.cancellation_token = Some(token);
909        self
910    }
911
912    /// Preserve the stable orchestration root across a Runner handoff.
913    pub fn with_orchestration_root_invocation_id(mut self, invocation_id: String) -> Self {
914        self.orchestration_root_invocation_id = invocation_id;
915        self
916    }
917
918    /// Attach the run's steering inbox, which
919    /// [`steering_inbox`](adk_core::InvocationContext::steering_inbox) returns.
920    ///
921    /// The [`Runner`](crate::Runner) installs one per run, so every agent the run hands
922    /// control to takes the messages [`Runner::steer`](crate::Runner::steer) queues.
923    pub fn with_steering_inbox(mut self, inbox: adk_core::SteeringInbox) -> Self {
924        self.steering_inbox = Some(inbox);
925        self
926    }
927
928    /// Get a reference to the mutable session.
929    /// This allows the Runner to apply state deltas when events are processed.
930    pub fn mutable_session(&self) -> &Arc<MutableSession> {
931        &self.session
932    }
933
934    /// A copy of this context, sharing its session and services, whose user message is
935    /// `content`.
936    pub(crate) fn with_user_content(&self, content: Content) -> Self {
937        Self {
938            identity: self.identity.clone(),
939            agent: self.agent.clone(),
940            user_content: content,
941            artifacts: self.artifacts.clone(),
942            memory: self.memory.clone(),
943            run_config: self.run_config.clone(),
944            ended: self.ended.clone(),
945            session: self.session.clone(),
946            request_context: self.request_context.clone(),
947            shared_state: self.shared_state.clone(),
948            secret_service: self.secret_service.clone(),
949            cancellation_token: self.cancellation_token.clone(),
950            orchestration_root_invocation_id: self.orchestration_root_invocation_id.clone(),
951            steering_inbox: self.steering_inbox.clone(),
952        }
953    }
954}
955
956#[async_trait]
957impl ReadonlyContext for InvocationContext {
958    fn invocation_id(&self) -> &str {
959        self.identity.invocation_id.as_ref()
960    }
961
962    fn agent_name(&self) -> &str {
963        self.agent.name()
964    }
965
966    fn user_id(&self) -> &str {
967        // Explicit authenticated user override: when a RequestContext is
968        // present (set via with_request_context from the auth middleware
969        // bridge), the authenticated user_id takes precedence over the
970        // session-scoped identity. This keeps auth binding explicit and
971        // ensures the runtime reflects the verified caller identity.
972        self.request_context.as_ref().map_or(self.identity.adk.user_id.as_ref(), |rc| &rc.user_id)
973    }
974
975    fn app_name(&self) -> &str {
976        self.identity.adk.app_name.as_ref()
977    }
978
979    fn session_id(&self) -> &str {
980        self.identity.adk.session_id.as_ref()
981    }
982
983    fn branch(&self) -> &str {
984        &self.identity.branch
985    }
986
987    fn user_content(&self) -> &Content {
988        &self.user_content
989    }
990
991    fn acting_context(&self) -> adk_core::ActingContext {
992        self.run_config.acting_context_for(self.app_name(), self.agent_name(), self.user_id())
993    }
994
995    /// `true` when the run carries a [`RequestContext`] (spec 3.1 §10 F5) and its subject
996    /// is not a [`Visitor`](adk_core::SubjectKind::Visitor), whom no credential identifies.
997    fn is_authenticated(&self) -> bool {
998        self.request_context.is_some()
999            && self.run_config.acting.subject_kind != adk_core::SubjectKind::Visitor
1000    }
1001
1002    fn state(&self) -> Option<&dyn adk_core::State> {
1003        // Expose the runner's mutable session view so a toolset can observe a
1004        // state delta emitted by an earlier tool result on the next model turn.
1005        Some(adk_core::Session::state(self.session.as_ref()))
1006    }
1007}
1008
1009#[async_trait]
1010impl CallbackContext for InvocationContext {
1011    fn artifacts(&self) -> Option<Arc<dyn Artifacts>> {
1012        self.artifacts.clone()
1013    }
1014
1015    fn shared_state(&self) -> Option<Arc<adk_core::SharedState>> {
1016        self.shared_state.clone()
1017    }
1018}
1019
1020#[async_trait]
1021impl InvocationContextTrait for InvocationContext {
1022    fn agent(&self) -> Arc<dyn Agent> {
1023        self.agent.clone()
1024    }
1025
1026    fn memory(&self) -> Option<Arc<dyn Memory>> {
1027        self.memory.clone()
1028    }
1029
1030    fn session(&self) -> &dyn adk_core::Session {
1031        self.session.as_ref()
1032    }
1033
1034    fn run_config(&self) -> &RunConfig {
1035        &self.run_config
1036    }
1037
1038    fn end_invocation(&self) {
1039        self.ended.store(true, std::sync::atomic::Ordering::SeqCst);
1040    }
1041
1042    fn ended(&self) -> bool {
1043        self.ended.load(std::sync::atomic::Ordering::SeqCst)
1044    }
1045
1046    fn is_cancelled(&self) -> bool {
1047        self.cancellation_token
1048            .as_ref()
1049            .is_some_and(tokio_util::sync::CancellationToken::is_cancelled)
1050    }
1051
1052    fn user_scopes(&self) -> Vec<String> {
1053        self.request_context.as_ref().map_or_else(Vec::new, |rc| rc.scopes.clone())
1054    }
1055
1056    fn request_metadata(&self) -> HashMap<String, serde_json::Value> {
1057        // The authenticated request context's entries are written last, so an
1058        // unauthenticated entry never replaces one of them.
1059        self.run_config
1060            .request_metadata
1061            .iter()
1062            .chain(self.request_context.iter().flat_map(|rc| rc.metadata.iter()))
1063            .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
1064            .collect()
1065    }
1066
1067    fn orchestration_root_invocation_id(&self) -> &str {
1068        &self.orchestration_root_invocation_id
1069    }
1070
1071    fn steering_inbox(&self) -> Option<adk_core::SteeringInbox> {
1072        self.steering_inbox.clone()
1073    }
1074
1075    async fn get_secret(&self, name: &str) -> adk_core::Result<Option<String>> {
1076        let request = adk_core::SecretRequest::new(name)
1077            .with_identity(self.app_name(), self.user_id(), self.session_id())
1078            .with_invocation_id(self.invocation_id());
1079        self.get_secret_for(&request).await
1080    }
1081
1082    async fn get_secret_for(
1083        &self,
1084        request: &adk_core::SecretRequest,
1085    ) -> adk_core::Result<Option<String>> {
1086        match &self.secret_service {
1087            Some(service) => service.get_secret_for(request).await.map(Some),
1088            None => Ok(None),
1089        }
1090    }
1091}
1092
1093#[cfg(test)]
1094mod poisoned_lock_tests {
1095    use super::*;
1096    use adk_session::{CreateRequest, InMemorySessionService, SessionService};
1097
1098    #[tokio::test]
1099    async fn a_poisoned_lock_keeps_the_history_and_state() {
1100        let service = InMemorySessionService::new();
1101        let stored = service
1102            .create(CreateRequest {
1103                app_name: "app".to_string(),
1104                user_id: "user".to_string(),
1105                session_id: Some("session".to_string()),
1106                state: HashMap::new(),
1107            })
1108            .await
1109            .unwrap();
1110        let session = Arc::new(MutableSession::new(Arc::from(stored)));
1111        let mut event = Event::new("inv-1");
1112        event.author = "user".to_string();
1113        event.llm_response.content = Some(Content::new("user").with_text("hello"));
1114        session.append_event(event);
1115        session.apply_state_delta(&HashMap::from([(
1116            "topic".to_string(),
1117            serde_json::json!("billing"),
1118        )]));
1119
1120        // A thread that panics while it holds the write guards poisons both locks.
1121        let holder = Arc::clone(&session);
1122        let _ = std::thread::spawn(move || {
1123            let _events = holder.events.write().unwrap();
1124            let _state = holder.state.write().unwrap();
1125            panic!("poison the session locks");
1126        })
1127        .join();
1128        assert!(session.events.is_poisoned() && session.state.is_poisoned());
1129
1130        let history = adk_core::Session::conversation_history(session.as_ref());
1131        let texts: Vec<_> = history
1132            .iter()
1133            .map(|content| {
1134                (
1135                    content.role.as_str(),
1136                    content.parts.iter().filter_map(Part::text).collect::<String>(),
1137                )
1138            })
1139            .collect();
1140        assert_eq!(texts, [("user", "hello".to_string())]);
1141        assert_eq!(
1142            adk_core::State::get(session.as_ref(), "topic"),
1143            Some(serde_json::json!("billing"))
1144        );
1145        let mut later = Event::new("inv-1");
1146        later.author = "agent".to_string();
1147        later.llm_response.content = Some(Content::new("model").with_text("hi"));
1148        session.append_event(later);
1149        assert_eq!(session.events_len(), 2, "a write after the panic is kept");
1150    }
1151}
1152
1153#[cfg(test)]
1154mod snapshot_tests {
1155    use super::*;
1156    use adk_session::{Events, State};
1157    use std::sync::atomic::{AtomicUsize, Ordering};
1158
1159    /// A loaded session that counts how its history leaves it.
1160    struct CountingSession {
1161        events: Vec<Event>,
1162        state: HashMap<String, serde_json::Value>,
1163        copies: Arc<AtomicUsize>,
1164        takes: Arc<AtomicUsize>,
1165    }
1166
1167    impl CountingSession {
1168        fn new(copies: &Arc<AtomicUsize>, takes: &Arc<AtomicUsize>) -> Self {
1169            let events = ["first", "second"]
1170                .into_iter()
1171                .map(|text| {
1172                    let mut event = Event::new("inv-1");
1173                    event.author = "user".to_string();
1174                    event.llm_response.content = Some(Content::new("user").with_text(text));
1175                    event
1176                })
1177                .collect();
1178            Self {
1179                events,
1180                state: HashMap::from([("topic".to_string(), serde_json::json!("billing"))]),
1181                copies: Arc::clone(copies),
1182                takes: Arc::clone(takes),
1183            }
1184        }
1185    }
1186
1187    impl Events for CountingSession {
1188        fn all(&self) -> Vec<Event> {
1189            self.copies.fetch_add(1, Ordering::SeqCst);
1190            self.events.clone()
1191        }
1192        fn len(&self) -> usize {
1193            self.events.len()
1194        }
1195        fn at(&self, index: usize) -> Option<&Event> {
1196            self.events.get(index)
1197        }
1198    }
1199
1200    impl State for CountingSession {
1201        fn get(&self, key: &str) -> Option<serde_json::Value> {
1202            self.state.get(key).cloned()
1203        }
1204        fn set(&mut self, key: String, value: serde_json::Value) {
1205            self.state.insert(key, value);
1206        }
1207        fn all(&self) -> HashMap<String, serde_json::Value> {
1208            self.state.clone()
1209        }
1210    }
1211
1212    impl AdkSession for CountingSession {
1213        fn id(&self) -> &str {
1214            "session"
1215        }
1216        fn app_name(&self) -> &str {
1217            "app"
1218        }
1219        fn user_id(&self) -> &str {
1220            "user"
1221        }
1222        fn state(&self) -> &dyn State {
1223            self
1224        }
1225        fn events(&self) -> &dyn Events {
1226            self
1227        }
1228        fn last_update_time(&self) -> chrono::DateTime<chrono::Utc> {
1229            chrono::Utc::now()
1230        }
1231        fn take_events(&mut self) -> Vec<Event> {
1232            self.takes.fetch_add(1, Ordering::SeqCst);
1233            std::mem::take(&mut self.events)
1234        }
1235    }
1236
1237    fn texts(session: &MutableSession) -> Vec<String> {
1238        session
1239            .events_snapshot()
1240            .iter()
1241            .flat_map(|event| event.llm_response.content.iter().flat_map(|c| c.parts.iter()))
1242            .filter_map(|part| part.text().map(str::to_string))
1243            .collect()
1244    }
1245
1246    #[test]
1247    fn a_session_held_once_moves_its_history() {
1248        let (copies, takes) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
1249        let session = MutableSession::new(Arc::new(CountingSession::new(&copies, &takes)));
1250
1251        assert_eq!((copies.load(Ordering::SeqCst), takes.load(Ordering::SeqCst)), (0, 1));
1252        assert_eq!(texts(&session), ["first", "second"]);
1253        let identity = (
1254            adk_core::Session::id(&session),
1255            adk_core::Session::app_name(&session),
1256            adk_core::Session::user_id(&session),
1257        );
1258        assert_eq!(identity, ("session", "app", "user"));
1259        assert_eq!(adk_core::State::get(&session, "topic"), Some(serde_json::json!("billing")));
1260    }
1261
1262    #[test]
1263    fn a_shared_session_keeps_its_history() {
1264        let (copies, takes) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
1265        let shared: Arc<dyn AdkSession> = Arc::new(CountingSession::new(&copies, &takes));
1266        let session = MutableSession::new(Arc::clone(&shared));
1267
1268        assert_eq!((copies.load(Ordering::SeqCst), takes.load(Ordering::SeqCst)), (1, 0));
1269        assert_eq!(texts(&session), ["first", "second"]);
1270        assert_eq!(shared.events().len(), 2, "the caller's handle keeps its events");
1271    }
1272}