Skip to main content

gadk_agent/
parent_map.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! The agent tree's parent map.
17
18use crate::go_fmt::go_quote;
19use std::collections::HashMap;
20use std::sync::Arc;
21
22use crate::agent::Agent;
23use crate::error::AgentError;
24
25/// Child agent name → parent agent, plus the root.
26#[derive(Clone, Default)]
27pub struct ParentMap {
28    parents: HashMap<String, Arc<dyn Agent>>,
29    root: Option<Arc<dyn Agent>>,
30}
31
32impl std::fmt::Debug for ParentMap {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        struct Parents<'a>(&'a HashMap<String, Arc<dyn Agent>>);
35        impl std::fmt::Debug for Parents<'_> {
36            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37                f.debug_map()
38                    .entries(self.0.iter().map(|(child, parent)| (child, parent.name())))
39                    .finish()
40            }
41        }
42        f.debug_struct("ParentMap")
43            .field("parents", &Parents(&self.parents))
44            .field("root", &self.root.as_ref().map(|r| r.name()))
45            .finish()
46    }
47}
48
49impl ParentMap {
50    /// Builds the map: at most one parent per agent, names unique across the tree.
51    pub fn new(root: &Arc<dyn Agent>) -> Result<Self, AgentError> {
52        let mut parents = HashMap::new();
53        let mut seen: HashMap<usize, String> =
54            HashMap::from([(ptr(root), "is root agent".to_string())]);
55        walk(root, root.name(), &mut parents, &mut seen)?;
56        Ok(Self {
57            parents,
58            root: Some(root.clone()),
59        })
60    }
61
62    /// The parent of the agent named `agent_name`; `None` for the root or an unknown name.
63    pub fn parent(&self, agent_name: &str) -> Option<Arc<dyn Agent>> {
64        self.parents.get(agent_name).cloned()
65    }
66
67    /// The root agent the map was built from.
68    pub fn root(&self) -> Option<Arc<dyn Agent>> {
69        self.root.clone()
70    }
71
72    /// Follows parents from `cur` to the top.
73    pub fn root_agent(&self, cur: &Arc<dyn Agent>) -> Arc<dyn Agent> {
74        let mut cur = cur.clone();
75        while let Some(parent) = self.parents.get(cur.name()) {
76            cur = parent.clone();
77        }
78        cur
79    }
80}
81
82fn ptr(a: &Arc<dyn Agent>) -> usize {
83    Arc::as_ptr(a).cast::<()>() as usize
84}
85
86fn walk(
87    cur: &Arc<dyn Agent>,
88    root_name: &str,
89    parents: &mut HashMap<String, Arc<dyn Agent>>,
90    seen: &mut HashMap<usize, String>,
91) -> Result<(), AgentError> {
92    for sub in cur.sub_agents() {
93        if let Some(p) = seen.get(&ptr(sub)) {
94            return Err(AgentError::Config(format!(
95                "{} agent cannot have >1 parents, found: {}, {}",
96                go_quote(sub.name()),
97                go_quote(p),
98                go_quote(cur.name())
99            )));
100        }
101        if parents.contains_key(sub.name()) || sub.name() == root_name {
102            return Err(AgentError::Config(format!(
103                "agent names must be unique in the agent tree, found duplicate: {}",
104                go_quote(sub.name())
105            )));
106        }
107        parents.insert(sub.name().to_string(), cur.clone());
108        seen.insert(ptr(sub), cur.name().to_string());
109        walk(sub, root_name, parents, seen)?;
110    }
111    Ok(())
112}