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
11pub struct MutableSession {
22 id: String,
24 app_name: String,
25 user_id: String,
26 state: Arc<RwLock<HashMap<String, serde_json::Value>>>,
29 events: Arc<RwLock<Vec<Event>>>,
31}
32
33impl MutableSession {
34 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 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 for (key, value) in delta {
70 state.insert(key.clone(), value.clone());
71 }
72 }
73
74 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 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 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 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 pub fn events_len(&self) -> usize {
102 let events = self.events.read().unwrap_or_else(PoisonError::into_inner);
103 events.len()
104 }
105
106 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 let mut compaction_boundary = None;
150 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 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 if event.actions.compaction.is_some() {
192 continue;
193 }
194
195 if event.llm_response.partial {
198 continue;
199 }
200
201 if event.actions.tool_confirmation.is_some() {
205 continue;
206 }
207
208 if let Some(boundary) = compaction_boundary
210 && event.timestamp <= boundary
211 {
212 continue;
213 }
214
215 if !adk_core::event_belongs_to_branch(branch, &event.branch) {
219 continue;
220 }
221
222 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 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 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 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
294fn 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#[derive(Clone, Copy)]
312enum OtherAgents {
313 Exclude,
315 AsContext,
317 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
340struct HeldAnswer {
342 response: PartLocation,
344 id: Option<String>,
345 name: String,
346}
347
348fn 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 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 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 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 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
520fn 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 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 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 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
693pub 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 session: Arc<MutableSession>,
710 request_context: Option<RequestContext>,
714 shared_state: Option<Arc<adk_core::SharedState>>,
716 secret_service: Option<Arc<dyn SecretService>>,
719 cancellation_token: Option<tokio_util::sync::CancellationToken>,
725 orchestration_root_invocation_id: String,
727 steering_inbox: Option<adk_core::SteeringInbox>,
729}
730
731impl InvocationContext {
732 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 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 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 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 pub fn with_branch(mut self, branch: String) -> Self {
852 self.identity.branch = branch;
853 self
854 }
855
856 pub fn with_artifacts(mut self, artifacts: Arc<dyn Artifacts>) -> Self {
858 self.artifacts = Some(artifacts);
859 self
860 }
861
862 pub fn with_memory(mut self, memory: Arc<dyn Memory>) -> Self {
864 self.memory = Some(memory);
865 self
866 }
867
868 pub fn with_run_config(mut self, config: RunConfig) -> Self {
870 self.run_config = config;
871 self
872 }
873
874 pub fn with_request_context(mut self, ctx: RequestContext) -> Self {
882 self.request_context = Some(ctx);
883 self
884 }
885
886 pub fn with_shared_state(mut self, shared: Arc<adk_core::SharedState>) -> Self {
888 self.shared_state = Some(shared);
889 self
890 }
891
892 pub fn with_secret_service(mut self, service: Arc<dyn SecretService>) -> Self {
898 self.secret_service = Some(service);
899 self
900 }
901
902 pub fn with_cancellation_token(mut self, token: tokio_util::sync::CancellationToken) -> Self {
908 self.cancellation_token = Some(token);
909 self
910 }
911
912 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 pub fn with_steering_inbox(mut self, inbox: adk_core::SteeringInbox) -> Self {
924 self.steering_inbox = Some(inbox);
925 self
926 }
927
928 pub fn mutable_session(&self) -> &Arc<MutableSession> {
931 &self.session
932 }
933
934 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 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 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 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 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 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 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}