Skip to main content

adk_harness/
team.rs

1//! Team members lowered to one `TeamSpec` (spec 3.1 §7.10, feature `team`).
2//!
3//! The harness coordinator and its members compile to a team with one `Delegate` edge per
4//! member, which gives every delegation a timeout, a circuit breaker, a team budget,
5//! termination and runtime discovery, and lets the harness itself be a member of a larger
6//! team (spec 3.1 §6 D-5).
7//!
8//! | Member kind | Agent | Its tool calls |
9//! |---|---|---|
10//! | [`MemberKind::Local`] | an `LlmAgent` the harness builds over [`HarnessToolset::member`] | the shared [`HarnessPolicy`](crate::HarnessPolicy) and the parent's mode |
11//! | `MemberKind::Acp` (`team-acp`) | an ACP-compatible coding agent over `adk-acp` | each permission request through the governed path |
12//! | `MemberKind::Remote` (`team-a2a`) | `RemoteA2aAgent` | governed by the remote agent |
13//! | [`MemberKind::Agent`] | the agent supplied | the shared policy; its tools are `External` |
14//! | `MemberKind::Perceiver` (`vision`) | an `LlmAgent` on a model that runs on the device, over the read tools and the vision pack's on-device tools | as a local member; a call that would leave the device is refused |
15//!
16//! With the vision pack, `MemberSpec::perceiver`, `MemberSpec::reasoner` and
17//! `MemberSpec::verifier` are the three roles of a multimodal team (spec 3.7 §7.12). The
18//! harness refuses to build a perceiver on a remote model or holding any tool that declares
19//! network use, and puts the pack's privacy guardrail on every local member whose model is
20//! remote, so a reasoner sees only images the egress gate released.
21
22use std::collections::{BTreeMap, HashMap, HashSet};
23use std::fmt;
24use std::sync::Arc;
25use std::time::{Duration, Instant};
26
27use adk_agent::{
28    CircuitBreakerPolicy, LlmAgentBuilder, RelationshipApprovalPolicy, RelationshipFailureStrategy,
29    RelationshipKind, RelationshipPolicy, TeamAgentDescriptor, TeamAgentHealth, TeamAgentRegistry,
30    TeamContextPolicy, TeamHistoryPolicy, TeamMemberSpec, TeamPolicy, TeamRelationship,
31    TeamResumePolicy, TeamSpec, TeamStateMergePolicy,
32};
33use adk_core::audit_log::AuditActor;
34use adk_core::{
35    AdkError, Agent, AgentCapabilities, AgentTopology, Content, EventStream, InstructionProvider,
36    InvocationContext, Llm, ReadonlyContext, Result, RunConfig, Tool,
37};
38use adk_devtools::Workspace;
39use async_trait::async_trait;
40use futures::StreamExt;
41use serde_json::{Value, json};
42use tracing::Instrument;
43
44use crate::audit::HarnessAudit;
45use crate::mode::{HarnessMode, ModeStore};
46use crate::policy::{ToolClassRegistry, ToolKind};
47use crate::run_context::ScopedContext;
48use crate::toolset::HarnessToolset;
49
50/// A member's delegation timeout unless its spec sets another (spec 3.1 §7.10).
51///
52/// # Example
53///
54/// ```rust
55/// assert_eq!(adk_harness::MEMBER_TIMEOUT.as_secs(), 15 * 60);
56/// ```
57pub const MEMBER_TIMEOUT: Duration = Duration::from_secs(15 * 60);
58
59/// A member's most model turns unless its spec sets another (spec 3.1 §7.10).
60///
61/// # Example
62///
63/// ```rust
64/// assert_eq!(adk_harness::MEMBER_MAX_ITERATIONS, 50);
65/// ```
66pub const MEMBER_MAX_ITERATIONS: u32 = 50;
67
68/// The circuit breaker on every member edge (spec 3.1 §7.10): three consecutive failures
69/// open the edge for a minute.
70///
71/// # Example
72///
73/// ```rust
74/// assert_eq!(adk_harness::MEMBER_CIRCUIT_BREAKER.failure_threshold, 3);
75/// ```
76pub const MEMBER_CIRCUIT_BREAKER: CircuitBreakerPolicy =
77    CircuitBreakerPolicy { failure_threshold: 3, reset_after_ms: 60_000 };
78
79/// Names of the read tools a [`MemberTools::ReadOnly`] member gets.
80const READ_ONLY_MEMBER_TOOLS: &[&str] =
81    &["read_file", "glob", "grep", "write_todos", "update_todo"];
82
83/// One member of the harness team (spec 3.1 §7.10).
84///
85/// # Example
86///
87/// ```rust
88/// let explore = adk_harness::MemberSpec::explore();
89/// assert_eq!(explore.name, "explore");
90/// assert_eq!(explore.max_iterations, 50);
91/// ```
92#[derive(Clone)]
93pub struct MemberSpec {
94    /// Member name.
95    pub name: String,
96    /// When to use it (model-facing).
97    pub description: String,
98    /// What the member is.
99    pub kind: MemberKind,
100    /// The member's tools.
101    pub tools: MemberTools,
102    /// Whether the member sees skills.
103    pub skills: bool,
104    /// Most model turns.
105    pub max_iterations: u32,
106    /// Delegation timeout; never unlimited.
107    pub timeout: Duration,
108    /// Structured output schema.
109    pub output_schema: Option<Value>,
110}
111
112impl fmt::Debug for MemberSpec {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        f.debug_struct("MemberSpec")
115            .field("name", &self.name)
116            .field("description", &self.description)
117            .field("kind", &self.kind_label())
118            .field("skills", &self.skills)
119            .field("max_iterations", &self.max_iterations)
120            .field("timeout", &self.timeout)
121            .finish_non_exhaustive()
122    }
123}
124
125/// What a member is (spec 3.1 §7.10).
126///
127/// # Example
128///
129/// ```rust
130/// let kind = adk_harness::MemberKind::Local { instruction: "Find the relevant files.".into(), model: None };
131/// # let _ = kind;
132/// ```
133#[derive(Clone)]
134#[non_exhaustive]
135#[allow(
136    clippy::large_enum_variant,
137    reason = "built once per team member; boxing the ACP config would only change the public variant"
138)]
139pub enum MemberKind {
140    /// An `LlmAgent` the harness builds.
141    Local {
142        /// The member's instruction.
143        instruction: String,
144        /// Its model; `None` uses the member model or the harness model.
145        model: Option<Arc<dyn Llm>>,
146    },
147    /// An ACP-compatible coding agent.
148    #[cfg(feature = "team-acp")]
149    Acp(adk_acp::AcpAgentConfig),
150    /// A remote agent over A2A.
151    #[cfg(feature = "team-a2a")]
152    Remote(adk_server::a2a::RemoteA2aConfig),
153    /// Any agent the caller supplies.
154    Agent(Arc<dyn Agent>),
155    /// A perceiver (spec 3.7 §7.12, feature `vision`): an `LlmAgent` the harness builds on a
156    /// model that runs on the device, holding the read tools and the vision pack's on-device
157    /// tools only ([`MemberTools::ReadOnly`] or [`MemberTools::LocalPerception`]). The build
158    /// refuses a remote model and any other tools.
159    #[cfg(feature = "vision")]
160    Perceiver {
161        /// The member's instruction.
162        instruction: String,
163        /// Its model; must not send requests off the machine.
164        model: Arc<dyn Llm>,
165    },
166}
167
168/// The tools a member gets (spec 3.1 §7.10).
169///
170/// # Example
171///
172/// ```rust
173/// assert!(matches!(adk_harness::MemberTools::default(), adk_harness::MemberTools::ReadOnly));
174/// ```
175#[derive(Clone, Default)]
176pub enum MemberTools {
177    /// Read tools only; the default.
178    #[default]
179    ReadOnly,
180    /// Every harness tool a member may have.
181    Full,
182    /// Exactly these tools.
183    Custom(Vec<Arc<dyn Tool>>),
184    /// The read tools, the vision pack's tools whose default backend is on the device, and
185    /// these (spec 3.7 §7.12, feature `vision`). Each of these must declare no network use,
186    /// or the build refuses the member; each call of any of them that would leave the device
187    /// is refused when it runs.
188    #[cfg(feature = "vision")]
189    LocalPerception(Vec<Arc<dyn Tool>>),
190}
191
192impl MemberSpec {
193    fn local(name: &str, description: &str, instruction: &str, tools: MemberTools) -> Self {
194        Self {
195            name: name.to_string(),
196            description: description.to_string(),
197            kind: MemberKind::Local { instruction: instruction.to_string(), model: None },
198            tools,
199            skills: false,
200            max_iterations: MEMBER_MAX_ITERATIONS,
201            timeout: MEMBER_TIMEOUT,
202            output_schema: None,
203        }
204    }
205
206    /// A read-only explorer.
207    pub fn explore() -> Self {
208        Self::local(
209            "explore",
210            "Explores the codebase read-only and reports what it found, with file paths.",
211            "Investigate the question with read-only tools. Report findings with file paths and line numbers.",
212            MemberTools::ReadOnly,
213        )
214    }
215
216    /// A general-purpose member with the full tool set.
217    pub fn general() -> Self {
218        Self::local(
219            "general",
220            "Handles a self-contained subtask with the full tool set and reports the result.",
221            "Complete the subtask you are given and report what you changed and verified.",
222            MemberTools::Full,
223        )
224    }
225
226    /// A reviewer that is an ACP-compatible coding agent started with `cmd` (spec 3.1
227    /// §7.10, feature `team-acp`). It runs in the harness workspace and every permission
228    /// it asks for is decided by the harness policy.
229    ///
230    /// # Example
231    ///
232    /// ```rust
233    /// let reviewer = adk_harness::MemberSpec::reviewer_acp("my-coding-agent --acp");
234    /// assert_eq!(reviewer.name, "reviewer");
235    /// ```
236    #[cfg(feature = "team-acp")]
237    pub fn reviewer_acp(cmd: &str) -> Self {
238        Self {
239            name: "reviewer".to_string(),
240            description: "Reviews a change with an independent coding agent and reports problems, \
241                          with file paths, or confirms it is ready."
242                .to_string(),
243            kind: MemberKind::Acp(adk_acp::AcpAgentConfig::new(cmd)),
244            tools: MemberTools::ReadOnly,
245            skills: false,
246            max_iterations: MEMBER_MAX_ITERATIONS,
247            timeout: MEMBER_TIMEOUT,
248            output_schema: None,
249        }
250    }
251
252    /// Whether the harness builds the member's agent itself: a local member or a perceiver.
253    fn is_built_locally(&self) -> bool {
254        match &self.kind {
255            MemberKind::Local { .. } => true,
256            #[cfg(feature = "vision")]
257            MemberKind::Perceiver { .. } => true,
258            _ => false,
259        }
260    }
261
262    /// The member's kind as audit records name it: `local`, `acp`, `a2a` or `agent`. A
263    /// perceiver is `local`.
264    pub fn kind_label(&self) -> &'static str {
265        match &self.kind {
266            MemberKind::Local { .. } => "local",
267            #[cfg(feature = "vision")]
268            MemberKind::Perceiver { .. } => "local",
269            #[cfg(feature = "team-acp")]
270            MemberKind::Acp(_) => "acp",
271            #[cfg(feature = "team-a2a")]
272            MemberKind::Remote(_) => "a2a",
273            MemberKind::Agent(_) => "agent",
274        }
275    }
276
277    /// The contract of the coordinator's `Delegate` edge to this member (spec 3.1 §7.10).
278    ///
279    /// | Field | Value |
280    /// |---|---|
281    /// | `context` | `Isolated` |
282    /// | `history` | `None` |
283    /// | `state_keys`, `state_write_keys`, `artifact_prefixes` | empty |
284    /// | `timeout_ms` | the member's `timeout` |
285    /// | `approval` | `Never`: the member's own calls are governed by the shared policy |
286    /// | `failure` | read-only local members retry once after a second; any other member is attempted once, since a retry would repeat its effects (§9.2 I37) |
287    /// | `circuit_breaker` | [`MEMBER_CIRCUIT_BREAKER`] |
288    /// | `output_schema` | the member's `output_schema` |
289    ///
290    /// # Example
291    ///
292    /// ```rust
293    /// use adk_agent::{RelationshipApprovalPolicy, TeamContextPolicy};
294    ///
295    /// let policy = adk_harness::MemberSpec::explore().relationship_policy();
296    /// assert_eq!(policy.context, Some(TeamContextPolicy::Isolated));
297    /// assert_eq!(policy.timeout_ms, Some(15 * 60 * 1000));
298    /// assert_eq!(policy.approval, RelationshipApprovalPolicy::Never);
299    /// ```
300    pub fn relationship_policy(&self) -> RelationshipPolicy {
301        let read_only_local =
302            self.is_built_locally() && matches!(self.tools, MemberTools::ReadOnly);
303        RelationshipPolicy {
304            input_schema: None,
305            output_schema: self.output_schema.clone(),
306            context: Some(TeamContextPolicy::Isolated),
307            history: TeamHistoryPolicy::None,
308            state_keys: Vec::new(),
309            state_write_keys: Vec::new(),
310            state_merge: TeamStateMergePolicy::RejectConflicts,
311            artifact_prefixes: Vec::new(),
312            resume: TeamResumePolicy::FailClosed,
313            timeout_ms: Some(u64::try_from(self.timeout.as_millis()).unwrap_or(u64::MAX)),
314            approval: RelationshipApprovalPolicy::Never,
315            failure: if read_only_local {
316                RelationshipFailureStrategy::Retry { max_attempts: 2, backoff_ms: 1_000 }
317            } else {
318                RelationshipFailureStrategy::Retry { max_attempts: 1, backoff_ms: 0 }
319            },
320            circuit_breaker: Some(MEMBER_CIRCUIT_BREAKER),
321        }
322    }
323}
324
325/// The team policy of a harness team (spec 3.1 §7.10): `base` (or the default) with an
326/// isolated context and a delegation depth of 1, which the harness always enforces
327/// (spec 3.1 §9.2 I35). The budget, termination, failure policy and concurrency come from
328/// `base`; the default allows four concurrent delegations.
329///
330/// # Example
331///
332/// ```rust
333/// use adk_agent::{TeamContextPolicy, TeamPolicy};
334///
335/// let policy = adk_harness::harness_team_policy(Some(TeamPolicy { max_delegation_depth: 3, ..TeamPolicy::default() }));
336/// assert_eq!(policy.context, TeamContextPolicy::Isolated);
337/// assert_eq!(policy.max_delegation_depth, 1);
338/// assert_eq!(policy.max_concurrent_delegations, 4);
339/// ```
340pub fn harness_team_policy(base: Option<TeamPolicy>) -> TeamPolicy {
341    let mut policy = base.unwrap_or_default();
342    policy.context = TeamContextPolicy::Isolated;
343    policy.max_delegation_depth = 1;
344    policy
345}
346
347/// The compiled team of a harness (spec 3.1 §7.10).
348///
349/// # Example
350///
351/// ```rust,ignore
352/// let team = harness.runtime().team().expect("the harness has members");
353/// assert_eq!(team.spec().coordinator, "harness");
354/// ```
355pub struct HarnessTeam {
356    spec: TeamSpec,
357    root: Arc<dyn Agent>,
358    members: BTreeMap<String, Arc<dyn Agent>>,
359    own: BTreeMap<String, Arc<dyn Agent>>,
360}
361
362impl fmt::Debug for HarnessTeam {
363    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
364        f.debug_struct("HarnessTeam")
365            .field("name", &self.spec.name)
366            .field("members", &self.members.keys().collect::<Vec<_>>())
367            .finish()
368    }
369}
370
371impl HarnessTeam {
372    /// The `TeamSpec` the members lowered to.
373    pub fn spec(&self) -> &TeamSpec {
374        &self.spec
375    }
376
377    /// The members' names, in name order.
378    pub fn member_names(&self) -> Vec<String> {
379        self.members.keys().cloned().collect()
380    }
381
382    /// The compiled team root.
383    pub(crate) fn root(&self) -> &Arc<dyn Agent> {
384        &self.root
385    }
386
387    /// A review round over `reviewers` (spec 3.1 §7.10 "group work"): a round-robin
388    /// `BlackboardSpec` in which each reviewer reads what the others said, for at most
389    /// `max_rounds` rounds. Run it as an isolated delegation, as a plan's `Review` gate does.
390    ///
391    /// # Errors
392    ///
393    /// Returns a configuration error when a reviewer is not a member the harness built, or
394    /// the round is invalid (no reviewers, zero rounds).
395    ///
396    /// # Example
397    ///
398    /// ```rust,ignore
399    /// let round = harness.runtime().team().unwrap().review_round("review", &["reviewer", "explore"], 2)?;
400    /// ```
401    pub fn review_round(
402        &self,
403        name: &str,
404        reviewers: &[&str],
405        max_rounds: u32,
406    ) -> Result<Arc<dyn Agent>> {
407        self.review_round_with(
408            name,
409            reviewers,
410            adk_agent::BlackboardPolicy { max_rounds, ..Default::default() },
411        )
412    }
413
414    /// A review round over `reviewers` under `policy` (spec 3.1 §7.10 "group work"): a
415    /// round-robin `BlackboardSpec` whose rounds, history window, `TeamBudget` and
416    /// termination are the policy's. Each reviewer sees what the others said, called and got
417    /// back as other-agent context. Run it as an isolated delegation, or as a runner root
418    /// under the harness layer with [`HarnessAgent::governed_root`](crate::HarnessAgent::governed_root).
419    ///
420    /// # Errors
421    ///
422    /// Returns a configuration error when a reviewer is not a member the harness built, or
423    /// the round is invalid (no reviewers, zero rounds, an empty history window).
424    ///
425    /// # Example
426    ///
427    /// ```rust,ignore
428    /// use adk_agent::{BlackboardHistoryPolicy, BlackboardPolicy};
429    ///
430    /// let team = harness.runtime().team().expect("the harness has members");
431    /// let round = team.review_round_with(
432    ///     "review",
433    ///     &["review_correctness", "review_style"],
434    ///     BlackboardPolicy { max_rounds: 2, history: BlackboardHistoryPolicy::Full, ..Default::default() },
435    /// )?;
436    /// ```
437    pub fn review_round_with(
438        &self,
439        name: &str,
440        reviewers: &[&str],
441        policy: adk_agent::BlackboardPolicy,
442    ) -> Result<Arc<dyn Agent>> {
443        let agents = reviewers
444            .iter()
445            .map(|reviewer| {
446                self.own.get(*reviewer).cloned().ok_or_else(|| {
447                    AdkError::config(format!("'{reviewer}' is not a member the harness built"))
448                })
449            })
450            .collect::<Result<Vec<_>>>()?;
451        let spec = adk_agent::BlackboardSpec {
452            name: name.to_string(),
453            description: format!("A review round of {}.", reviewers.join(", ")),
454            members: reviewers.iter().map(|reviewer| (*reviewer).to_string()).collect(),
455            schedule: adk_agent::BlackboardSchedule::RoundRobin,
456            transitions: Vec::new(),
457            policy,
458        };
459        Ok(Arc::new(spec.compile(agents).map_err(AdkError::from)?))
460    }
461
462    /// The agent a plan's `Review` gate delegates to (spec 3.1 §7.11): the member named
463    /// `reviewer*` when there is one, a review round when there are several, else
464    /// `explore`.
465    #[cfg(feature = "graph")]
466    pub(crate) fn reviewer(&self) -> Option<Arc<dyn Agent>> {
467        let reviewers: Vec<&str> = self
468            .own
469            .keys()
470            .map(String::as_str)
471            .filter(|name| name.starts_with("reviewer"))
472            .collect();
473        match reviewers.as_slice() {
474            [] => self.own.get("explore").cloned(),
475            [one] => self.own.get(*one).cloned(),
476            several => self.review_round("review_round", several, 1).ok(),
477        }
478    }
479}
480
481/// The members a harness lowers, resolved before its policy is built: their names
482/// register in the tool-class registry (spec 3.1 §7.4, §9.2 I12).
483pub(crate) struct TeamPlan {
484    members: Vec<MemberSpec>,
485    discovered: Vec<TeamAgentDescriptor>,
486    registry: Option<Arc<dyn TeamAgentRegistry>>,
487    policy: TeamPolicy,
488}
489
490/// What the lowering needs from the harness build.
491pub(crate) struct TeamInputs<'a> {
492    pub(crate) harness: &'a str,
493    pub(crate) coordinator: Arc<dyn Agent>,
494    pub(crate) model: Arc<dyn Llm>,
495    pub(crate) tools: &'a [Arc<dyn Tool>],
496    pub(crate) mode_store: Arc<dyn ModeStore>,
497    pub(crate) default_mode: HarnessMode,
498    pub(crate) workspace: &'a Workspace,
499    pub(crate) tool_timeout: Duration,
500    #[cfg(feature = "skills")]
501    pub(crate) skills: &'a crate::skills::SkillsConfig,
502    /// The coordinator toolset's request observers (identity gate, loop guard).
503    pub(crate) observers: &'a [Arc<dyn crate::toolset::RequestObserver>],
504    /// The harness's effort policy; members run at `members` (spec 3.1 §7.23).
505    pub(crate) effort: crate::posture::EffortPolicy,
506    /// The vision pack, whose evidence callback and privacy guardrail every local member gets.
507    #[cfg(feature = "vision")]
508    pub(crate) vision: Option<&'a crate::packs::vision::VisionPackRuntime>,
509    /// The harness audit trail the members' privacy guardrails write to.
510    #[cfg(feature = "vision")]
511    pub(crate) vision_audit: Option<adk_core::audit_log::AuditTrail>,
512}
513
514/// Runs `future` to completion from a synchronous caller, inside a runtime or not.
515///
516/// `HarnessAgentBuilder::build` is synchronous and a member registry is asynchronous, so the
517/// registry is read on a scoped thread with its own runtime; the caller's runtime, if any,
518/// is never blocked on itself.
519fn block_on<T: Send>(future: impl std::future::Future<Output = T> + Send) -> Result<T> {
520    std::thread::scope(|scope| {
521        scope
522            .spawn(|| {
523                let runtime =
524                    tokio::runtime::Builder::new_current_thread().enable_all().build().map_err(
525                        |error| AdkError::config(format!("cannot start a runtime: {error}")),
526                    )?;
527                Ok(runtime.block_on(future))
528            })
529            .join()
530            .map_err(|_| AdkError::config("the member registry panicked"))?
531    })
532}
533
534impl TeamPlan {
535    /// The members as the manifest lists them (spec 3.1 §7.25), sorted by name.
536    pub(crate) fn member_entries(&self) -> Vec<crate::manifest::MemberEntry> {
537        let mut entries: Vec<crate::manifest::MemberEntry> = self
538            .members
539            .iter()
540            .map(|member| {
541                let kind = match &member.kind {
542                    MemberKind::Local { .. } => "local",
543                    #[cfg(feature = "vision")]
544                    MemberKind::Perceiver { .. } => "local",
545                    #[cfg(feature = "team-acp")]
546                    MemberKind::Acp(_) => "acp",
547                    #[cfg(feature = "team-a2a")]
548                    MemberKind::Remote(_) => "a2a",
549                    MemberKind::Agent(_) => "agent",
550                };
551                let tools = match &member.tools {
552                    MemberTools::ReadOnly => "read-only",
553                    MemberTools::Full => "full",
554                    MemberTools::Custom(_) => "custom",
555                    #[cfg(feature = "vision")]
556                    MemberTools::LocalPerception(_) => "local-perception",
557                };
558                crate::manifest::MemberEntry::new(member.name.clone(), kind, tools)
559            })
560            .chain(self.discovered.iter().map(|agent| {
561                crate::manifest::MemberEntry::new(agent.name.clone(), "a2a", "its own")
562            }))
563            .collect();
564        entries.sort_by(|a, b| a.name.cmp(&b.name));
565        entries
566    }
567
568    /// Resolves the member list: the defaults (`explore`, `general`) unless left out or
569    /// replaced by a member of the same name, the members given, and the candidates of
570    /// `registry` that no other member names.
571    ///
572    /// Returns `None` when the harness has no members.
573    pub(crate) fn prepare(
574        harness: &str,
575        members: Vec<MemberSpec>,
576        defaults: bool,
577        registry: Option<Arc<dyn TeamAgentRegistry>>,
578        policy: Option<TeamPolicy>,
579        reserved: &HashSet<String>,
580    ) -> Result<Option<Self>> {
581        let mut all: Vec<MemberSpec> = Vec::new();
582        if defaults {
583            for default in [MemberSpec::explore(), MemberSpec::general()] {
584                if !members.iter().any(|member| member.name == default.name) {
585                    all.push(default);
586                }
587            }
588        }
589        all.extend(members);
590        let mut names = HashSet::new();
591        for member in &all {
592            let name = member.name.trim();
593            if name.is_empty() || name != member.name {
594                return Err(AdkError::config(format!(
595                    "member name '{}' must be non-empty with no surrounding spaces",
596                    member.name
597                )));
598            }
599            if name == harness || reserved.contains(name) {
600                return Err(AdkError::config(format!(
601                    "member '{name}' collides with the harness or one of its tools; members are \
602                     called as tools named after them, so choose another name"
603                )));
604            }
605            if !names.insert(name.to_string()) {
606                return Err(AdkError::config(format!("member '{name}' is declared twice")));
607            }
608            if member.timeout.is_zero() {
609                return Err(AdkError::config(format!(
610                    "member '{name}' has a zero timeout; every member edge has a timeout (spec 3.1 §9.2 I35)"
611                )));
612            }
613            if let MemberKind::Agent(agent) = &member.kind
614                && agent.name() == harness
615            {
616                return Err(AdkError::config(format!(
617                    "member '{name}' wraps an agent named like the harness"
618                )));
619            }
620        }
621        let discovered = match &registry {
622            Some(registry) => {
623                let registry = registry.clone();
624                let candidates = block_on(async move { registry.candidates().await })??;
625                let mut seen = HashSet::new();
626                candidates
627                    .into_iter()
628                    .filter(|candidate| candidate.health != TeamAgentHealth::Unavailable)
629                    .filter(|candidate| {
630                        candidate.name != harness
631                            && !names.contains(&candidate.name)
632                            && !reserved.contains(&candidate.name)
633                            && seen.insert(candidate.name.clone())
634                    })
635                    .collect()
636            }
637            None => Vec::new(),
638        };
639        if all.is_empty() && discovered.is_empty() {
640            return Ok(None);
641        }
642        Ok(Some(Self { members: all, discovered, registry, policy: harness_team_policy(policy) }))
643    }
644
645    /// Every member's name.
646    pub(crate) fn names(&self) -> Vec<String> {
647        self.members
648            .iter()
649            .map(|member| member.name.clone())
650            .chain(self.discovered.iter().map(|candidate| candidate.name.clone()))
651            .collect()
652    }
653
654    /// Registers the members' classes (spec 3.1 §7.4): every delegation is `Delegate`; a
655    /// local or ACP member is one of the harness's own agents, so its calls classify as
656    /// harness classes; an ACP member's read and edit permission requests are `Read` and
657    /// `Edit`.
658    pub(crate) fn register_classes(&self, registry: &mut ToolClassRegistry) {
659        let mut updated = std::mem::take(registry);
660        for name in self.names() {
661            updated.register(name, ToolKind::Delegate);
662        }
663        for member in &self.members {
664            match &member.kind {
665                MemberKind::Local { .. } => updated = updated.with_agent(member.name.clone()),
666                #[cfg(feature = "vision")]
667                MemberKind::Perceiver { .. } => updated = updated.with_agent(member.name.clone()),
668                #[cfg(feature = "team-acp")]
669                MemberKind::Acp(_) => {
670                    updated = updated.with_agent(member.name.clone());
671                    updated.register(acp::ACP_READ, ToolKind::Read);
672                    updated.register(acp::ACP_EDIT, ToolKind::Edit);
673                }
674                #[cfg(feature = "team-a2a")]
675                MemberKind::Remote(_) => {}
676                MemberKind::Agent(_) => {}
677            }
678        }
679        *registry = updated;
680    }
681
682    /// Lowers the members to one `TeamSpec` with the coordinator and compiles it
683    /// (spec 3.1 §7.10).
684    pub(crate) fn compile(self, inputs: TeamInputs<'_>) -> Result<HarnessTeam> {
685        let mut agents: BTreeMap<String, Arc<dyn Agent>> = BTreeMap::new();
686        let mut team_members = vec![
687            TeamMemberSpec::new(inputs.harness)
688                .with_description(inputs.coordinator.description().to_string()),
689        ];
690        let mut relationships = Vec::new();
691        for member in &self.members {
692            let agent = build_member(member, &inputs)?;
693            team_members.push(
694                TeamMemberSpec::new(member.name.clone())
695                    .with_description(member.description.clone()),
696            );
697            relationships.push(
698                TeamRelationship::new(
699                    inputs.harness,
700                    member.name.clone(),
701                    RelationshipKind::Delegate,
702                )
703                .with_policy(member.relationship_policy()),
704            );
705            agents.insert(member.name.clone(), agent);
706        }
707        for candidate in &self.discovered {
708            let spec = MemberSpec {
709                name: candidate.name.clone(),
710                description: candidate.description.clone(),
711                kind: MemberKind::Agent(Arc::new(PendingRegistryAgent)),
712                tools: MemberTools::ReadOnly,
713                skills: false,
714                max_iterations: MEMBER_MAX_ITERATIONS,
715                timeout: MEMBER_TIMEOUT,
716                output_schema: None,
717            };
718            let mut member = TeamMemberSpec::new(candidate.name.clone());
719            if !candidate.description.is_empty() {
720                member = member.with_description(candidate.description.clone());
721            }
722            team_members.push(member);
723            relationships.push(
724                TeamRelationship::new(
725                    inputs.harness,
726                    candidate.name.clone(),
727                    RelationshipKind::Delegate,
728                )
729                .with_policy(spec.relationship_policy()),
730            );
731        }
732        let spec = TeamSpec {
733            name: format!("{}_team", inputs.harness),
734            description: format!("The {} harness and its members.", inputs.harness),
735            coordinator: inputs.harness.to_string(),
736            members: team_members,
737            relationships,
738            policy: self.policy,
739        };
740        let mut own: HashMap<String, Arc<dyn Agent>> =
741            agents.iter().map(|(name, agent)| (name.clone(), agent.clone())).collect();
742        own.insert(
743            inputs.harness.to_string(),
744            Arc::new(Coordinator { inner: inputs.coordinator.clone() }),
745        );
746        let registry: Arc<dyn TeamAgentRegistry> = Arc::new(HarnessMemberRegistry {
747            own,
748            discovered: self.discovered.iter().map(|candidate| candidate.name.clone()).collect(),
749            external: self.registry.clone(),
750        });
751        let compile_spec = spec.clone();
752        let compiled = block_on(async move { compile_spec.compile_with_registry(registry).await })?
753            .map_err(AdkError::from)?;
754        // Members run as the team runs them, under its budget and lifecycle.
755        let members = compiled
756            .sub_agents()
757            .iter()
758            .filter(|agent| agent.name() != inputs.harness)
759            .map(|agent| (agent.name().to_string(), agent.clone()))
760            .collect();
761        Ok(HarnessTeam { spec, root: Arc::new(compiled), members, own: agents })
762    }
763}
764
765/// Builds the agent of one member, wrapped so its delegation is audited and its state
766/// writes stay its own.
767fn build_member(member: &MemberSpec, inputs: &TeamInputs<'_>) -> Result<Arc<dyn Agent>> {
768    let inner: Arc<dyn Agent> = match &member.kind {
769        MemberKind::Local { instruction, model } => {
770            Arc::new(build_local(member, instruction, model.clone(), inputs)?)
771        }
772        #[cfg(feature = "vision")]
773        MemberKind::Perceiver { instruction, model } => {
774            vision_roles::check_perceiver(member, model.as_ref())?;
775            Arc::new(build_local(member, instruction, Some(model.clone()), inputs)?)
776        }
777        #[cfg(feature = "team-acp")]
778        MemberKind::Acp(config) => {
779            let mut config = config.clone();
780            // An ACP member works in the harness workspace, never wherever the process started.
781            config.working_dir = inputs.workspace.root().to_path_buf();
782            Arc::new(acp::AcpMember::new(&member.name, &member.description, config))
783        }
784        #[cfg(feature = "team-a2a")]
785        MemberKind::Remote(config) => {
786            let mut config = config.clone();
787            config.name = member.name.clone();
788            config.description = member.description.clone();
789            Arc::new(adk_server::a2a::RemoteA2aAgent::new(config))
790        }
791        MemberKind::Agent(agent) => agent.clone(),
792    };
793    Ok(Arc::new(MemberAgent::new(member, inner)))
794}
795
796fn build_local(
797    member: &MemberSpec,
798    instruction: &str,
799    model: Option<Arc<dyn Llm>>,
800    inputs: &TeamInputs<'_>,
801) -> Result<adk_agent::LlmAgent> {
802    let tools: Vec<Arc<dyn Tool>> = match &member.tools {
803        MemberTools::ReadOnly => inputs
804            .tools
805            .iter()
806            .filter(|tool| READ_ONLY_MEMBER_TOOLS.contains(&tool.name()))
807            .cloned()
808            .collect(),
809        MemberTools::Full => inputs.tools.to_vec(),
810        MemberTools::Custom(tools) => tools.clone(),
811        #[cfg(feature = "vision")]
812        MemberTools::LocalPerception(extra) => vision_roles::local_perception_tools(
813            member,
814            inputs.tools,
815            extra,
816            READ_ONLY_MEMBER_TOOLS,
817        )?,
818    };
819    let model = model.unwrap_or_else(|| inputs.model.clone());
820    let text = format!(
821        "{instruction}\n\nYou are the `{name}` member of a harness team, working in the workspace at \
822         {root}. You receive one request without the conversation that led to it; work on it with \
823         your own tools and report what you found or changed, with file paths. You cannot \
824         delegate or change the harness mode: the user's mode and approvals govern your tool \
825         calls.",
826        name = member.name,
827        root = inputs.workspace.root().display(),
828    );
829    let provider: InstructionProvider = Box::new(move |_ctx: Arc<dyn ReadonlyContext>| {
830        let text = text.clone();
831        Box::pin(async move { Ok(text) })
832    });
833    let mut builder = LlmAgentBuilder::new(member.name.clone())
834        .model(model.clone())
835        .description(member.description.clone())
836        .instruction_provider(provider)
837        .toolset(Arc::new(
838            HarnessToolset::member(tools, inputs.mode_store.clone(), inputs.default_mode)
839                .with_observers(inputs.observers)
840                .with_effort(inputs.effort),
841        ))
842        .max_iterations(member.max_iterations)
843        .tool_timeout(inputs.tool_timeout);
844    #[cfg(feature = "skills")]
845    if member.skills
846        && let crate::skills::SkillsWiring::Toolset(skills) =
847            crate::skills::wire(inputs.workspace.root(), inputs.skills)?
848    {
849        builder = builder.toolset(skills);
850    }
851    if let Some(schema) = &member.output_schema {
852        builder = builder.output_schema(schema.clone());
853    }
854    // The vision pack's evidence and privacy guardrail on a member as on the coordinator
855    // (spec 3.7 V-I4): a held remote call carries its egress image, and a remote member model
856    // sees only images the egress gate released.
857    #[cfg(feature = "vision")]
858    if let Some(vision) = inputs.vision {
859        builder = builder.before_tool_callback(vision.toolset.evidence_callback());
860        if model.data_locality().leaves_machine() {
861            let guardrail = vision.guardrail(model.as_ref(), inputs.vision_audit.clone());
862            builder = builder.before_model_callback(guardrail.before_model_callback());
863        }
864    }
865    builder.build()
866}
867
868/// The coordinator as its team member: the harness `LlmAgent` under a context that keeps
869/// the session state visible to its toolsets, which the team's own context does not
870/// forward.
871pub(crate) struct Coordinator {
872    pub(crate) inner: Arc<dyn Agent>,
873}
874
875#[async_trait]
876impl Agent for Coordinator {
877    fn name(&self) -> &str {
878        self.inner.name()
879    }
880
881    fn description(&self) -> &str {
882        self.inner.description()
883    }
884
885    fn sub_agents(&self) -> &[Arc<dyn Agent>] {
886        self.inner.sub_agents()
887    }
888
889    fn capabilities(&self) -> AgentCapabilities {
890        self.inner.capabilities()
891    }
892
893    fn supports_agent_transfer(&self) -> bool {
894        self.inner.supports_agent_transfer()
895    }
896
897    fn configure_run(&self, agent_name: &str, config: &mut RunConfig) {
898        self.inner.configure_run(agent_name, config);
899    }
900
901    async fn screen_user_input(&self, content: &Content) -> Result<Option<Content>> {
902        self.inner.screen_user_input(content).await
903    }
904
905    async fn close(&self) {
906        self.inner.close().await;
907    }
908
909    async fn prewarm(&self) -> Result<()> {
910        self.inner.prewarm().await
911    }
912
913    async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
914        self.inner.run(Arc::new(ScopedContext::new(ctx))).await
915    }
916}
917
918/// Stands in for a registry-discovered member until the registry resolves it.
919struct PendingRegistryAgent;
920
921#[async_trait]
922impl Agent for PendingRegistryAgent {
923    fn name(&self) -> &str {
924        "pending"
925    }
926
927    fn description(&self) -> &str {
928        ""
929    }
930
931    fn sub_agents(&self) -> &[Arc<dyn Agent>] {
932        &[]
933    }
934
935    async fn run(&self, _ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
936        Err(AdkError::agent("a discovered member runs only through its registry binding"))
937    }
938}
939
940/// The registry a harness team compiles against: the harness's own agents first, then the
941/// caller's registry for discovered members, each wrapped like any member.
942struct HarnessMemberRegistry {
943    own: HashMap<String, Arc<dyn Agent>>,
944    discovered: HashSet<String>,
945    external: Option<Arc<dyn TeamAgentRegistry>>,
946}
947
948const OWN_BINDING_PREFIX: &str = "adk-harness:";
949
950#[async_trait]
951impl TeamAgentRegistry for HarnessMemberRegistry {
952    async fn candidates(&self) -> Result<Vec<TeamAgentDescriptor>> {
953        let mut candidates: Vec<TeamAgentDescriptor> = self
954            .own
955            .iter()
956            .map(|(name, agent)| TeamAgentDescriptor {
957                binding: format!("{OWN_BINDING_PREFIX}{name}"),
958                name: name.clone(),
959                description: agent.description().to_string(),
960                capabilities: Vec::new(),
961                priority: i32::MAX,
962                version: None,
963                digest: None,
964                trust_labels: Vec::new(),
965                health: TeamAgentHealth::Healthy,
966                expires_at_ms: None,
967            })
968            .collect();
969        if let Some(external) = &self.external {
970            candidates.extend(
971                external
972                    .candidates()
973                    .await?
974                    .into_iter()
975                    .filter(|candidate| self.discovered.contains(&candidate.name)),
976            );
977        }
978        Ok(candidates)
979    }
980
981    async fn resolve(&self, binding: &str) -> Result<Arc<dyn Agent>> {
982        if let Some(name) = binding.strip_prefix(OWN_BINDING_PREFIX)
983            && let Some(agent) = self.own.get(name)
984        {
985            return Ok(agent.clone());
986        }
987        let external = self
988            .external
989            .as_ref()
990            .ok_or_else(|| AdkError::agent(format!("unknown member binding '{binding}'")))?;
991        let candidate = external
992            .candidates()
993            .await?
994            .into_iter()
995            .find(|candidate| candidate.binding == binding)
996            .ok_or_else(|| AdkError::agent(format!("unknown member binding '{binding}'")))?;
997        let agent = external.resolve(binding).await?;
998        let spec = MemberSpec {
999            name: candidate.name.clone(),
1000            description: candidate.description.clone(),
1001            kind: MemberKind::Agent(agent.clone()),
1002            tools: MemberTools::ReadOnly,
1003            skills: false,
1004            max_iterations: MEMBER_MAX_ITERATIONS,
1005            timeout: MEMBER_TIMEOUT,
1006            output_schema: None,
1007        };
1008        Ok(Arc::new(MemberAgent::new(&spec, agent)))
1009    }
1010
1011    async fn authorize(
1012        &self,
1013        member: &TeamMemberSpec,
1014        candidate: &TeamAgentDescriptor,
1015    ) -> Result<bool> {
1016        if candidate.binding.starts_with(OWN_BINDING_PREFIX) {
1017            return Ok(self.own.contains_key(&member.name) && candidate.name == member.name);
1018        }
1019        match &self.external {
1020            Some(external) if self.discovered.contains(&member.name) => {
1021                external.authorize(member, candidate).await
1022            }
1023            _ => Ok(false),
1024        }
1025    }
1026}
1027
1028/// A member as its delegations run it (spec 3.1 §7.10, §9.3).
1029///
1030/// Records `harness.member.spawned` before the member starts and `harness.member.finished`
1031/// when it ends. The member's state and artifact writes stay in its own isolated session:
1032/// they are kept in a state overlay the member reads and removed from the events its caller
1033/// merges, so nothing a member writes reaches the parent (`state_write_keys: []`).
1034struct MemberAgent {
1035    name: String,
1036    description: String,
1037    kind: &'static str,
1038    timeout_ms: u64,
1039    inner: Arc<dyn Agent>,
1040}
1041
1042impl MemberAgent {
1043    fn new(spec: &MemberSpec, inner: Arc<dyn Agent>) -> Self {
1044        Self {
1045            name: spec.name.clone(),
1046            description: spec.description.clone(),
1047            kind: spec.kind_label(),
1048            timeout_ms: u64::try_from(spec.timeout.as_millis()).unwrap_or(u64::MAX),
1049            inner,
1050        }
1051    }
1052}
1053
1054#[async_trait]
1055impl Agent for MemberAgent {
1056    fn name(&self) -> &str {
1057        &self.name
1058    }
1059
1060    fn description(&self) -> &str {
1061        &self.description
1062    }
1063
1064    fn sub_agents(&self) -> &[Arc<dyn Agent>] {
1065        &[]
1066    }
1067
1068    fn capabilities(&self) -> AgentCapabilities {
1069        self.inner.capabilities()
1070    }
1071
1072    fn supports_agent_transfer(&self) -> bool {
1073        false
1074    }
1075
1076    fn topology(&self) -> Option<AgentTopology> {
1077        self.inner.topology()
1078    }
1079
1080    fn configure_run(&self, _agent_name: &str, config: &mut RunConfig) {
1081        self.inner.configure_run(self.inner.name(), config);
1082    }
1083
1084    async fn screen_user_input(&self, content: &Content) -> Result<Option<Content>> {
1085        self.inner.screen_user_input(content).await
1086    }
1087
1088    async fn close(&self) {
1089        self.inner.close().await;
1090    }
1091
1092    async fn prewarm(&self) -> Result<()> {
1093        self.inner.prewarm().await
1094    }
1095
1096    async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
1097        let acting = ctx.acting_context();
1098        let audit = ctx.run_config().audit.clone().map(|trail| {
1099            HarnessAudit::new(trail, AuditActor::for_context(ctx.as_ref()), ctx.session_id())
1100        });
1101        let budget = ctx.run_config().budget_tracker.as_ref().map(|tracker| {
1102            let usage = tracker.usage();
1103            json!({
1104                "modelCalls": usage.model_calls,
1105                "totalTokens": usage.total_tokens,
1106                "costMicroUsd": usage.cost_micro_usd,
1107                "toolCalls": usage.tool_calls,
1108            })
1109        });
1110        let parent = acting.delegation_chain.last().map(|subject| subject.id.clone());
1111        let member_id = acting.agent.id.to_string();
1112        tracing::info!(
1113            harness.member = %self.name,
1114            member.kind = self.kind,
1115            delegation.depth = ctx.delegation_depth(),
1116            "member delegation started"
1117        );
1118        if let Some(audit) = &audit {
1119            audit
1120                .record(
1121                    "harness.member.spawned",
1122                    json!({
1123                        "parentAgentId": parent,
1124                        "memberAgentId": member_id,
1125                        "member": self.name,
1126                        "kind": self.kind,
1127                        "depth": ctx.delegation_depth(),
1128                        "timeoutMs": self.timeout_ms,
1129                        "budget": budget,
1130                    }),
1131                )
1132                .await?;
1133        }
1134        let started = Instant::now();
1135        let scoped = Arc::new(ScopedContext::new(ctx.clone()).with_state_overlay());
1136        let mut finish = FinishRecord {
1137            audit,
1138            member: self.name.clone(),
1139            member_id,
1140            kind: self.kind,
1141            started,
1142            outcome: None,
1143        };
1144        // The `harness.member` span of spec 3.1 §7.13, around everything the member does.
1145        #[cfg(feature = "observe")]
1146        let span = crate::observe::member_span(&self.name, ctx.invocation_id());
1147        #[cfg(not(feature = "observe"))]
1148        let span = tracing::Span::none();
1149        let mut inner = match self
1150            .inner
1151            .run(scoped.clone() as Arc<dyn InvocationContext>)
1152            .instrument(span.clone())
1153            .await
1154        {
1155            Ok(stream) => stream,
1156            Err(error) => {
1157                finish.outcome = Some("failed");
1158                finish.record().await;
1159                return Err(error);
1160            }
1161        };
1162        Ok(Box::pin(async_stream::stream! {
1163            let mut held = false;
1164            while let Some(item) = inner.next().instrument(span.clone()).await {
1165                match item {
1166                    Ok(mut event) => {
1167                        if let Some(overlay) = scoped.overlay() {
1168                            overlay.absorb(&event.actions.state_delta);
1169                        }
1170                        event.actions.state_delta.clear();
1171                        event.actions.artifact_delta.clear();
1172                        held |= event.actions.tool_confirmation.is_some();
1173                        yield Ok(event);
1174                    }
1175                    Err(error) => {
1176                        finish.outcome = Some("failed");
1177                        finish.record().await;
1178                        yield Err(error);
1179                        return;
1180                    }
1181                }
1182            }
1183            finish.outcome = Some(if held { "held" } else { "completed" });
1184            finish.record().await;
1185        }))
1186    }
1187}
1188
1189/// The `harness.member.finished` record of one delegation; a delegation dropped before it
1190/// ends, such as by its edge timeout, is recorded as `abandoned`.
1191struct FinishRecord {
1192    audit: Option<HarnessAudit>,
1193    member: String,
1194    member_id: String,
1195    kind: &'static str,
1196    started: Instant,
1197    outcome: Option<&'static str>,
1198}
1199
1200impl FinishRecord {
1201    fn fields(&self, outcome: &str) -> Value {
1202        json!({
1203            "memberAgentId": self.member_id,
1204            "member": self.member,
1205            "kind": self.kind,
1206            "outcome": outcome,
1207            "durationMs": u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX),
1208        })
1209    }
1210
1211    async fn record(&mut self) {
1212        let outcome = self.outcome.unwrap_or("completed");
1213        tracing::info!(harness.member = %self.member, member.outcome = outcome, "member delegation finished");
1214        if let Some(audit) = self.audit.take()
1215            && let Err(error) = audit.record("harness.member.finished", self.fields(outcome)).await
1216        {
1217            tracing::warn!(error = %error, "could not record harness.member.finished");
1218        }
1219    }
1220}
1221
1222impl Drop for FinishRecord {
1223    fn drop(&mut self) {
1224        if let Some(audit) = self.audit.take() {
1225            let fields = self.fields("abandoned");
1226            tracing::info!(harness.member = %self.member, "member delegation abandoned");
1227            if let Ok(handle) = tokio::runtime::Handle::try_current() {
1228                handle.spawn(async move {
1229                    if let Err(error) = audit.record("harness.member.finished", fields).await {
1230                        tracing::warn!(error = %error, "could not record harness.member.finished");
1231                    }
1232                });
1233            }
1234        }
1235    }
1236}
1237
1238#[cfg(feature = "team-acp")]
1239mod acp {
1240    //! ACP members (spec 3.1 §7.10): an ACP-compatible coding agent whose permission
1241    //! requests are decided on the governed path by the harness policy.
1242
1243    use std::sync::Arc;
1244
1245    use adk_acp::{AcpAgentConfig, PermissionDecision, PermissionPolicy, PermissionRequest};
1246    use adk_core::{
1247        AdkError, Agent, ApprovalScope, Content, Event, EventStream, GovernedCall,
1248        InvocationContext, Result, ToolAuthorization, ToolEffect, ToolGate, ToolOrigin,
1249    };
1250    use async_trait::async_trait;
1251    use serde_json::{Value, json};
1252
1253    /// Registered as `Read` for an ACP member's read and search permission requests.
1254    pub(super) const ACP_READ: &str = "acp_read";
1255    /// Registered as `Edit` for an ACP member's edit, delete and move requests with a path.
1256    pub(super) const ACP_EDIT: &str = "acp_edit";
1257
1258    pub(super) struct AcpMember {
1259        name: String,
1260        description: String,
1261        config: AcpAgentConfig,
1262    }
1263
1264    impl AcpMember {
1265        pub(super) fn new(name: &str, description: &str, config: AcpAgentConfig) -> Self {
1266            Self { name: name.to_string(), description: description.to_string(), config }
1267        }
1268    }
1269
1270    fn request_path(request: &PermissionRequest) -> Option<String> {
1271        let input = request.raw_input.as_ref()?;
1272        ["path", "file_path", "filePath", "abs_path", "absolutePath", "target_path"]
1273            .iter()
1274            .find_map(|key| input.get(*key).and_then(Value::as_str))
1275            .map(str::to_string)
1276    }
1277
1278    /// The governed call an ACP permission request is decided as.
1279    pub(super) fn governed_call(member: &str, request: &PermissionRequest) -> GovernedCall {
1280        use adk_acp::agent_client_protocol::v1::schema::ToolKind as AcpKind;
1281        let kind = format!("{:?}", request.kind).to_lowercase();
1282        let path = request_path(request);
1283        let mut args =
1284            json!({ "title": request.title, "kind": kind, "rawInput": request.raw_input });
1285        let (tool, effect, origin) = match (&request.kind, path) {
1286            (AcpKind::Read | AcpKind::Search, path) => {
1287                if let Some(path) = path {
1288                    args["path"] = Value::String(path);
1289                }
1290                (ACP_READ.to_string(), ToolEffect::ReadOnly, None)
1291            }
1292            (AcpKind::Edit | AcpKind::Delete | AcpKind::Move, Some(path)) => {
1293                args["path"] = Value::String(path);
1294                (ACP_EDIT.to_string(), ToolEffect::NonIdempotent, None)
1295            }
1296            _ => {
1297                let tool = format!("acp_{kind}");
1298                let origin = ToolOrigin::new(
1299                    format!("acp:{member}"),
1300                    &json!({ "name": tool, "kind": kind }),
1301                    None,
1302                );
1303                (tool, ToolEffect::NonIdempotent, Some(origin))
1304            }
1305        };
1306        let mut call = GovernedCall::new(tool, format!("acp-{}", request.tool_call_id), args);
1307        call.effect = effect;
1308        call.origin = origin;
1309        call
1310    }
1311
1312    /// Decides one permission request on the governed path, under the member's run
1313    /// config without its approval store: a call an ACP session cannot wait for is
1314    /// decided live by the confirmation handler, or refused.
1315    async fn decide(
1316        ctx: Arc<dyn InvocationContext>,
1317        member: String,
1318        request: PermissionRequest,
1319    ) -> PermissionDecision {
1320        let mut config = ctx.run_config().clone();
1321        config.approval_store = None;
1322        config.approval_service = None;
1323        let gate = ToolGate::new(
1324            &config,
1325            &member,
1326            ctx.invocation_id(),
1327            ApprovalScope::new(ctx.app_name(), ctx.user_id(), ctx.session_id()),
1328        )
1329        .with_acting_context(ctx.acting_context());
1330        let call = governed_call(&member, &request);
1331        let tool = call.tool_name.clone();
1332        match adk_core::authorize_tool_call(&gate, call).await {
1333            Ok(ToolAuthorization::Execute { .. }) => {
1334                tracing::info!(harness.member = %member, tool.name = %tool, "acp permission allowed");
1335                PermissionDecision::AllowOnce
1336            }
1337            Ok(ToolAuthorization::Refuse { reason, .. }) => {
1338                tracing::info!(harness.member = %member, tool.name = %tool, reason = %reason, "acp permission refused");
1339                PermissionDecision::Deny
1340            }
1341            Ok(ToolAuthorization::Pending { reason, .. }) => {
1342                tracing::info!(harness.member = %member, tool.name = %tool, reason = %reason, "acp permission needs a decision no one can give live; refused");
1343                PermissionDecision::Deny
1344            }
1345            Err(error) => {
1346                tracing::warn!(harness.member = %member, tool.name = %tool, error = %error, "acp permission refused");
1347                PermissionDecision::Deny
1348            }
1349        }
1350    }
1351
1352    #[async_trait]
1353    impl Agent for AcpMember {
1354        fn name(&self) -> &str {
1355            &self.name
1356        }
1357
1358        fn description(&self) -> &str {
1359            &self.description
1360        }
1361
1362        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
1363            &[]
1364        }
1365
1366        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
1367            ctx.run_config().check_governance()?;
1368            let prompt: String = ctx
1369                .user_content()
1370                .parts
1371                .iter()
1372                .filter_map(|part| part.text())
1373                .collect::<Vec<_>>()
1374                .join("\n");
1375            let member = self.name.clone();
1376            let bridge_ctx = ctx.clone();
1377            let policy = PermissionPolicy::async_custom(move |request| {
1378                decide(bridge_ctx.clone(), member.clone(), request)
1379            });
1380            let config = self.config.clone();
1381            let name = self.name.clone();
1382            let invocation = ctx.invocation_id().to_string();
1383            Ok(Box::pin(async_stream::stream! {
1384                match adk_acp::prompt_agent_with_policy(&config, &prompt, Arc::new(policy)).await {
1385                    Ok(text) => {
1386                        let mut event = Event::new(&invocation);
1387                        event.author = name.clone();
1388                        event.llm_response.content = Some(Content::new("model").with_text(text));
1389                        yield Ok(event);
1390                    }
1391                    Err(error) => {
1392                        yield Err(AdkError::agent(format!("ACP member '{name}' failed: {error}")));
1393                    }
1394                }
1395            }))
1396        }
1397    }
1398}
1399
1400/// The perceiver, reasoner and verifier presets and their build checks (spec 3.7 §7.12).
1401#[cfg(feature = "vision")]
1402mod vision_roles {
1403    use std::sync::Arc;
1404
1405    use adk_core::egress::ToolEgress;
1406    use adk_core::{AdkError, Llm, Result, Tool};
1407    use serde_json::json;
1408
1409    use super::{MEMBER_MAX_ITERATIONS, MEMBER_TIMEOUT, MemberKind, MemberSpec, MemberTools};
1410
1411    /// Refuses a perceiver on a remote model or holding tools other than the read and local
1412    /// perception tools.
1413    pub(super) fn check_perceiver(member: &MemberSpec, model: &dyn Llm) -> Result<()> {
1414        if model.data_locality().leaves_machine() {
1415            return Err(AdkError::config(format!(
1416                "the perceiver '{}' would send what it sees to the remote model '{}'; give it a \
1417                 model that runs on the device (adk-mistralrs, or a server at a loopback \
1418                 address), or bind adk-vision's model-free Perceiver as a MemberKind::Agent \
1419                 (spec 3.7 §7.12)",
1420                member.name,
1421                model.name()
1422            )));
1423        }
1424        match &member.tools {
1425            MemberTools::ReadOnly | MemberTools::LocalPerception(_) => Ok(()),
1426            MemberTools::Full | MemberTools::Custom(_) => Err(AdkError::config(format!(
1427                "the perceiver '{}' holds the read tools and the vision pack's on-device tools \
1428                 only: use MemberTools::LocalPerception for more tools that stay on the device",
1429                member.name
1430            ))),
1431        }
1432    }
1433
1434    /// The read tools, the vision pack's tools whose default backend is on the device, and
1435    /// `extra`, each refusing a call that would leave the device. `extra` tools that declare
1436    /// network use refuse the member.
1437    pub(super) fn local_perception_tools(
1438        member: &MemberSpec,
1439        tools: &[Arc<dyn Tool>],
1440        extra: &[Arc<dyn Tool>],
1441        read_only: &[&str],
1442    ) -> Result<Vec<Arc<dyn Tool>>> {
1443        for tool in extra {
1444            let egress = tool.egress(&json!({}));
1445            if egress != ToolEgress::None || adk_vision::VISION_TOOL_NAMES.contains(&tool.name()) {
1446                return Err(AdkError::config(format!(
1447                    "the member '{}' holds tools that stay on the device, and `{}` declares \
1448                     {egress:?}; give it only tools that declare ToolEgress::None (spec 3.7 \
1449                     §7.12)",
1450                    member.name,
1451                    tool.name()
1452                )));
1453            }
1454        }
1455        // A digest that names no image still routes the call, so its declared egress is the
1456        // default backend's.
1457        let probe = json!({ "image": format!("sha256:{}", "0".repeat(64)) });
1458        let selected = tools
1459            .iter()
1460            .filter(|tool| {
1461                read_only.contains(&tool.name())
1462                    || (adk_vision::VISION_TOOL_NAMES.contains(&tool.name())
1463                        && tool.egress(&probe) == ToolEgress::None)
1464            })
1465            .cloned()
1466            .chain(extra.iter().cloned())
1467            .map(|tool| {
1468                Arc::new(adk_vision::team::LocalOnlyTool::new(tool, member.name.clone()))
1469                    as Arc<dyn Tool>
1470            })
1471            .collect();
1472        Ok(selected)
1473    }
1474
1475    impl MemberSpec {
1476        /// A perceiver (spec 3.7 §7.12): sees full images on the device through the read
1477        /// tools and the vision pack's on-device tools, on `model`, which must run on the
1478        /// device. The build refuses a remote model and any tool that declares network use.
1479        ///
1480        /// # Example
1481        ///
1482        /// ```rust,ignore
1483        /// let perceiver = adk_harness::MemberSpec::perceiver(qwen3_vl_local);
1484        /// assert_eq!(perceiver.name, "perceiver");
1485        /// ```
1486        pub fn perceiver(model: Arc<dyn Llm>) -> Self {
1487            Self {
1488                name: "perceiver".to_string(),
1489                description: "Looks at an image on this device with the local vision tools and \
1490                              reports regions in source pixels, with labels and scores."
1491                    .to_string(),
1492                kind: MemberKind::Perceiver {
1493                    instruction: "Look at the image you are given with your vision tools, which \
1494                                  all run on this device. Report what you found as regions in \
1495                                  source pixels, with labels and scores, and the image digest."
1496                        .to_string(),
1497                    model,
1498                },
1499                tools: MemberTools::LocalPerception(Vec::new()),
1500                skills: false,
1501                max_iterations: MEMBER_MAX_ITERATIONS,
1502                timeout: MEMBER_TIMEOUT,
1503                output_schema: None,
1504            }
1505        }
1506
1507        /// A reasoner (spec 3.7 §7.12): answers over regions, measurements and crops the
1508        /// egress gate released, on `model`, usually a cloud model, with no tools. Its answer
1509        /// is an opinion (`adk_agent::opinion_schema`); a remote model gets the pack's privacy
1510        /// guardrail.
1511        ///
1512        /// # Example
1513        ///
1514        /// ```rust,ignore
1515        /// let reasoner = adk_harness::MemberSpec::reasoner(claude);
1516        /// assert!(reasoner.output_schema.is_some());
1517        /// ```
1518        pub fn reasoner(model: Arc<dyn Llm>) -> Self {
1519            Self {
1520                name: "reasoner".to_string(),
1521                description: "Judges a question over the regions, measurements and released \
1522                              crop digests it is given, and answers with a verdict, a \
1523                              confidence and why."
1524                    .to_string(),
1525                kind: MemberKind::Local {
1526                    instruction: "You never see the whole image: you get regions in source \
1527                                  pixels, measurements and the digests of redacted crops. Judge \
1528                                  the question and answer with a verdict, the class you judged, \
1529                                  a confidence from 0 to 1 and one sentence of rationale."
1530                        .to_string(),
1531                    model: Some(model),
1532                },
1533                tools: MemberTools::Custom(Vec::new()),
1534                skills: false,
1535                max_iterations: MEMBER_MAX_ITERATIONS,
1536                timeout: MEMBER_TIMEOUT,
1537                output_schema: Some(adk_agent::opinion_schema()),
1538            }
1539        }
1540
1541        /// A verifier (spec 3.7 §7.12): re-checks a claim against the pixels with the read
1542        /// tools and the vision pack's on-device tools, on `model` — by default another
1543        /// provider than the reasoner's, which the caller chooses. Its answer is an opinion.
1544        ///
1545        /// # Example
1546        ///
1547        /// ```rust,ignore
1548        /// let verifier = adk_harness::MemberSpec::verifier(nemotron);
1549        /// assert_eq!(verifier.name, "verifier");
1550        /// ```
1551        pub fn verifier(model: Arc<dyn Llm>) -> Self {
1552            Self {
1553                name: "verifier".to_string(),
1554                description: "Re-checks a claim about an image against its pixels with the \
1555                              local vision tools, and answers with a verdict, a confidence and \
1556                              why."
1557                    .to_string(),
1558                kind: MemberKind::Local {
1559                    instruction: "Re-check the claim you are given against the image with your \
1560                                  vision tools, which run on this device: look for the claimed \
1561                                  class over the claimed region. Answer with a verdict, the class, \
1562                                  a confidence from 0 to 1 and one sentence of rationale."
1563                        .to_string(),
1564                    model: Some(model),
1565                },
1566                tools: MemberTools::LocalPerception(Vec::new()),
1567                skills: false,
1568                max_iterations: MEMBER_MAX_ITERATIONS,
1569                timeout: MEMBER_TIMEOUT,
1570                output_schema: Some(adk_agent::opinion_schema()),
1571            }
1572        }
1573    }
1574}
1575
1576#[cfg(test)]
1577mod tests {
1578    use super::*;
1579
1580    #[test]
1581    fn the_defaults_are_explore_and_general_unless_replaced() {
1582        let plan = TeamPlan::prepare("harness", Vec::new(), true, None, None, &HashSet::new())
1583            .unwrap()
1584            .unwrap();
1585        assert_eq!(plan.names(), vec!["explore".to_string(), "general".to_string()]);
1586        let mut custom = MemberSpec::explore();
1587        custom.description = "mine".into();
1588        let plan = TeamPlan::prepare("harness", vec![custom], true, None, None, &HashSet::new())
1589            .unwrap()
1590            .unwrap();
1591        assert_eq!(plan.names(), vec!["general".to_string(), "explore".to_string()]);
1592        assert!(
1593            TeamPlan::prepare("harness", Vec::new(), false, None, None, &HashSet::new())
1594                .unwrap()
1595                .is_none()
1596        );
1597    }
1598
1599    #[test]
1600    fn member_names_cannot_collide() {
1601        let reserved: HashSet<String> = ["bash".to_string()].into_iter().collect();
1602        let mut named = MemberSpec::explore();
1603        named.name = "bash".into();
1604        assert!(TeamPlan::prepare("harness", vec![named], false, None, None, &reserved).is_err());
1605        let mut harness = MemberSpec::explore();
1606        harness.name = "harness".into();
1607        assert!(TeamPlan::prepare("harness", vec![harness], false, None, None, &reserved).is_err());
1608        assert!(
1609            TeamPlan::prepare(
1610                "harness",
1611                vec![MemberSpec::explore(), MemberSpec::explore()],
1612                false,
1613                None,
1614                None,
1615                &reserved
1616            )
1617            .is_err()
1618        );
1619        let mut untimed = MemberSpec::general();
1620        untimed.timeout = Duration::ZERO;
1621        assert!(TeamPlan::prepare("harness", vec![untimed], false, None, None, &reserved).is_err());
1622    }
1623}