Skip to main content

adk_agent/
team.rs

1//! Portable, validated multi-agent team composition.
2//!
3//! A [`TeamSpec`] is data: it names members, identifies the coordinator, and
4//! declares exact directed relationships. Compilation binds those names to any
5//! existing [`Agent`] implementations and produces a [`CompiledTeam`] root that
6//! can be passed directly to a Runner.
7
8use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
9use std::sync::Arc;
10
11#[cfg(feature = "team-tools")]
12use std::sync::{Mutex, OnceLock};
13
14use adk_core::{Agent, Content, EventStream, InvocationContext, Result, RunConfig};
15use async_trait::async_trait;
16use futures::StreamExt;
17use schemars::JsonSchema;
18use serde::{Deserialize, Serialize};
19use thiserror::Error;
20use tracing::Instrument;
21
22mod blackboard;
23mod discovery;
24mod evaluation;
25mod lifecycle;
26pub mod perception;
27mod runtime;
28mod templates;
29pub use blackboard::{
30    BlackboardHistoryPolicy, BlackboardPolicy, BlackboardSchedule, BlackboardSpec,
31    BlackboardTransition, CompiledBlackboardTeam,
32};
33pub use discovery::{
34    StaticTeamAgentRegistry, TeamAgentDescriptor, TeamAgentHealth, TeamAgentRegistry,
35};
36pub use evaluation::{
37    TeamExecutionAnalysis, TeamReplayError, analyze_team_execution, validate_team_replay,
38};
39pub use lifecycle::{
40    TeamLifecycleContext, TeamLifecycleDecision, TeamLifecycleHook, TeamLifecycleOutcome,
41    TeamLifecyclePhase,
42};
43pub use perception::{
44    PERCEIVER_CAPABILITY, REASONER_CAPABILITY, VERIFIER_CAPABILITY, opinion_schema,
45    perceiver_input_schema, reasoner_input_schema, verifier_input_schema,
46};
47use runtime::{EventDisposition, TeamEdgeStart, TeamRuntimeRegistry};
48pub use runtime::{
49    ResolvedTeamMember, TEAM_EDGE_ID_KEY, TEAM_EXECUTION_STATE_KEY, TEAM_ROOT_INVOCATION_KEY,
50    TeamEdgeExecution, TeamExecutionSnapshot, TeamExecutionStatus, TeamExecutionUsage,
51};
52pub use templates::{TeamArchitectureTemplate, TeamManagerBranch, WorkflowArchitectureTemplate};
53
54#[cfg(feature = "team-tools")]
55use adk_core::{RuntimeToolset, Tool, Toolset};
56#[cfg(feature = "team-tools")]
57use adk_tool::{
58    AgentTool, AgentToolFailureMode, AgentToolSessionSnapshot, AgentToolStateMergePolicy,
59};
60
61/// A portable team definition independent of concrete model or runtime types.
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
63#[serde(rename_all = "camelCase", deny_unknown_fields)]
64pub struct TeamSpec {
65    /// Stable name of the executable team root.
66    pub name: String,
67    /// Human-readable purpose of the team.
68    #[serde(default, skip_serializing_if = "String::is_empty")]
69    pub description: String,
70    /// Member that handles the initial request.
71    pub coordinator: String,
72    /// Named members expected at compilation time.
73    pub members: Vec<TeamMemberSpec>,
74    /// Exact directed handoff and delegation relationships.
75    #[serde(default, skip_serializing_if = "Vec::is_empty")]
76    pub relationships: Vec<TeamRelationship>,
77    /// Runtime policies enforced by the compiled team.
78    #[serde(default)]
79    pub policy: TeamPolicy,
80}
81
82/// Serializable metadata for one team member.
83#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
84#[serde(rename_all = "camelCase", deny_unknown_fields)]
85pub struct TeamMemberSpec {
86    /// Name used to bind the member to an [`Agent`].
87    pub name: String,
88    /// Optional portable description for design tools and documentation.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub description: Option<String>,
91    /// Capabilities a discovered binding must provide.
92    #[serde(default, skip_serializing_if = "Vec::is_empty")]
93    pub required_capabilities: Vec<String>,
94    /// Registry trust, version, and integrity constraints for this member.
95    #[serde(default)]
96    pub registry: TeamRegistryRequirement,
97}
98
99impl TeamMemberSpec {
100    /// Creates member metadata for `name`.
101    pub fn new(name: impl Into<String>) -> Self {
102        Self {
103            name: name.into(),
104            description: None,
105            required_capabilities: Vec::new(),
106            registry: TeamRegistryRequirement::default(),
107        }
108    }
109
110    /// Adds a portable description.
111    pub fn with_description(mut self, description: impl Into<String>) -> Self {
112        self.description = Some(description.into());
113        self
114    }
115
116    /// Requires all named capabilities when resolving this member dynamically.
117    pub fn with_capabilities(
118        mut self,
119        capabilities: impl IntoIterator<Item = impl Into<String>>,
120    ) -> Self {
121        self.required_capabilities = capabilities.into_iter().map(Into::into).collect();
122        self
123    }
124
125    /// Applies discovery-time trust and integrity constraints.
126    pub fn with_registry_requirement(mut self, requirement: TeamRegistryRequirement) -> Self {
127        self.registry = requirement;
128        self
129    }
130}
131
132/// Portable governance constraints for dynamically discovered bindings.
133#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
134#[serde(rename_all = "camelCase", deny_unknown_fields)]
135pub struct TeamRegistryRequirement {
136    /// Exact semantic or provider version required from the descriptor.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub version: Option<String>,
139    /// Exact immutable content/configuration digest required from the descriptor.
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub digest: Option<String>,
142    /// At least one of these trust labels must be advertised.
143    #[serde(default, skip_serializing_if = "Vec::is_empty")]
144    pub trust_labels: Vec<String>,
145    /// Reject degraded candidates as well as unavailable ones.
146    #[serde(default)]
147    pub require_healthy: bool,
148}
149
150/// One exact directed relationship between two team members.
151#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
152#[serde(rename_all = "camelCase", deny_unknown_fields)]
153pub struct TeamRelationship {
154    /// Calling or transferring member.
155    pub from: String,
156    /// Target member.
157    pub to: String,
158    /// Control-flow semantics of this edge.
159    pub kind: RelationshipKind,
160    /// Input, output, safety, and failure contract for this exact edge.
161    #[serde(default)]
162    pub policy: RelationshipPolicy,
163}
164
165impl TeamRelationship {
166    /// Creates a directed relationship.
167    pub fn new(from: impl Into<String>, to: impl Into<String>, kind: RelationshipKind) -> Self {
168        Self { from: from.into(), to: to.into(), kind, policy: RelationshipPolicy::default() }
169    }
170
171    /// Applies a contract to this relationship.
172    pub fn with_policy(mut self, policy: RelationshipPolicy) -> Self {
173        self.policy = policy;
174        self
175    }
176}
177
178/// Contract enforced for one exact relationship.
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
180#[serde(rename_all = "camelCase", deny_unknown_fields)]
181pub struct RelationshipPolicy {
182    /// Optional JSON Schema for arguments supplied to the relationship tool.
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub input_schema: Option<serde_json::Value>,
185    /// Optional JSON Schema validated against a delegate's returned value.
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub output_schema: Option<serde_json::Value>,
188    /// Override the team-wide context policy for this edge.
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub context: Option<TeamContextPolicy>,
191    /// History projection applied to delegated child sessions.
192    #[serde(default)]
193    pub history: TeamHistoryPolicy,
194    /// Exact state keys copied to delegated child sessions. Empty means all
195    /// keys allowed by the selected context policy.
196    #[serde(default, skip_serializing_if = "Vec::is_empty")]
197    pub state_keys: Vec<String>,
198    /// Exact state keys a delegated member may write back. Empty allows all keys.
199    #[serde(default, skip_serializing_if = "Vec::is_empty")]
200    pub state_write_keys: Vec<String>,
201    /// Merge behavior for delegated state writes.
202    #[serde(default)]
203    pub state_merge: TeamStateMergePolicy,
204    /// Allowed artifact-name prefixes written by a delegate. Empty allows all names.
205    #[serde(default, skip_serializing_if = "Vec::is_empty")]
206    pub artifact_prefixes: Vec<String>,
207    /// Durable recovery contract for an interrupted delegation.
208    #[serde(default)]
209    pub resume: TeamResumePolicy,
210    /// Per-attempt timeout in milliseconds.
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub timeout_ms: Option<u64>,
213    /// Whether invoking this edge requires a tool confirmation decision.
214    #[serde(default)]
215    pub approval: RelationshipApprovalPolicy,
216    /// Failure handling for this edge.
217    #[serde(default)]
218    pub failure: RelationshipFailureStrategy,
219    /// Optional circuit breaker for repeatedly failing delegate calls.
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub circuit_breaker: Option<CircuitBreakerPolicy>,
222}
223
224/// Conversation history exposed to a delegated member.
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
226#[serde(rename_all = "camelCase", tag = "mode")]
227pub enum TeamHistoryPolicy {
228    /// Derive history behavior from the selected context policy.
229    #[default]
230    Inherit,
231    /// Do not copy conversation history.
232    None,
233    /// Copy the full available history.
234    Full,
235    /// Copy at most the most recent `max_events` messages.
236    Last {
237        /// Maximum number of messages copied.
238        max_events: usize,
239    },
240}
241
242/// Approval requirement for a relationship invocation.
243#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
244#[serde(rename_all = "camelCase")]
245pub enum RelationshipApprovalPolicy {
246    /// Invoke without a relationship-specific approval gate.
247    #[default]
248    Never,
249    /// Reuse the runtime's exact-call tool confirmation mechanism.
250    Required,
251}
252
253/// Failure handling for an exact relationship.
254#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
255#[serde(rename_all = "camelCase", tag = "strategy")]
256pub enum RelationshipFailureStrategy {
257    /// Use the team-wide failure policy.
258    #[default]
259    Inherit,
260    /// Propagate the member failure.
261    Propagate,
262    /// Return a structured error to the delegating member.
263    ReturnError,
264    /// Retry the same target with bounded attempts and backoff.
265    Retry {
266        /// Total attempts, including the initial attempt.
267        max_attempts: u32,
268        /// Delay between attempts in milliseconds.
269        #[serde(default)]
270        backoff_ms: u64,
271    },
272    /// Transfer the failed operation to another explicitly declared target.
273    Fallback {
274        /// Exact fallback member name.
275        target: String,
276    },
277    /// Retry first, then use an explicitly declared fallback target.
278    RetryThenFallback {
279        /// Total attempts against the primary target.
280        max_attempts: u32,
281        /// Delay between attempts in milliseconds.
282        #[serde(default)]
283        backoff_ms: u64,
284        /// Exact fallback member name.
285        target: String,
286    },
287}
288
289/// Opens an edge circuit after repeated failures.
290#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
291#[serde(rename_all = "camelCase", deny_unknown_fields)]
292pub struct CircuitBreakerPolicy {
293    /// Consecutive failures required to open the circuit.
294    pub failure_threshold: u32,
295    /// Cooldown before a half-open probe, in milliseconds.
296    pub reset_after_ms: u64,
297}
298
299/// Control-flow semantics for a team relationship.
300#[derive(
301    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
302)]
303#[serde(rename_all = "camelCase")]
304pub enum RelationshipKind {
305    /// Invoke the target as a tool, receive its result, and resume the caller.
306    Delegate,
307    /// Transfer active control to the target; the caller does not resume.
308    Handoff,
309}
310
311/// Policies applied uniformly by a compiled team.
312#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
313#[serde(rename_all = "camelCase", deny_unknown_fields)]
314pub struct TeamPolicy {
315    /// Maximum handoffs in one Runner invocation.
316    pub max_transfer_depth: u32,
317    /// Maximum nested agent-as-tool calls.
318    pub max_delegation_depth: u32,
319    /// Maximum simultaneous delegate calls from a member.
320    pub max_concurrent_delegations: usize,
321    /// Context exposed to delegated members.
322    pub context: TeamContextPolicy,
323    /// How member failures surface to callers.
324    pub failure: TeamFailurePolicy,
325    /// Aggregate resource limits for one root invocation.
326    #[serde(default)]
327    pub budget: TeamBudget,
328    /// Conditions that terminate a running team cleanly.
329    #[serde(default)]
330    pub termination: TeamTerminationPolicy,
331}
332
333impl Default for TeamPolicy {
334    fn default() -> Self {
335        Self {
336            max_transfer_depth: 8,
337            max_delegation_depth: 4,
338            max_concurrent_delegations: 4,
339            context: TeamContextPolicy::Shared,
340            failure: TeamFailurePolicy::Propagate,
341            budget: TeamBudget::default(),
342            termination: TeamTerminationPolicy::default(),
343        }
344    }
345}
346
347/// Aggregate limits enforced across a root team invocation and its delegates.
348///
349/// Model calls, tokens, cost, tool calls and wall time are enforced by an
350/// [`adk_core::BudgetTracker`] shared by every member: a member stops before
351/// the model or tool call that would start past a reached limit. The tracker
352/// counts against the run's [`adk_core::RunBudget`] as well, so the stricter
353/// of the two applies. Events, delegations and handoffs are counted from the
354/// team's own events; partial streaming chunks never count.
355#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
356#[serde(rename_all = "camelCase", deny_unknown_fields)]
357pub struct TeamBudget {
358    /// Maximum emitted non-partial events.
359    #[serde(default, skip_serializing_if = "Option::is_none")]
360    pub max_events: Option<u64>,
361    /// Maximum model calls.
362    #[serde(default, skip_serializing_if = "Option::is_none")]
363    pub max_model_requests: Option<u64>,
364    /// Maximum tool calls dispatched.
365    #[serde(default, skip_serializing_if = "Option::is_none")]
366    pub max_tool_calls: Option<u64>,
367    /// Maximum total input and output tokens.
368    #[serde(default, skip_serializing_if = "Option::is_none")]
369    pub max_tokens: Option<u64>,
370    /// Maximum cost in millionths of a US dollar, from the providers' priced usage.
371    ///
372    /// A model response with no known cost stops the team unless
373    /// [`allow_unpriced_models`](Self::allow_unpriced_models) is set.
374    #[serde(default, skip_serializing_if = "Option::is_none")]
375    pub max_cost_microusd: Option<u64>,
376    /// Maximum delegation relationship executions.
377    #[serde(default, skip_serializing_if = "Option::is_none")]
378    pub max_delegations: Option<u64>,
379    /// Maximum handoff relationship executions.
380    #[serde(default, skip_serializing_if = "Option::is_none")]
381    pub max_handoffs: Option<u64>,
382    /// Maximum wall-clock duration in milliseconds.
383    #[serde(default, skip_serializing_if = "Option::is_none")]
384    pub max_wall_time_ms: Option<u64>,
385    /// Count model responses with no known cost as zero cost under
386    /// [`max_cost_microusd`](Self::max_cost_microusd).
387    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
388    pub allow_unpriced_models: bool,
389}
390
391/// Clean termination conditions independent from hard resource budgets.
392#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
393#[serde(rename_all = "camelCase", deny_unknown_fields)]
394pub struct TeamTerminationPolicy {
395    /// End when an event requests human escalation.
396    pub stop_on_escalation: bool,
397    /// End after a final response authored by one of these members.
398    #[serde(default, skip_serializing_if = "Vec::is_empty")]
399    pub final_authors: Vec<String>,
400    /// End when emitted text contains one of these exact markers.
401    #[serde(default, skip_serializing_if = "Vec::is_empty")]
402    pub text_markers: Vec<String>,
403}
404
405impl Default for TeamTerminationPolicy {
406    fn default() -> Self {
407        Self { stop_on_escalation: true, final_authors: Vec::new(), text_markers: Vec::new() }
408    }
409}
410
411/// Context sharing policy for agent-as-tool delegation.
412#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
413#[serde(rename_all = "camelCase")]
414pub enum TeamContextPolicy {
415    /// Start delegates with an empty history/state snapshot and no memory.
416    Isolated,
417    /// Snapshot parent history/state and forward memory, artifacts, and shared state.
418    Shared,
419}
420
421/// Merge policy for state returned by an exact delegation edge.
422#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
423#[serde(rename_all = "camelCase")]
424pub enum TeamStateMergePolicy {
425    /// Reject writes whose parent value changed after delegation began.
426    #[default]
427    RejectConflicts,
428    /// Apply child writes with last-writer-wins semantics.
429    Overwrite,
430}
431
432/// Recovery contract for a delegation that was running when execution stopped.
433#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
434#[serde(rename_all = "camelCase", tag = "strategy")]
435pub enum TeamResumePolicy {
436    /// Never replay an unresolved delegation automatically.
437    #[default]
438    FailClosed,
439    /// Require the target to advertise checkpoint resume and let the durable
440    /// host provide a continuation token stored under this state key.
441    RequireCheckpoint {
442        /// Session-state key holding the opaque target continuation token.
443        token_state_key: String,
444    },
445}
446
447/// Safe action a durable host can take for a restored execution receipt.
448#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
449#[serde(rename_all = "camelCase", tag = "action")]
450pub enum TeamResumePlan {
451    /// No relationship was active; start or continue with the coordinator.
452    Coordinator,
453    /// Resume control at an active handoff target.
454    Handoff {
455        /// Active relationship execution.
456        edge_id: String,
457        /// Member that owns control.
458        target: String,
459    },
460    /// Resume an unresolved delegate through its checkpoint-aware host adapter.
461    DelegateCheckpoint {
462        /// Active relationship execution.
463        edge_id: String,
464        /// Delegated member.
465        target: String,
466        /// State key containing the opaque continuation token.
467        token_state_key: String,
468    },
469    /// The active delegation cannot be replayed safely.
470    UnsafeDelegate {
471        /// Active relationship execution.
472        edge_id: String,
473        /// Delegated member.
474        target: String,
475        /// Explanation suitable for an operator or durable scheduler.
476        reason: String,
477    },
478}
479
480/// Failure behavior for team relationships.
481#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
482#[serde(rename_all = "camelCase")]
483pub enum TeamFailurePolicy {
484    /// Surface member and timeout failures as failed tool or agent executions.
485    Propagate,
486    /// Return delegate failures as structured tool results; handoff failures still propagate.
487    ReturnDelegateError,
488}
489
490/// Validation or compilation failure for a [`TeamSpec`].
491#[derive(Debug, Error, PartialEq, Eq)]
492pub enum TeamError {
493    /// A required name is empty.
494    #[error("team {field} must not be empty")]
495    EmptyName {
496        /// Name-bearing field that failed validation.
497        field: &'static str,
498    },
499    /// A member name occurs more than once.
500    #[error("duplicate team member '{0}'")]
501    DuplicateMember(String),
502    /// The team root name collides with a member name.
503    #[error("team name '{0}' must not also be a member name")]
504    TeamNameCollision(String),
505    /// The coordinator is not declared as a member.
506    #[error("team coordinator '{0}' is not a declared member")]
507    UnknownCoordinator(String),
508    /// A relationship references a missing member.
509    #[error("relationship {endpoint} references unknown member '{name}'")]
510    UnknownRelationshipMember {
511        /// Whether the source or target was invalid.
512        endpoint: &'static str,
513        /// Invalid member name.
514        name: String,
515    },
516    /// A member points to itself.
517    #[error("self relationship is not allowed for member '{0}'")]
518    SelfRelationship(String),
519    /// The same semantic edge occurs more than once.
520    #[error("duplicate {kind:?} relationship from '{from}' to '{to}'")]
521    DuplicateRelationship {
522        /// Source member.
523        from: String,
524        /// Target member.
525        to: String,
526        /// Repeated relationship kind.
527        kind: RelationshipKind,
528    },
529    /// The directed topology contains a cycle.
530    #[error("team topology contains a cycle involving '{0}'")]
531    CyclicTopology(String),
532    /// A member cannot be reached from the coordinator.
533    #[error("team member '{0}' is unreachable from the coordinator")]
534    UnreachableMember(String),
535    /// A depth or concurrency policy is zero.
536    #[error("team policy '{0}' must be greater than zero")]
537    InvalidPolicy(&'static str),
538    /// A member capability requirement is empty or repeated.
539    #[error("invalid capability requirement for member '{member}': {reason}")]
540    InvalidMemberCapability {
541        /// Member carrying the invalid requirement.
542        member: String,
543        /// Actionable validation failure.
544        reason: String,
545    },
546    /// An exact relationship contract is invalid.
547    #[error("invalid relationship policy from '{from}' to '{to}': {reason}")]
548    InvalidRelationshipPolicy {
549        /// Relationship source.
550        from: String,
551        /// Relationship target.
552        to: String,
553        /// Actionable validation failure.
554        reason: String,
555    },
556    /// A team budget contains a zero bound.
557    #[error("team budget '{0}' must be greater than zero when configured")]
558    InvalidBudget(&'static str),
559    /// A termination rule names an undeclared member.
560    #[error("team termination final author '{0}' is not a declared member")]
561    UnknownTerminationAuthor(String),
562    /// No concrete agent was registered for a member.
563    #[error("no agent registered for team member '{0}'")]
564    MissingAgent(String),
565    /// More than one concrete agent has the same name.
566    #[error("duplicate agent binding for team member '{0}'")]
567    DuplicateAgentBinding(String),
568    /// A concrete agent was supplied but is not declared by the specification.
569    #[error("agent binding '{0}' is not declared by the team")]
570    UnexpectedAgentBinding(String),
571    /// A bound source agent cannot enforce a declared relationship.
572    #[error(
573        "agent '{member}' does not support required runtime capability '{capability}' for {relationship}"
574    )]
575    UnsupportedAgentCapability {
576        /// Portable member name.
577        member: String,
578        /// Missing execution-plane capability.
579        capability: &'static str,
580        /// Relationship that requires the capability.
581        relationship: String,
582    },
583    /// Delegation support was not compiled into `adk-agent`.
584    #[error("TeamSpec contains Delegate relationships; enable the adk-agent 'team-tools' feature")]
585    DelegationFeatureDisabled,
586    /// A dynamic registry operation failed.
587    #[error("team registry failed: {0}")]
588    Registry(String),
589    /// No registry candidate satisfies a portable member requirement.
590    #[error(
591        "no registry candidate for team member '{member}' with required capabilities {capabilities:?}"
592    )]
593    NoRegistryCandidate {
594        /// Portable member name.
595        member: String,
596        /// Required capability identifiers.
597        capabilities: Vec<String>,
598    },
599    /// A persisted execution receipt cannot be restored into this compiled team.
600    #[error("incompatible team execution snapshot: {0}")]
601    IncompatibleExecutionSnapshot(String),
602}
603
604/// Structured failure produced while a compiled team is executing.
605#[derive(Debug, Error)]
606pub enum TeamRuntimeError {
607    /// A lifecycle hook failed.
608    #[error("team lifecycle hook '{hook}' failed during {phase:?}: {message}")]
609    LifecycleHook {
610        /// Hook name.
611        hook: String,
612        /// Lifecycle boundary.
613        phase: TeamLifecyclePhase,
614        /// Hook failure.
615        message: String,
616    },
617    /// A lifecycle policy denied an operation.
618    #[error("team policy denied {operation}: {reason}")]
619    PolicyDenied {
620        /// Operation being denied.
621        operation: String,
622        /// Auditable policy reason.
623        reason: String,
624    },
625    /// A configured aggregate budget was exhausted.
626    #[error("team budget exceeded: {0}")]
627    BudgetExceeded(String),
628    /// A persisted delegation cannot be replayed safely.
629    #[error("unsafe team resume: {0}")]
630    UnsafeResume(String),
631    /// Delegated state violated its write/merge contract.
632    #[error("team state policy rejected delegated output: {0}")]
633    StatePolicy(String),
634}
635
636impl From<TeamRuntimeError> for adk_core::AdkError {
637    fn from(error: TeamRuntimeError) -> Self {
638        use adk_core::{AdkError, ErrorCategory, ErrorComponent};
639        let (category, code) = match &error {
640            TeamRuntimeError::LifecycleHook { .. } => {
641                (ErrorCategory::Internal, "agent.team.lifecycle_hook_failed")
642            }
643            TeamRuntimeError::PolicyDenied { .. } => {
644                (ErrorCategory::Forbidden, "agent.team.policy_denied")
645            }
646            TeamRuntimeError::BudgetExceeded(_) => {
647                (ErrorCategory::ResourceExhausted, "agent.team.budget_exceeded")
648            }
649            TeamRuntimeError::UnsafeResume(_) => {
650                (ErrorCategory::Unsupported, "agent.team.resume_unsafe")
651            }
652            TeamRuntimeError::StatePolicy(_) => {
653                (ErrorCategory::InvalidInput, "agent.team.state_policy_violation")
654            }
655        };
656        AdkError::new(ErrorComponent::Agent, category, code, error.to_string())
657    }
658}
659
660impl From<TeamError> for adk_core::AdkError {
661    fn from(error: TeamError) -> Self {
662        use adk_core::{AdkError, ErrorCategory, ErrorComponent, ErrorDetails};
663
664        let message = error.to_string();
665        let (category, code) = match &error {
666            TeamError::MissingAgent(_)
667            | TeamError::NoRegistryCandidate { .. }
668            | TeamError::UnknownRelationshipMember { .. }
669            | TeamError::UnknownCoordinator(_) => {
670                (ErrorCategory::NotFound, "agent.team.binding_not_found")
671            }
672            TeamError::UnsupportedAgentCapability { .. } | TeamError::DelegationFeatureDisabled => {
673                (ErrorCategory::Unsupported, "agent.team.capability_unsupported")
674            }
675            TeamError::Registry(_) => (ErrorCategory::Unavailable, "agent.team.registry_failed"),
676            TeamError::IncompatibleExecutionSnapshot(_) => {
677                (ErrorCategory::InvalidInput, "agent.team.snapshot_incompatible")
678            }
679            TeamError::EmptyName { .. }
680            | TeamError::DuplicateMember(_)
681            | TeamError::TeamNameCollision(_)
682            | TeamError::SelfRelationship(_)
683            | TeamError::DuplicateRelationship { .. }
684            | TeamError::CyclicTopology(_)
685            | TeamError::UnreachableMember(_)
686            | TeamError::InvalidPolicy(_)
687            | TeamError::InvalidMemberCapability { .. }
688            | TeamError::InvalidRelationshipPolicy { .. }
689            | TeamError::InvalidBudget(_)
690            | TeamError::UnknownTerminationAuthor(_)
691            | TeamError::DuplicateAgentBinding(_)
692            | TeamError::UnexpectedAgentBinding(_) => {
693                (ErrorCategory::InvalidInput, "agent.team.invalid_spec")
694            }
695        };
696        let mut details = ErrorDetails::default();
697        details
698            .metadata
699            .insert("teamError".to_string(), serde_json::Value::String(format!("{error:?}")));
700        AdkError::new(ErrorComponent::Agent, category, code, message).with_details(details)
701    }
702}
703
704impl TeamSpec {
705    /// Validates names, policies, edges, acyclicity, and coordinator reachability.
706    pub fn validate(&self) -> std::result::Result<(), TeamError> {
707        if self.name.trim().is_empty() {
708            return Err(TeamError::EmptyName { field: "name" });
709        }
710        if self.coordinator.trim().is_empty() {
711            return Err(TeamError::EmptyName { field: "coordinator" });
712        }
713        if self.policy.max_transfer_depth == 0 {
714            return Err(TeamError::InvalidPolicy("maxTransferDepth"));
715        }
716        if self.policy.max_delegation_depth == 0 {
717            return Err(TeamError::InvalidPolicy("maxDelegationDepth"));
718        }
719        if self.policy.max_concurrent_delegations == 0 {
720            return Err(TeamError::InvalidPolicy("maxConcurrentDelegations"));
721        }
722
723        let mut names = BTreeSet::new();
724        for member in &self.members {
725            if member.name.trim().is_empty() {
726                return Err(TeamError::EmptyName { field: "member.name" });
727            }
728            if !names.insert(member.name.as_str()) {
729                return Err(TeamError::DuplicateMember(member.name.clone()));
730            }
731            let mut capabilities = BTreeSet::new();
732            for capability in &member.required_capabilities {
733                if capability.trim().is_empty() {
734                    return Err(TeamError::InvalidMemberCapability {
735                        member: member.name.clone(),
736                        reason: "capability names must not be empty".to_string(),
737                    });
738                }
739                if !capabilities.insert(capability.as_str()) {
740                    return Err(TeamError::InvalidMemberCapability {
741                        member: member.name.clone(),
742                        reason: format!("duplicate capability '{capability}'"),
743                    });
744                }
745            }
746            if member.registry.version.as_ref().is_some_and(|value| value.trim().is_empty()) {
747                return Err(TeamError::InvalidMemberCapability {
748                    member: member.name.clone(),
749                    reason: "registry version must not be empty".to_string(),
750                });
751            }
752            if member.registry.digest.as_ref().is_some_and(|value| value.trim().is_empty()) {
753                return Err(TeamError::InvalidMemberCapability {
754                    member: member.name.clone(),
755                    reason: "registry digest must not be empty".to_string(),
756                });
757            }
758            let mut trust_labels = BTreeSet::new();
759            for label in &member.registry.trust_labels {
760                if label.trim().is_empty() || !trust_labels.insert(label.as_str()) {
761                    return Err(TeamError::InvalidMemberCapability {
762                        member: member.name.clone(),
763                        reason: format!("invalid or duplicate registry trust label '{label}'"),
764                    });
765                }
766            }
767        }
768        if !names.contains(self.coordinator.as_str()) {
769            return Err(TeamError::UnknownCoordinator(self.coordinator.clone()));
770        }
771        if names.contains(self.name.as_str()) {
772            return Err(TeamError::TeamNameCollision(self.name.clone()));
773        }
774
775        let mut edges = BTreeSet::new();
776        let mut adjacency: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
777        for relationship in &self.relationships {
778            if !names.contains(relationship.from.as_str()) {
779                return Err(TeamError::UnknownRelationshipMember {
780                    endpoint: "source",
781                    name: relationship.from.clone(),
782                });
783            }
784            if !names.contains(relationship.to.as_str()) {
785                return Err(TeamError::UnknownRelationshipMember {
786                    endpoint: "target",
787                    name: relationship.to.clone(),
788                });
789            }
790            if relationship.from == relationship.to {
791                return Err(TeamError::SelfRelationship(relationship.from.clone()));
792            }
793            let edge = (relationship.from.as_str(), relationship.to.as_str(), relationship.kind);
794            if !edges.insert(edge) {
795                return Err(TeamError::DuplicateRelationship {
796                    from: relationship.from.clone(),
797                    to: relationship.to.clone(),
798                    kind: relationship.kind,
799                });
800            }
801            relationship.validate_policy(&names, &self.relationships)?;
802            adjacency.entry(relationship.from.as_str()).or_default().push(relationship.to.as_str());
803        }
804
805        for (name, limit) in [
806            ("maxEvents", self.policy.budget.max_events),
807            ("maxModelRequests", self.policy.budget.max_model_requests),
808            ("maxToolCalls", self.policy.budget.max_tool_calls),
809            ("maxTokens", self.policy.budget.max_tokens),
810            ("maxCostMicrousd", self.policy.budget.max_cost_microusd),
811            ("maxDelegations", self.policy.budget.max_delegations),
812            ("maxHandoffs", self.policy.budget.max_handoffs),
813            ("maxWallTimeMs", self.policy.budget.max_wall_time_ms),
814        ] {
815            if limit == Some(0) {
816                return Err(TeamError::InvalidBudget(name));
817            }
818        }
819        for author in &self.policy.termination.final_authors {
820            if !names.contains(author.as_str()) {
821                return Err(TeamError::UnknownTerminationAuthor(author.clone()));
822            }
823        }
824        if self.policy.termination.text_markers.iter().any(|marker| marker.is_empty()) {
825            return Err(TeamError::InvalidPolicy("termination.textMarkers"));
826        }
827
828        fn visit<'a>(
829            node: &'a str,
830            adjacency: &BTreeMap<&'a str, Vec<&'a str>>,
831            visiting: &mut HashSet<&'a str>,
832            visited: &mut HashSet<&'a str>,
833        ) -> std::result::Result<(), TeamError> {
834            if visiting.contains(node) {
835                return Err(TeamError::CyclicTopology(node.to_string()));
836            }
837            if !visited.insert(node) {
838                return Ok(());
839            }
840            visiting.insert(node);
841            for target in adjacency.get(node).into_iter().flatten() {
842                visit(target, adjacency, visiting, visited)?;
843            }
844            visiting.remove(node);
845            Ok(())
846        }
847
848        let mut visiting = HashSet::new();
849        let mut reachable = HashSet::new();
850        visit(&self.coordinator, &adjacency, &mut visiting, &mut reachable)?;
851        if let Some(unreachable) = names.iter().find(|name| !reachable.contains(**name)) {
852            return Err(TeamError::UnreachableMember((*unreachable).to_string()));
853        }
854        Ok(())
855    }
856
857    /// Binds this spec to concrete agents and returns an executable team root.
858    ///
859    /// Any [`Agent`] implementation can be a member. Delegate edges additionally
860    /// require the `team-tools` feature, which lowers them to `AgentTool`s.
861    pub fn compile(
862        &self,
863        agents: impl IntoIterator<Item = Arc<dyn Agent>>,
864    ) -> std::result::Result<CompiledTeam, TeamError> {
865        self.validate()?;
866        #[cfg(not(feature = "team-tools"))]
867        if self.relationships.iter().any(|edge| edge.kind == RelationshipKind::Delegate) {
868            return Err(TeamError::DelegationFeatureDisabled);
869        }
870        self.compile_inner(agents, Vec::new())
871    }
872
873    /// Binds concrete agents and ordered async team lifecycle hooks.
874    ///
875    /// Generic Runner plugins continue to apply normally. These hooks add
876    /// policy and observation at exact member and relationship boundaries.
877    pub fn compile_with_hooks(
878        &self,
879        agents: impl IntoIterator<Item = Arc<dyn Agent>>,
880        hooks: impl IntoIterator<Item = Arc<dyn TeamLifecycleHook>>,
881    ) -> std::result::Result<CompiledTeam, TeamError> {
882        self.validate()?;
883        #[cfg(not(feature = "team-tools"))]
884        if self.relationships.iter().any(|edge| edge.kind == RelationshipKind::Delegate) {
885            return Err(TeamError::DelegationFeatureDisabled);
886        }
887        self.compile_inner(agents, hooks.into_iter().collect())
888    }
889
890    fn compile_inner(
891        &self,
892        agents: impl IntoIterator<Item = Arc<dyn Agent>>,
893        hooks: Vec<Arc<dyn TeamLifecycleHook>>,
894    ) -> std::result::Result<CompiledTeam, TeamError> {
895        let declared: HashSet<&str> =
896            self.members.iter().map(|member| member.name.as_str()).collect();
897        let mut registry: HashMap<String, Arc<dyn Agent>> = HashMap::new();
898        for agent in agents {
899            let name = agent.name().to_string();
900            if !declared.contains(name.as_str()) {
901                return Err(TeamError::UnexpectedAgentBinding(name));
902            }
903            if registry.insert(name.clone(), agent).is_some() {
904                return Err(TeamError::DuplicateAgentBinding(name));
905            }
906        }
907        for member in &self.members {
908            if !registry.contains_key(&member.name) {
909                return Err(TeamError::MissingAgent(member.name.clone()));
910            }
911        }
912
913        let roster: Vec<ResolvedTeamMember> = self
914            .members
915            .iter()
916            .map(|member| ResolvedTeamMember {
917                member: member.name.clone(),
918                binding: member.name.clone(),
919                capabilities: member.required_capabilities.clone(),
920                version: None,
921                digest: None,
922                trust_labels: Vec::new(),
923            })
924            .collect();
925        self.compile_registry(registry, roster, hooks)
926    }
927
928    fn compile_registry(
929        &self,
930        registry: HashMap<String, Arc<dyn Agent>>,
931        roster: Vec<ResolvedTeamMember>,
932        hooks: Vec<Arc<dyn TeamLifecycleHook>>,
933    ) -> std::result::Result<CompiledTeam, TeamError> {
934        for relationship in &self.relationships {
935            let source = registry
936                .get(&relationship.from)
937                .expect("validated compilation has every member binding");
938            let capabilities = source.capabilities();
939            let (supported, capability) = match relationship.kind {
940                RelationshipKind::Delegate => (capabilities.runtime_tools, "runtimeTools"),
941                RelationshipKind::Handoff => (capabilities.handoff, "handoff"),
942            };
943            if !supported {
944                return Err(TeamError::UnsupportedAgentCapability {
945                    member: relationship.from.clone(),
946                    capability,
947                    relationship: format!("{:?} edge to '{}'", relationship.kind, relationship.to),
948                });
949            }
950            if relationship.policy.approval == RelationshipApprovalPolicy::Required
951                && !capabilities.relationship_confirmation
952            {
953                return Err(TeamError::UnsupportedAgentCapability {
954                    member: relationship.from.clone(),
955                    capability: "relationshipConfirmation",
956                    relationship: format!(
957                        "approved {:?} edge to '{}'",
958                        relationship.kind, relationship.to
959                    ),
960                });
961            }
962            if matches!(relationship.policy.resume, TeamResumePolicy::RequireCheckpoint { .. }) {
963                let target = registry
964                    .get(&relationship.to)
965                    .expect("validated compilation has every member binding");
966                if !target.capabilities().checkpoint_resume {
967                    return Err(TeamError::UnsupportedAgentCapability {
968                        member: relationship.to.clone(),
969                        capability: "checkpointResume",
970                        relationship: format!(
971                            "checkpoint-resumable delegation from '{}'",
972                            relationship.from
973                        ),
974                    });
975                }
976            }
977        }
978        let runtime = Arc::new(TeamRuntimeRegistry::new(
979            self.name.clone(),
980            roster,
981            self.policy.budget.clone(),
982            self.policy.termination.clone(),
983            hooks,
984        ));
985        #[cfg(feature = "team-tools")]
986        let member_registry = Arc::new(OnceLock::new());
987        let members: Vec<Arc<dyn Agent>> = self
988            .members
989            .iter()
990            .map(|member| {
991                let relationships: Vec<TeamRelationship> = self
992                    .relationships
993                    .iter()
994                    .filter(|relationship| relationship.from == member.name)
995                    .cloned()
996                    .collect();
997                Arc::new(TeamMemberAgent {
998                    name: member.name.clone(),
999                    description: member.description.clone().unwrap_or_else(|| {
1000                        registry
1001                            .get(&member.name)
1002                            .expect("all member bindings were checked before lowering")
1003                            .description()
1004                            .to_string()
1005                    }),
1006                    agent: registry
1007                        .get(&member.name)
1008                        .expect("all member bindings were checked before lowering")
1009                        .clone(),
1010                    relationships,
1011                    incoming_relationships: self
1012                        .relationships
1013                        .iter()
1014                        .filter(|relationship| relationship.to == member.name)
1015                        .cloned()
1016                        .collect(),
1017                    #[cfg(feature = "team-tools")]
1018                    members: member_registry.clone(),
1019                    #[cfg(feature = "team-tools")]
1020                    team_name: self.name.clone(),
1021                    policy: self.policy.clone(),
1022                    runtime: runtime.clone(),
1023                }) as Arc<dyn Agent>
1024            })
1025            .collect();
1026        #[cfg(feature = "team-tools")]
1027        member_registry
1028            .set(members.iter().map(|agent| (agent.name().to_string(), agent.clone())).collect())
1029            .map_err(|_| TeamError::InvalidPolicy("memberRegistry"))?;
1030
1031        let coordinator_index = self
1032            .members
1033            .iter()
1034            .position(|member| member.name == self.coordinator)
1035            .expect("validated coordinator must be present");
1036        Ok(CompiledTeam {
1037            spec: self.clone(),
1038            name: self.name.clone(),
1039            description: self.description.clone(),
1040            coordinator_name: self.coordinator.clone(),
1041            coordinator: members[coordinator_index].clone(),
1042            members,
1043            handoffs: self
1044                .members
1045                .iter()
1046                .map(|member| {
1047                    let targets = self
1048                        .relationships
1049                        .iter()
1050                        .filter(|edge| {
1051                            edge.from == member.name && edge.kind == RelationshipKind::Handoff
1052                        })
1053                        .map(|edge| edge.to.clone())
1054                        .collect();
1055                    (member.name.clone(), targets)
1056                })
1057                .collect(),
1058            policy: self.policy.clone(),
1059            runtime,
1060        })
1061    }
1062}
1063
1064impl TeamRelationship {
1065    fn validate_policy(
1066        &self,
1067        names: &BTreeSet<&str>,
1068        relationships: &[TeamRelationship],
1069    ) -> std::result::Result<(), TeamError> {
1070        let invalid = |reason: String| TeamError::InvalidRelationshipPolicy {
1071            from: self.from.clone(),
1072            to: self.to.clone(),
1073            reason,
1074        };
1075        if self.kind == RelationshipKind::Handoff {
1076            let unsupported = if self.policy.input_schema.is_some() {
1077                Some("inputSchema")
1078            } else if self.policy.output_schema.is_some() {
1079                Some("outputSchema")
1080            } else if self.policy.context.is_some() {
1081                Some("context")
1082            } else if self.policy.history != TeamHistoryPolicy::Inherit {
1083                Some("history")
1084            } else if !self.policy.state_keys.is_empty() {
1085                Some("stateKeys")
1086            } else if !self.policy.state_write_keys.is_empty() {
1087                Some("stateWriteKeys")
1088            } else if self.policy.state_merge != TeamStateMergePolicy::RejectConflicts {
1089                Some("stateMerge")
1090            } else if !self.policy.artifact_prefixes.is_empty() {
1091                Some("artifactPrefixes")
1092            } else if self.policy.resume != TeamResumePolicy::FailClosed {
1093                Some("resume")
1094            } else if self.policy.timeout_ms.is_some() {
1095                Some("timeoutMs")
1096            } else if self.policy.approval != RelationshipApprovalPolicy::Never {
1097                Some("approval")
1098            } else if self.policy.circuit_breaker.is_some() {
1099                Some("circuitBreaker")
1100            } else {
1101                None
1102            };
1103            if let Some(field) = unsupported {
1104                return Err(invalid(format!(
1105                    "{field} applies only to Delegate relationships; use team-wide handoff budgets or failure policy"
1106                )));
1107            }
1108        }
1109        for (label, schema) in [
1110            ("inputSchema", self.policy.input_schema.as_ref()),
1111            ("outputSchema", self.policy.output_schema.as_ref()),
1112        ] {
1113            if let Some(schema) = schema {
1114                jsonschema::validator_for(schema).map_err(|error| {
1115                    invalid(format!("{label} is not valid JSON Schema: {error}"))
1116                })?;
1117            }
1118        }
1119        if self.policy.timeout_ms == Some(0) {
1120            return Err(invalid("timeoutMs must be greater than zero".to_string()));
1121        }
1122        if let TeamHistoryPolicy::Last { max_events: 0 } = self.policy.history {
1123            return Err(invalid("history.maxEvents must be greater than zero".to_string()));
1124        }
1125        let mut state_keys = BTreeSet::new();
1126        for key in &self.policy.state_keys {
1127            adk_core::validate_state_key(key)
1128                .map_err(|reason| invalid(format!("invalid state key '{key}': {reason}")))?;
1129            if !state_keys.insert(key.as_str()) {
1130                return Err(invalid(format!("duplicate state key '{key}'")));
1131            }
1132        }
1133        let mut state_write_keys = BTreeSet::new();
1134        for key in &self.policy.state_write_keys {
1135            adk_core::validate_state_key(key)
1136                .map_err(|reason| invalid(format!("invalid state write key '{key}': {reason}")))?;
1137            if !state_write_keys.insert(key.as_str()) {
1138                return Err(invalid(format!("duplicate state write key '{key}'")));
1139            }
1140        }
1141        let mut artifact_prefixes = BTreeSet::new();
1142        for prefix in &self.policy.artifact_prefixes {
1143            if prefix.is_empty() {
1144                return Err(invalid("artifact prefixes must not be empty".to_string()));
1145            }
1146            if !artifact_prefixes.insert(prefix.as_str()) {
1147                return Err(invalid(format!("duplicate artifact prefix '{prefix}'")));
1148            }
1149        }
1150        if let TeamResumePolicy::RequireCheckpoint { token_state_key } = &self.policy.resume {
1151            adk_core::validate_state_key(token_state_key).map_err(|reason| {
1152                invalid(format!("invalid resume token state key '{token_state_key}': {reason}"))
1153            })?;
1154        }
1155        match &self.policy.failure {
1156            RelationshipFailureStrategy::Retry { max_attempts: 0, .. }
1157            | RelationshipFailureStrategy::RetryThenFallback { max_attempts: 0, .. } => {
1158                return Err(invalid("maxAttempts must be greater than zero".to_string()));
1159            }
1160            RelationshipFailureStrategy::Fallback { target }
1161            | RelationshipFailureStrategy::RetryThenFallback { target, .. } => {
1162                if !names.contains(target.as_str()) {
1163                    return Err(invalid(format!("fallback target '{target}' is not a member")));
1164                }
1165                if target == &self.to {
1166                    return Err(invalid(
1167                        "fallback target must differ from the primary target".to_string(),
1168                    ));
1169                }
1170                let declared = relationships.iter().any(|candidate| {
1171                    candidate.from == self.from
1172                        && candidate.to == *target
1173                        && candidate.kind == self.kind
1174                });
1175                if !declared {
1176                    return Err(invalid(format!(
1177                        "fallback target '{target}' must be declared as an exact {:?} edge from '{}'",
1178                        self.kind, self.from
1179                    )));
1180                }
1181            }
1182            RelationshipFailureStrategy::Inherit
1183            | RelationshipFailureStrategy::Propagate
1184            | RelationshipFailureStrategy::ReturnError
1185            | RelationshipFailureStrategy::Retry { .. } => {}
1186        }
1187        if let Some(circuit) = self.policy.circuit_breaker
1188            && (circuit.failure_threshold == 0 || circuit.reset_after_ms == 0)
1189        {
1190            return Err(invalid(
1191                "circuitBreaker failureThreshold and resetAfterMs must be greater than zero"
1192                    .to_string(),
1193            ));
1194        }
1195        Ok(())
1196    }
1197}
1198
1199/// Executable root produced by [`TeamSpec::compile`].
1200pub struct CompiledTeam {
1201    spec: TeamSpec,
1202    name: String,
1203    description: String,
1204    coordinator_name: String,
1205    coordinator: Arc<dyn Agent>,
1206    members: Vec<Arc<dyn Agent>>,
1207    handoffs: HashMap<String, Vec<String>>,
1208    policy: TeamPolicy,
1209    runtime: Arc<TeamRuntimeRegistry>,
1210}
1211
1212impl std::fmt::Debug for CompiledTeam {
1213    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1214        formatter
1215            .debug_struct("CompiledTeam")
1216            .field("name", &self.name)
1217            .field("coordinator", &self.coordinator_name)
1218            .field("member_count", &self.members.len())
1219            .finish()
1220    }
1221}
1222
1223impl CompiledTeam {
1224    /// Returns the portable source specification used to compile this root.
1225    pub fn spec(&self) -> &TeamSpec {
1226        &self.spec
1227    }
1228
1229    /// Returns the validated portable source specification's coordinator name.
1230    pub fn coordinator_name(&self) -> &str {
1231        &self.coordinator_name
1232    }
1233
1234    /// Returns the exact handoff targets for a member.
1235    pub fn handoff_targets(&self, member: &str) -> Option<&[String]> {
1236        self.handoffs.get(member).map(Vec::as_slice)
1237    }
1238
1239    /// Returns the latest serializable execution receipt for a root invocation.
1240    pub fn execution_snapshot(&self, invocation_id: &str) -> Option<TeamExecutionSnapshot> {
1241        self.runtime.snapshot(invocation_id)
1242    }
1243
1244    /// Returns all execution receipts currently retained by this compiled team.
1245    pub fn execution_snapshots(&self) -> Vec<TeamExecutionSnapshot> {
1246        self.runtime.snapshots()
1247    }
1248
1249    /// Restores a persisted execution receipt before resuming with the same
1250    /// root invocation identifier.
1251    ///
1252    /// The team name and frozen roster must exactly match this compiled team,
1253    /// preventing a resumed execution from silently selecting different agents.
1254    pub fn restore_execution_snapshot(
1255        &self,
1256        snapshot: TeamExecutionSnapshot,
1257    ) -> std::result::Result<(), TeamError> {
1258        self.runtime.restore(snapshot)
1259    }
1260
1261    /// Returns the safe durable-resume action for a retained invocation.
1262    ///
1263    /// This method never replays delegation implicitly. A checkpoint plan must
1264    /// be handed to the target's durable host adapter with the named opaque
1265    /// token; a fail-closed plan requires operator resolution.
1266    pub fn resume_plan(&self, invocation_id: &str) -> Option<TeamResumePlan> {
1267        let snapshot = self.runtime.snapshot(invocation_id)?;
1268        let Some(active) =
1269            snapshot.edges.iter().rev().find(|edge| edge.status == TeamExecutionStatus::Running)
1270        else {
1271            return Some(TeamResumePlan::Coordinator);
1272        };
1273        match active.kind {
1274            RelationshipKind::Handoff => Some(TeamResumePlan::Handoff {
1275                edge_id: active.id.clone(),
1276                target: active.to.clone(),
1277            }),
1278            RelationshipKind::Delegate => {
1279                let policy = self.spec.relationships.iter().find(|relationship| {
1280                    relationship.kind == RelationshipKind::Delegate
1281                        && relationship.from == active.from
1282                        && relationship.to == active.to
1283                });
1284                match policy.map(|relationship| &relationship.policy.resume) {
1285                    Some(TeamResumePolicy::RequireCheckpoint { token_state_key }) => {
1286                        Some(TeamResumePlan::DelegateCheckpoint {
1287                            edge_id: active.id.clone(),
1288                            target: active.to.clone(),
1289                            token_state_key: token_state_key.clone(),
1290                        })
1291                    }
1292                    Some(TeamResumePolicy::FailClosed) | None => {
1293                        Some(TeamResumePlan::UnsafeDelegate {
1294                            edge_id: active.id.clone(),
1295                            target: active.to.clone(),
1296                            reason: "the edge is fail-closed and has no checkpoint resume contract"
1297                                .to_string(),
1298                        })
1299                    }
1300                }
1301            }
1302        }
1303    }
1304
1305    /// Validates and summarizes one retained execution receipt without model calls.
1306    pub fn analyze_execution(
1307        &self,
1308        invocation_id: &str,
1309    ) -> std::result::Result<Option<TeamExecutionAnalysis>, TeamReplayError> {
1310        let Some(snapshot) = self.runtime.snapshot(invocation_id) else {
1311            return Ok(None);
1312        };
1313        validate_team_replay(&self.spec, &snapshot)?;
1314        Ok(Some(analyze_team_execution(&self.spec, &snapshot)))
1315    }
1316}
1317
1318#[async_trait]
1319impl Agent for CompiledTeam {
1320    fn name(&self) -> &str {
1321        &self.name
1322    }
1323
1324    fn description(&self) -> &str {
1325        &self.description
1326    }
1327
1328    fn sub_agents(&self) -> &[Arc<dyn Agent>] {
1329        &self.members
1330    }
1331
1332    fn capabilities(&self) -> adk_core::AgentCapabilities {
1333        self.coordinator.capabilities()
1334    }
1335
1336    fn topology(&self) -> Option<adk_core::AgentTopology> {
1337        Some(adk_core::AgentTopology {
1338            root: self.name.clone(),
1339            coordinator: self.coordinator_name.clone(),
1340            members: self
1341                .members
1342                .iter()
1343                .map(|member| adk_core::AgentTopologyMember {
1344                    name: member.name().to_string(),
1345                    description: member.description().to_string(),
1346                    coordinator: member.name() == self.coordinator_name,
1347                    capabilities: member.capabilities(),
1348                })
1349                .collect(),
1350            relationships: self
1351                .spec
1352                .relationships
1353                .iter()
1354                .map(|relationship| adk_core::AgentTopologyRelationship {
1355                    from: relationship.from.clone(),
1356                    to: relationship.to.clone(),
1357                    kind: match relationship.kind {
1358                        RelationshipKind::Delegate => adk_core::AgentRelationshipKind::Delegate,
1359                        RelationshipKind::Handoff => adk_core::AgentRelationshipKind::Handoff,
1360                    },
1361                })
1362                .collect(),
1363        })
1364    }
1365
1366    fn configure_run(&self, agent_name: &str, config: &mut RunConfig) {
1367        let member_name =
1368            if agent_name == self.name { self.coordinator_name.as_str() } else { agent_name };
1369        config.max_transfer_depth =
1370            Some(config.max_transfer_depth.map_or(self.policy.max_transfer_depth, |current| {
1371                current.min(self.policy.max_transfer_depth)
1372            }));
1373        if let Some(member) = self.members.iter().find(|member| member.name() == member_name) {
1374            member.configure_run(member_name, config);
1375        }
1376    }
1377
1378    fn transfer_targets_for(&self, agent_name: &str) -> Option<Vec<String>> {
1379        let member_name =
1380            if agent_name == self.name { self.coordinator_name.as_str() } else { agent_name };
1381        Some(self.handoffs.get(member_name).cloned().unwrap_or_default())
1382    }
1383
1384    fn strict_transfer_policy(&self) -> bool {
1385        true
1386    }
1387
1388    // The coordinator is one of the members, so each agent — and with it each toolset,
1389    // MCP connection or container session it holds — closes once.
1390    async fn close(&self) {
1391        for member in &self.members {
1392            member.close().await;
1393        }
1394    }
1395
1396    async fn prewarm(&self) -> Result<()> {
1397        for member in &self.members {
1398            member.prewarm().await?;
1399        }
1400        Ok(())
1401    }
1402
1403    async fn govern_transfer(
1404        &self,
1405        request: &adk_core::AgentTransferRequest,
1406    ) -> Result<adk_core::AgentTransferDecision> {
1407        let declared = self.spec.relationships.iter().any(|relationship| {
1408            relationship.kind == RelationshipKind::Handoff
1409                && relationship.from == request.from
1410                && relationship.to == request.to
1411        });
1412        if !declared {
1413            return Ok(adk_core::AgentTransferDecision::Deny {
1414                reason: "the exact handoff edge is not declared by TeamSpec".to_string(),
1415            });
1416        }
1417        if request.depth > self.policy.max_transfer_depth {
1418            return Ok(adk_core::AgentTransferDecision::Deny {
1419                reason: format!(
1420                    "handoff depth {} exceeds team maximum {}",
1421                    request.depth, self.policy.max_transfer_depth
1422                ),
1423            });
1424        }
1425        Ok(adk_core::AgentTransferDecision::Allow)
1426    }
1427
1428    async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
1429        // A call a person asked for needs an agent that holds it for their decision itself
1430        // (spec 3.3 §7.4 rule 5).
1431        if let Some(refused) = crate::requested_call::refused_by_root(
1432            ctx.as_ref(),
1433            &self.name,
1434            crate::requested_call::RUNS_OTHER_AGENTS,
1435        ) {
1436            return Ok(refused);
1437        }
1438        let root_invocation_id = ctx.orchestration_root_invocation_id().to_string();
1439        let lifecycle = TeamLifecycleContext {
1440            team: self.name.clone(),
1441            invocation_id: root_invocation_id.clone(),
1442            phase: TeamLifecyclePhase::Team,
1443            member: None,
1444            edge_id: None,
1445            from: None,
1446            to: None,
1447            kind: None,
1448            attempt: None,
1449        };
1450        let team_span = adk_telemetry::team_run_span_with_context(
1451            &self.name,
1452            &root_invocation_id,
1453            ctx.session_id(),
1454            &self.coordinator_name,
1455        );
1456        if let TeamLifecycleDecision::Terminate { reason } =
1457            self.runtime.before_lifecycle(&lifecycle).instrument(team_span.clone()).await?
1458        {
1459            self.runtime
1460                .after_lifecycle(
1461                    &lifecycle,
1462                    &TeamLifecycleOutcome::Terminated { reason: reason.clone() },
1463                )
1464                .await?;
1465            return Err(TeamRuntimeError::PolicyDenied {
1466                operation: "team start".to_string(),
1467                reason,
1468            }
1469            .into());
1470        }
1471        if let Some(target) = self.runtime.resume_handoff_target(&root_invocation_id)? {
1472            let member = self
1473                .members
1474                .iter()
1475                .find(|member| member.name() == target)
1476                .cloned()
1477                .ok_or_else(|| {
1478                    adk_core::AdkError::new(
1479                        adk_core::ErrorComponent::Agent,
1480                        adk_core::ErrorCategory::NotFound,
1481                        "agent.team.resume_target_missing",
1482                        format!(
1483                            "restored handoff target '{target}' is not in the frozen team roster"
1484                        ),
1485                    )
1486                })?;
1487            let inner = member.run(ctx).await;
1488            return wrap_lifecycle_stream(inner, self.runtime.clone(), lifecycle, team_span).await;
1489        }
1490        let inner = self.coordinator.run(ctx).await;
1491        wrap_lifecycle_stream(inner, self.runtime.clone(), lifecycle, team_span).await
1492    }
1493}
1494
1495async fn wrap_lifecycle_stream(
1496    inner: Result<EventStream>,
1497    runtime: Arc<TeamRuntimeRegistry>,
1498    lifecycle: TeamLifecycleContext,
1499    span: tracing::Span,
1500) -> Result<EventStream> {
1501    // Alive as long as the stream; the invocation finishes when its last team stream ends.
1502    let active = runtime.enter(&lifecycle.invocation_id);
1503    let mut inner = match inner {
1504        Ok(stream) => stream,
1505        Err(error) => {
1506            let outcome = TeamLifecycleOutcome::Failed {
1507                code: Some(error.code.to_string()),
1508                message: error.to_string(),
1509            };
1510            runtime.after_lifecycle(&lifecycle, &outcome).await?;
1511            span.record("team.status", "failed");
1512            return Err(error);
1513        }
1514    };
1515    Ok(Box::pin(async_stream::stream! {
1516        let _active = active;
1517        while let Some(result) = inner.next().await {
1518            match result {
1519                Ok(event) => {
1520                    span.in_scope(|| tracing::trace!("team execution event"));
1521                    yield Ok(event);
1522                }
1523                Err(error) => {
1524                    let outcome = TeamLifecycleOutcome::Failed {
1525                        code: Some(error.code.to_string()),
1526                        message: error.to_string(),
1527                    };
1528                    if let Err(hook_error) = runtime.after_lifecycle(&lifecycle, &outcome).await {
1529                        span.record("team.status", "failed");
1530                        yield Err(hook_error);
1531                    } else {
1532                        span.record("team.status", "failed");
1533                        yield Err(error);
1534                    }
1535                    return;
1536                }
1537            }
1538        }
1539        if let Err(error) = runtime
1540            .after_lifecycle(&lifecycle, &TeamLifecycleOutcome::Succeeded)
1541            .await
1542        {
1543            span.record("team.status", "failed");
1544            yield Err(error);
1545        } else {
1546            span.record("team.status", "completed");
1547        }
1548    }))
1549}
1550
1551struct TeamMemberAgent {
1552    name: String,
1553    description: String,
1554    agent: Arc<dyn Agent>,
1555    relationships: Vec<TeamRelationship>,
1556    incoming_relationships: Vec<TeamRelationship>,
1557    #[cfg(feature = "team-tools")]
1558    members: Arc<OnceLock<HashMap<String, Arc<dyn Agent>>>>,
1559    #[cfg(feature = "team-tools")]
1560    team_name: String,
1561    policy: TeamPolicy,
1562    runtime: Arc<TeamRuntimeRegistry>,
1563}
1564
1565#[async_trait]
1566impl Agent for TeamMemberAgent {
1567    fn name(&self) -> &str {
1568        &self.name
1569    }
1570
1571    fn description(&self) -> &str {
1572        &self.description
1573    }
1574
1575    fn sub_agents(&self) -> &[Arc<dyn Agent>] {
1576        &[]
1577    }
1578
1579    async fn screen_user_input(&self, content: &Content) -> Result<Option<Content>> {
1580        self.agent.screen_user_input(content).await
1581    }
1582
1583    fn supports_agent_transfer(&self) -> bool {
1584        self.agent.supports_agent_transfer()
1585    }
1586
1587    fn capabilities(&self) -> adk_core::AgentCapabilities {
1588        self.agent.capabilities()
1589    }
1590
1591    // `sub_agents` is empty on purpose, so the default `close` would stop here.
1592    async fn close(&self) {
1593        self.agent.close().await;
1594    }
1595
1596    async fn prewarm(&self) -> Result<()> {
1597        self.agent.prewarm().await
1598    }
1599
1600    fn configure_run(&self, _agent_name: &str, config: &mut RunConfig) {
1601        // The member applies its own run policy first, such as a harness's governed layer;
1602        // the team's transfer targets and delegation tools then take precedence over it.
1603        self.agent.configure_run(&self.name, config);
1604        let handoff_targets: Vec<String> = self
1605            .relationships
1606            .iter()
1607            .filter(|relationship| relationship.kind == RelationshipKind::Handoff)
1608            .map(|relationship| relationship.to.clone())
1609            .collect();
1610        config.transfer_targets = handoff_targets;
1611        config.parent_agent = None;
1612        config.max_transfer_depth =
1613            Some(config.max_transfer_depth.map_or(self.policy.max_transfer_depth, |current| {
1614                current.min(self.policy.max_transfer_depth)
1615            }));
1616        #[cfg(feature = "team-tools")]
1617        {
1618            config
1619                .runtime_toolsets
1620                .retain(|runtime| !runtime.toolset().name().starts_with("__adk_team_"));
1621            let delegates: Vec<&TeamRelationship> = self
1622                .relationships
1623                .iter()
1624                .filter(|relationship| relationship.kind == RelationshipKind::Delegate)
1625                .collect();
1626            if !delegates.is_empty() {
1627                let members = self
1628                    .members
1629                    .get()
1630                    .expect("compiled team initializes member registry before execution");
1631                let limiter =
1632                    Arc::new(tokio::sync::Semaphore::new(self.policy.max_concurrent_delegations));
1633                let build_tool = |relationship: &TeamRelationship| -> Arc<dyn Tool> {
1634                    let target = members
1635                        .get(&relationship.to)
1636                        .expect("validated relationship target has a compiled binding")
1637                        .clone();
1638                    let context = relationship.policy.context.unwrap_or(self.policy.context);
1639                    let history = relationship.policy.history;
1640                    let snapshot = match (context, history) {
1641                        (TeamContextPolicy::Shared, _)
1642                        | (
1643                            TeamContextPolicy::Isolated,
1644                            TeamHistoryPolicy::Full | TeamHistoryPolicy::Last { .. },
1645                        ) => AgentToolSessionSnapshot::Parent,
1646                        (
1647                            TeamContextPolicy::Isolated,
1648                            TeamHistoryPolicy::Inherit | TeamHistoryPolicy::None,
1649                        ) => AgentToolSessionSnapshot::Isolated,
1650                    };
1651                    let mut tool = AgentTool::new(target)
1652                        .session_snapshot(snapshot)
1653                        .forward_artifacts(context == TeamContextPolicy::Shared)
1654                        .forward_shared_state(context == TeamContextPolicy::Shared)
1655                        .forward_events(true)
1656                        .forward_memory(context == TeamContextPolicy::Shared)
1657                        .failure_mode(AgentToolFailureMode::Propagate)
1658                        .max_delegation_depth(self.policy.max_delegation_depth)
1659                        .execute_child_handoffs(members.values().cloned());
1660                    if let Some(schema) = &relationship.policy.input_schema {
1661                        tool = tool.input_schema(schema.clone());
1662                    }
1663                    if let Some(schema) = &relationship.policy.output_schema {
1664                        tool = tool.output_schema(schema.clone());
1665                    }
1666                    if let Some(timeout_ms) = relationship.policy.timeout_ms {
1667                        tool = tool.timeout(std::time::Duration::from_millis(timeout_ms));
1668                    }
1669                    match history {
1670                        TeamHistoryPolicy::None => tool = tool.history_max_events(0),
1671                        TeamHistoryPolicy::Last { max_events } => {
1672                            tool = tool.history_max_events(max_events);
1673                        }
1674                        TeamHistoryPolicy::Inherit | TeamHistoryPolicy::Full => {}
1675                    }
1676                    if context == TeamContextPolicy::Isolated {
1677                        tool = tool.state_keys(Vec::<String>::new());
1678                    } else if !relationship.policy.state_keys.is_empty() {
1679                        tool = tool.state_keys(relationship.policy.state_keys.clone());
1680                    }
1681                    if !relationship.policy.state_write_keys.is_empty() {
1682                        let mut writable_keys = relationship.policy.state_write_keys.clone();
1683                        writable_keys.push(runtime::TEAM_EXECUTION_STATE_KEY.to_string());
1684                        tool = tool.output_state_keys(writable_keys);
1685                    }
1686                    tool = tool.state_merge_policy(match relationship.policy.state_merge {
1687                        TeamStateMergePolicy::RejectConflicts => {
1688                            AgentToolStateMergePolicy::RejectConflicts
1689                        }
1690                        TeamStateMergePolicy::Overwrite => AgentToolStateMergePolicy::Overwrite,
1691                    });
1692                    tool = tool.state_merge_exempt_keys([runtime::TEAM_EXECUTION_STATE_KEY]);
1693                    if !relationship.policy.artifact_prefixes.is_empty() {
1694                        tool =
1695                            tool.artifact_prefixes(relationship.policy.artifact_prefixes.clone());
1696                    }
1697                    Arc::new(tool)
1698                };
1699                let tools = delegates
1700                    .iter()
1701                    .map(|relationship| {
1702                        let fallback_target = match &relationship.policy.failure {
1703                            RelationshipFailureStrategy::Fallback { target }
1704                            | RelationshipFailureStrategy::RetryThenFallback { target, .. } => {
1705                                Some(target.as_str())
1706                            }
1707                            RelationshipFailureStrategy::Inherit
1708                            | RelationshipFailureStrategy::Propagate
1709                            | RelationshipFailureStrategy::ReturnError
1710                            | RelationshipFailureStrategy::Retry { .. } => None,
1711                        };
1712                        let fallback = fallback_target.and_then(|target| {
1713                            self.relationships
1714                                .iter()
1715                                .find(|candidate| {
1716                                    candidate.kind == RelationshipKind::Delegate
1717                                        && candidate.to == target
1718                                })
1719                                .map(&build_tool)
1720                        });
1721                        Arc::new(BoundedDelegateTool {
1722                            inner: build_tool(relationship),
1723                            fallback,
1724                            limiter: limiter.clone(),
1725                            relationship: (*relationship).clone(),
1726                            team_failure: self.policy.failure,
1727                            runtime: self.runtime.clone(),
1728                            circuit: Arc::new(Mutex::new(CircuitState::default())),
1729                        }) as Arc<dyn Tool>
1730                    })
1731                    .collect();
1732                config.runtime_toolsets.push(RuntimeToolset::new(Arc::new(TeamToolset {
1733                    name: format!("__adk_team_{}_{}", self.team_name, self.name),
1734                    tools,
1735                })));
1736            }
1737        }
1738    }
1739
1740    async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
1741        let root_invocation_id = ctx.orchestration_root_invocation_id().to_string();
1742        // Attached before any other ledger access so the team budget chains to the run budget.
1743        let team_tracker = self
1744            .runtime
1745            .budget_tracker(&root_invocation_id, ctx.run_config().budget_tracker.clone());
1746        self.runtime.check_budget(&root_invocation_id)?;
1747        let member_lifecycle = TeamLifecycleContext {
1748            team: self.runtime.team_name().to_string(),
1749            invocation_id: root_invocation_id.clone(),
1750            phase: TeamLifecyclePhase::Member,
1751            member: Some(self.name.clone()),
1752            edge_id: ctx.orchestration_edge_id().map(str::to_string),
1753            from: None,
1754            to: None,
1755            kind: None,
1756            attempt: None,
1757        };
1758        let member_span = adk_telemetry::team_member_span_with_context(
1759            self.runtime.team_name(),
1760            &self.name,
1761            &root_invocation_id,
1762            ctx.session_id(),
1763        );
1764        if let TeamLifecycleDecision::Terminate { reason } =
1765            self.runtime.before_lifecycle(&member_lifecycle).instrument(member_span.clone()).await?
1766        {
1767            self.runtime
1768                .after_lifecycle(
1769                    &member_lifecycle,
1770                    &TeamLifecycleOutcome::Terminated { reason: reason.clone() },
1771                )
1772                .await?;
1773            return Err(TeamRuntimeError::PolicyDenied {
1774                operation: format!("member '{}' start", self.name),
1775                reason,
1776            }
1777            .into());
1778        }
1779        let mut config = ctx.run_config().clone();
1780        self.configure_run(self.name(), &mut config);
1781        config.budget_tracker = Some(team_tracker);
1782        let required_confirmations = self
1783            .relationships
1784            .iter()
1785            .filter(|relationship| {
1786                relationship.kind == RelationshipKind::Delegate
1787                    && relationship.policy.approval == RelationshipApprovalPolicy::Required
1788            })
1789            .map(|relationship| relationship.to.clone())
1790            .collect();
1791        let configured_ctx = Arc::new(TeamInvocationContext {
1792            inner: ctx.clone(),
1793            agent: self.agent.clone(),
1794            config,
1795            max_delegation_depth: self.policy.max_delegation_depth,
1796            required_confirmations,
1797        });
1798        let incoming = self.incoming_execution(ctx.as_ref(), &root_invocation_id);
1799        let incoming_relationship_span = incoming.as_ref().map(|(relationship, edge)| {
1800            adk_telemetry::team_relationship_span_with_context(
1801                self.runtime.team_name(),
1802                &relationship.from,
1803                &relationship.to,
1804                "handoff",
1805                &edge.id,
1806                &root_invocation_id,
1807                ctx.session_id(),
1808            )
1809        });
1810        let incoming_lifecycle =
1811            incoming.as_ref().map(|(relationship, edge)| TeamLifecycleContext {
1812                team: self.runtime.team_name().to_string(),
1813                invocation_id: root_invocation_id.clone(),
1814                phase: TeamLifecyclePhase::Relationship,
1815                member: None,
1816                edge_id: Some(edge.id.clone()),
1817                from: Some(relationship.from.clone()),
1818                to: Some(relationship.to.clone()),
1819                kind: Some(relationship.kind),
1820                attempt: Some(edge.attempt),
1821            });
1822        let incoming_relationship_started = std::time::Instant::now();
1823        let (max_attempts, backoff_ms) = incoming.as_ref().map_or((1, 0), |(relationship, _)| {
1824            match relationship.policy.failure {
1825                RelationshipFailureStrategy::Retry { max_attempts, backoff_ms }
1826                | RelationshipFailureStrategy::RetryThenFallback {
1827                    max_attempts, backoff_ms, ..
1828                } => (max_attempts, backoff_ms),
1829                RelationshipFailureStrategy::Inherit
1830                | RelationshipFailureStrategy::Propagate
1831                | RelationshipFailureStrategy::ReturnError
1832                | RelationshipFailureStrategy::Fallback { .. } => (1, 0),
1833            }
1834        });
1835        let mut immediate_error = None;
1836        let mut inner = None;
1837        for attempt in 1..=max_attempts {
1838            match self
1839                .agent
1840                .run(configured_ctx.clone())
1841                .instrument(incoming_relationship_span.clone().unwrap_or_else(tracing::Span::none))
1842                .await
1843            {
1844                Ok(stream) => {
1845                    inner = Some(stream);
1846                    break;
1847                }
1848                Err(error) => {
1849                    immediate_error = Some(error);
1850                    if attempt < max_attempts && backoff_ms > 0 {
1851                        tokio::time::sleep(std::time::Duration::from_millis(backoff_ms)).await;
1852                    }
1853                }
1854            }
1855        }
1856        let Some(mut inner) = inner else {
1857            let error = immediate_error.unwrap_or_else(|| {
1858                adk_core::AdkError::new(
1859                    adk_core::ErrorComponent::Agent,
1860                    adk_core::ErrorCategory::Internal,
1861                    "agent.team.member_start_failed",
1862                    format!("team member '{}' failed to start", self.name),
1863                )
1864            });
1865            if let Some((_, edge)) = &incoming {
1866                self.runtime.finish_edge(&root_invocation_id, &edge.id, Some(error.to_string()));
1867            }
1868            if let Some(span) = &incoming_relationship_span {
1869                span.record("team.status", "failed");
1870                span.record(
1871                    "team.duration_ms",
1872                    incoming_relationship_started.elapsed().as_millis() as u64,
1873                );
1874            }
1875            if let Some(lifecycle) = &incoming_lifecycle {
1876                self.runtime
1877                    .after_lifecycle(
1878                        lifecycle,
1879                        &TeamLifecycleOutcome::Failed {
1880                            code: Some(error.code.to_string()),
1881                            message: error.to_string(),
1882                        },
1883                    )
1884                    .await?;
1885            }
1886            self.runtime.fail(&root_invocation_id, &error);
1887            if let Some((relationship, incoming_edge)) = &incoming {
1888                match &relationship.policy.failure {
1889                    RelationshipFailureStrategy::Fallback { target }
1890                    | RelationshipFailureStrategy::RetryThenFallback { target, .. } => {
1891                        let mut event = adk_core::Event::new(ctx.invocation_id());
1892                        event.author = relationship.from.clone();
1893                        event.actions.transfer_to_agent = Some(target.clone());
1894                        event.llm_response.turn_complete = true;
1895                        let edge_id = self.runtime.start_edge(
1896                            &root_invocation_id,
1897                            TeamEdgeStart {
1898                                execution_id: None,
1899                                parent_id: incoming_edge.parent_id.clone(),
1900                                from: &relationship.from,
1901                                to: target,
1902                                kind: RelationshipKind::Handoff,
1903                                attempt: 1,
1904                            },
1905                        )?;
1906                        self.runtime.record_event(
1907                            &root_invocation_id,
1908                            Some(&edge_id),
1909                            &mut event,
1910                        )?;
1911                        return wrap_lifecycle_stream(
1912                            Ok(Box::pin(futures::stream::once(async { Ok(event) }))),
1913                            self.runtime.clone(),
1914                            member_lifecycle,
1915                            member_span,
1916                        )
1917                        .await;
1918                    }
1919                    RelationshipFailureStrategy::ReturnError => {
1920                        let mut event = adk_core::Event::new(ctx.invocation_id());
1921                        event.author = self.name.clone();
1922                        event.llm_response.turn_complete = true;
1923                        event.llm_response.content = Some(
1924                            adk_core::Content::new("model").with_text(
1925                                serde_json::json!({
1926                                    "error": error.to_string(),
1927                                    "agent": self.name,
1928                                })
1929                                .to_string(),
1930                            ),
1931                        );
1932                        self.runtime.record_event(
1933                            &root_invocation_id,
1934                            Some(&incoming_edge.id),
1935                            &mut event,
1936                        )?;
1937                        return wrap_lifecycle_stream(
1938                            Ok(Box::pin(futures::stream::once(async { Ok(event) }))),
1939                            self.runtime.clone(),
1940                            member_lifecycle,
1941                            member_span,
1942                        )
1943                        .await;
1944                    }
1945                    RelationshipFailureStrategy::Inherit
1946                    | RelationshipFailureStrategy::Propagate
1947                    | RelationshipFailureStrategy::Retry { .. } => {}
1948                }
1949            }
1950            return wrap_lifecycle_stream(
1951                Err(error),
1952                self.runtime.clone(),
1953                member_lifecycle,
1954                member_span,
1955            )
1956            .await;
1957        };
1958        let relationships = self.relationships.clone();
1959        let member = self.name.clone();
1960        let inner_name = self.agent.name().to_string();
1961        let runtime = self.runtime.clone();
1962        let incoming_edge_id = incoming.as_ref().map(|(_, edge)| edge.id.clone());
1963        let stream = async_stream::stream! {
1964            let mut incoming_finished = false;
1965            while let Some(result) = inner.next().await {
1966                match result {
1967                    Ok(mut event) => {
1968                        if event.author.is_empty() || event.author == inner_name {
1969                            event.author.clone_from(&member);
1970                        }
1971                        let mut event_edge_id = ctx
1972                            .orchestration_edge_id()
1973                            .map(str::to_string)
1974                            .or_else(|| incoming_edge_id.clone());
1975                        if let Some(target) = &event.actions.transfer_to_agent {
1976                            let Some(_relationship) = relationships.iter().find(|relationship| {
1977                                relationship.kind == RelationshipKind::Handoff
1978                                    && relationship.to == *target
1979                            }) else {
1980                                let allowed = relationships
1981                                    .iter()
1982                                    .filter(|relationship| relationship.kind == RelationshipKind::Handoff)
1983                                    .map(|relationship| relationship.to.as_str())
1984                                    .collect::<Vec<_>>()
1985                                    .join(", ");
1986                                let error: adk_core::AdkError = TeamRuntimeError::PolicyDenied {
1987                                    operation: format!(
1988                                        "handoff from '{member}' to '{target}' (allowed: {allowed})"
1989                                    ),
1990                                    reason: "the exact edge is not declared".to_string(),
1991                                }
1992                                .into();
1993                                runtime.fail(&root_invocation_id, &error);
1994                                yield Err(error);
1995                                return;
1996                            };
1997                            let proposed_edge_id = uuid::Uuid::new_v4().to_string();
1998                            let relationship_lifecycle = TeamLifecycleContext {
1999                                team: runtime.team_name().to_string(),
2000                                invocation_id: root_invocation_id.clone(),
2001                                phase: TeamLifecyclePhase::Relationship,
2002                                member: None,
2003                                edge_id: Some(proposed_edge_id.clone()),
2004                                from: Some(member.clone()),
2005                                to: Some(target.clone()),
2006                                kind: Some(RelationshipKind::Handoff),
2007                                attempt: Some(1),
2008                            };
2009                            match runtime.before_lifecycle(&relationship_lifecycle).await {
2010                                Ok(TeamLifecycleDecision::Continue) => {}
2011                                Ok(TeamLifecycleDecision::Terminate { reason }) => {
2012                                    if let Err(error) = runtime
2013                                        .after_lifecycle(
2014                                            &relationship_lifecycle,
2015                                            &TeamLifecycleOutcome::Terminated {
2016                                                reason: reason.clone(),
2017                                            },
2018                                        )
2019                                        .await
2020                                    {
2021                                        yield Err(error);
2022                                    } else {
2023                                        yield Err(TeamRuntimeError::PolicyDenied {
2024                                            operation: format!(
2025                                                "handoff from '{member}' to '{target}'"
2026                                            ),
2027                                            reason,
2028                                        }
2029                                        .into());
2030                                    }
2031                                    return;
2032                                }
2033                                Err(error) => {
2034                                    yield Err(error);
2035                                    return;
2036                                }
2037                            }
2038                            match runtime.start_edge(
2039                                &root_invocation_id,
2040                                TeamEdgeStart {
2041                                    execution_id: Some(proposed_edge_id),
2042                                    parent_id: event_edge_id.clone(),
2043                                    from: &member,
2044                                    to: target,
2045                                    kind: RelationshipKind::Handoff,
2046                                    attempt: 1,
2047                                },
2048                            ) {
2049                                Ok(edge_id) => {
2050                                    if let Some(incoming_id) = &incoming_edge_id {
2051                                        runtime.finish_edge(&root_invocation_id, incoming_id, None);
2052                                        incoming_finished = true;
2053                                        if let Some(span) = &incoming_relationship_span {
2054                                            span.record("team.status", "completed");
2055                                            span.record(
2056                                                "team.duration_ms",
2057                                                incoming_relationship_started.elapsed().as_millis() as u64,
2058                                            );
2059                                        }
2060                                        if let Some(lifecycle) = &incoming_lifecycle
2061                                            && let Err(error) = runtime
2062                                                .after_lifecycle(
2063                                                    lifecycle,
2064                                                    &TeamLifecycleOutcome::Succeeded,
2065                                                )
2066                                                .await
2067                                        {
2068                                            yield Err(error);
2069                                            return;
2070                                        }
2071                                    }
2072                                    event_edge_id = Some(edge_id);
2073                                }
2074                                Err(error) => {
2075                                    yield Err(error);
2076                                    return;
2077                                }
2078                            }
2079                        } else if event.is_final_response()
2080                            && let Some(incoming_id) = &incoming_edge_id
2081                        {
2082                            runtime.finish_edge(&root_invocation_id, incoming_id, None);
2083                            incoming_finished = true;
2084                            if let Some(span) = &incoming_relationship_span {
2085                                span.record("team.status", "completed");
2086                                span.record(
2087                                    "team.duration_ms",
2088                                    incoming_relationship_started.elapsed().as_millis() as u64,
2089                                );
2090                            }
2091                            if let Some(lifecycle) = &incoming_lifecycle
2092                                && let Err(error) = runtime
2093                                    .after_lifecycle(lifecycle, &TeamLifecycleOutcome::Succeeded)
2094                                    .await
2095                            {
2096                                yield Err(error);
2097                                return;
2098                            }
2099                        }
2100                        match runtime.record_event(
2101                            &root_invocation_id,
2102                            event_edge_id.as_deref(),
2103                            &mut event,
2104                        ) {
2105                            Ok(EventDisposition::Continue) => yield Ok(event),
2106                            Ok(EventDisposition::Terminate) => {
2107                                ctx.end_invocation();
2108                                yield Ok(event);
2109                                return;
2110                            }
2111                            // The event's model call already happened, so it is kept
2112                            // before the run stops on the shared budget.
2113                            Err(error) if error.code.starts_with("budget.") => {
2114                                yield Ok(event);
2115                                yield Err(error);
2116                                return;
2117                            }
2118                            Err(error) => {
2119                                yield Err(error);
2120                                return;
2121                            }
2122                        }
2123                    }
2124                    Err(error) => {
2125                        if let Some(incoming_id) = &incoming_edge_id {
2126                            runtime.finish_edge(
2127                                &root_invocation_id,
2128                                incoming_id,
2129                                Some(error.to_string()),
2130                            );
2131                        }
2132                        runtime.fail(&root_invocation_id, &error);
2133                        if let Some(span) = &incoming_relationship_span {
2134                            span.record("team.status", "failed");
2135                            span.record(
2136                                "team.duration_ms",
2137                                incoming_relationship_started.elapsed().as_millis() as u64,
2138                            );
2139                        }
2140                        if let Some(lifecycle) = &incoming_lifecycle {
2141                            let outcome = TeamLifecycleOutcome::Failed {
2142                                code: Some(error.code.to_string()),
2143                                message: error.to_string(),
2144                            };
2145                            if let Err(hook_error) = runtime.after_lifecycle(lifecycle, &outcome).await {
2146                                yield Err(hook_error);
2147                                return;
2148                            }
2149                        }
2150                        yield Err(error);
2151                        return;
2152                    }
2153                }
2154            }
2155            if !incoming_finished && let Some(incoming_id) = &incoming_edge_id {
2156                runtime.finish_edge(&root_invocation_id, incoming_id, None);
2157                if let Some(span) = &incoming_relationship_span {
2158                    span.record("team.status", "completed");
2159                    span.record(
2160                        "team.duration_ms",
2161                        incoming_relationship_started.elapsed().as_millis() as u64,
2162                    );
2163                }
2164                if let Some(lifecycle) = &incoming_lifecycle
2165                    && let Err(error) = runtime
2166                        .after_lifecycle(lifecycle, &TeamLifecycleOutcome::Succeeded)
2167                        .await
2168                {
2169                    yield Err(error);
2170                }
2171            }
2172        };
2173        wrap_lifecycle_stream(
2174            Ok(Box::pin(stream)),
2175            self.runtime.clone(),
2176            member_lifecycle,
2177            member_span,
2178        )
2179        .await
2180    }
2181}
2182
2183impl TeamMemberAgent {
2184    fn incoming_execution(
2185        &self,
2186        ctx: &dyn InvocationContext,
2187        root_invocation_id: &str,
2188    ) -> Option<(TeamRelationship, TeamEdgeExecution)> {
2189        let snapshot = self.runtime.snapshot(root_invocation_id).or_else(|| {
2190            ctx.session()
2191                .state()
2192                .get(TEAM_EXECUTION_STATE_KEY)
2193                .and_then(|value| serde_json::from_value::<TeamExecutionSnapshot>(value).ok())
2194        })?;
2195        let edge = snapshot
2196            .edges
2197            .iter()
2198            .rev()
2199            .find(|edge| {
2200                edge.kind == RelationshipKind::Handoff
2201                    && edge.status == TeamExecutionStatus::Running
2202                    && edge.to == self.name
2203            })?
2204            .clone();
2205        let relationship = self
2206            .incoming_relationships
2207            .iter()
2208            .find(|relationship| {
2209                relationship.kind == RelationshipKind::Handoff
2210                    && relationship.from == edge.from
2211                    && relationship.to == edge.to
2212            })
2213            .cloned()?;
2214        Some((relationship, edge))
2215    }
2216}
2217
2218/// Context wrapper that makes member-specific policy visible even when the
2219/// member is invoked by `AgentTool` rather than directly by `Runner`.
2220struct TeamInvocationContext {
2221    inner: Arc<dyn InvocationContext>,
2222    agent: Arc<dyn Agent>,
2223    config: RunConfig,
2224    max_delegation_depth: u32,
2225    required_confirmations: HashSet<String>,
2226}
2227
2228#[async_trait]
2229impl adk_core::ReadonlyContext for TeamInvocationContext {
2230    fn invocation_id(&self) -> &str {
2231        self.inner.invocation_id()
2232    }
2233
2234    fn agent_name(&self) -> &str {
2235        self.agent.name()
2236    }
2237
2238    fn user_id(&self) -> &str {
2239        self.inner.user_id()
2240    }
2241
2242    fn app_name(&self) -> &str {
2243        self.inner.app_name()
2244    }
2245
2246    fn session_id(&self) -> &str {
2247        self.inner.session_id()
2248    }
2249
2250    fn branch(&self) -> &str {
2251        self.inner.branch()
2252    }
2253
2254    fn user_content(&self) -> &adk_core::Content {
2255        self.inner.user_content()
2256    }
2257
2258    fn acting_context(&self) -> adk_core::ActingContext {
2259        self.inner.acting_context()
2260    }
2261
2262    fn is_authenticated(&self) -> bool {
2263        self.inner.is_authenticated()
2264    }
2265}
2266
2267#[async_trait]
2268impl adk_core::CallbackContext for TeamInvocationContext {
2269    fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
2270        self.inner.artifacts()
2271    }
2272
2273    fn tool_outcome(&self) -> Option<adk_core::ToolOutcome> {
2274        self.inner.tool_outcome()
2275    }
2276
2277    fn tool_name(&self) -> Option<&str> {
2278        self.inner.tool_name()
2279    }
2280
2281    fn tool_input(&self) -> Option<&serde_json::Value> {
2282        self.inner.tool_input()
2283    }
2284
2285    fn shared_state(&self) -> Option<Arc<adk_core::SharedState>> {
2286        self.inner.shared_state()
2287    }
2288}
2289
2290#[async_trait]
2291impl InvocationContext for TeamInvocationContext {
2292    fn agent(&self) -> Arc<dyn Agent> {
2293        self.agent.clone()
2294    }
2295
2296    fn memory(&self) -> Option<Arc<dyn adk_core::Memory>> {
2297        self.inner.memory()
2298    }
2299
2300    fn session(&self) -> &dyn adk_core::Session {
2301        self.inner.session()
2302    }
2303
2304    fn run_config(&self) -> &RunConfig {
2305        &self.config
2306    }
2307
2308    fn end_invocation(&self) {
2309        self.inner.end_invocation();
2310    }
2311
2312    fn ended(&self) -> bool {
2313        self.inner.ended()
2314    }
2315
2316    fn is_cancelled(&self) -> bool {
2317        self.inner.is_cancelled()
2318    }
2319
2320    fn user_scopes(&self) -> Vec<String> {
2321        self.inner.user_scopes()
2322    }
2323
2324    fn request_metadata(&self) -> HashMap<String, serde_json::Value> {
2325        self.inner.request_metadata()
2326    }
2327
2328    fn authoritative_transfer_targets(&self) -> bool {
2329        true
2330    }
2331
2332    fn delegation_depth(&self) -> u32 {
2333        self.inner.delegation_depth()
2334    }
2335
2336    fn max_delegation_depth(&self) -> Option<u32> {
2337        Some(
2338            self.inner.max_delegation_depth().map_or(self.max_delegation_depth, |current| {
2339                current.min(self.max_delegation_depth)
2340            }),
2341        )
2342    }
2343
2344    fn orchestration_root_invocation_id(&self) -> &str {
2345        self.inner.orchestration_root_invocation_id()
2346    }
2347
2348    fn orchestration_edge_id(&self) -> Option<&str> {
2349        self.inner.orchestration_edge_id()
2350    }
2351
2352    fn requires_tool_confirmation(&self, tool_name: &str) -> bool {
2353        self.required_confirmations.contains(tool_name)
2354            || self.inner.requires_tool_confirmation(tool_name)
2355    }
2356
2357    fn steering_inbox(&self) -> Option<adk_core::SteeringInbox> {
2358        self.inner.steering_inbox()
2359    }
2360
2361    async fn get_secret(&self, name: &str) -> Result<Option<String>> {
2362        self.inner.get_secret(name).await
2363    }
2364
2365    async fn get_secret_for(&self, request: &adk_core::SecretRequest) -> Result<Option<String>> {
2366        self.inner.get_secret_for(request).await
2367    }
2368}
2369
2370#[cfg(feature = "team-tools")]
2371struct TeamToolset {
2372    name: String,
2373    tools: Vec<Arc<dyn Tool>>,
2374}
2375
2376#[cfg(feature = "team-tools")]
2377#[async_trait]
2378impl Toolset for TeamToolset {
2379    fn name(&self) -> &str {
2380        &self.name
2381    }
2382
2383    async fn tools(&self, _ctx: Arc<dyn adk_core::ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>> {
2384        Ok(self.tools.clone())
2385    }
2386}
2387
2388#[cfg(feature = "team-tools")]
2389struct BoundedDelegateTool {
2390    inner: Arc<dyn Tool>,
2391    fallback: Option<Arc<dyn Tool>>,
2392    limiter: Arc<tokio::sync::Semaphore>,
2393    relationship: TeamRelationship,
2394    team_failure: TeamFailurePolicy,
2395    runtime: Arc<TeamRuntimeRegistry>,
2396    circuit: Arc<Mutex<CircuitState>>,
2397}
2398
2399#[cfg(feature = "team-tools")]
2400#[derive(Default)]
2401struct CircuitState {
2402    consecutive_failures: u32,
2403    opened_at: Option<std::time::Instant>,
2404}
2405
2406#[cfg(feature = "team-tools")]
2407#[async_trait]
2408impl Tool for BoundedDelegateTool {
2409    fn name(&self) -> &str {
2410        self.inner.name()
2411    }
2412
2413    fn description(&self) -> &str {
2414        self.inner.description()
2415    }
2416
2417    fn declaration(&self) -> serde_json::Value {
2418        self.inner.declaration()
2419    }
2420
2421    fn enhanced_description(&self) -> String {
2422        self.inner.enhanced_description()
2423    }
2424
2425    fn is_long_running(&self) -> bool {
2426        self.inner.is_long_running()
2427    }
2428
2429    fn is_builtin(&self) -> bool {
2430        self.inner.is_builtin()
2431    }
2432
2433    fn parameters_schema(&self) -> Option<serde_json::Value> {
2434        self.inner.parameters_schema()
2435    }
2436
2437    fn response_schema(&self) -> Option<serde_json::Value> {
2438        self.inner.response_schema()
2439    }
2440
2441    fn required_scopes(&self) -> &[&str] {
2442        self.inner.required_scopes()
2443    }
2444
2445    fn is_read_only(&self) -> bool {
2446        self.inner.is_read_only()
2447    }
2448
2449    fn is_concurrency_safe(&self) -> bool {
2450        self.inner.is_concurrency_safe()
2451    }
2452
2453    fn is_agent_delegation(&self) -> bool {
2454        self.inner.is_agent_delegation()
2455    }
2456
2457    fn effect(&self) -> adk_core::ToolEffect {
2458        self.inner.effect()
2459    }
2460
2461    fn egress(&self, args: &serde_json::Value) -> adk_core::egress::ToolEgress {
2462        self.inner.egress(args)
2463    }
2464
2465    fn approval_evidence(&self, args: &serde_json::Value) -> Vec<adk_core::Evidence> {
2466        self.inner.approval_evidence(args)
2467    }
2468
2469    fn batch_group(&self) -> Option<adk_core::BatchGroup> {
2470        self.inner.batch_group()
2471    }
2472
2473    fn origin(&self) -> &str {
2474        self.inner.origin()
2475    }
2476
2477    fn timeout_override(&self) -> Option<Option<std::time::Duration>> {
2478        self.inner.timeout_override()
2479    }
2480
2481    async fn execute(
2482        &self,
2483        ctx: Arc<dyn adk_core::ToolContext>,
2484        args: serde_json::Value,
2485    ) -> Result<serde_json::Value> {
2486        let _permit = self.limiter.acquire().await.map_err(|_| {
2487            adk_core::AdkError::new(
2488                adk_core::ErrorComponent::Tool,
2489                adk_core::ErrorCategory::Unavailable,
2490                "tool.team.delegation_limiter_closed",
2491                "team delegation limiter was closed",
2492            )
2493        })?;
2494        let root_invocation_id = ctx.orchestration_root_invocation_id().to_string();
2495        self.runtime.check_budget(&root_invocation_id)?;
2496        if let Some(schema) = &self.relationship.policy.input_schema {
2497            let validator = jsonschema::validator_for(schema).map_err(|error| {
2498                adk_core::AdkError::new(
2499                    adk_core::ErrorComponent::Tool,
2500                    adk_core::ErrorCategory::Internal,
2501                    "tool.team.invalid_compiled_input_schema",
2502                    format!("invalid relationship input schema: {error}"),
2503                )
2504            })?;
2505            if !validator.is_valid(&args) {
2506                return Err(adk_core::AdkError::new(
2507                    adk_core::ErrorComponent::Tool,
2508                    adk_core::ErrorCategory::InvalidInput,
2509                    "tool.team.delegate_input_invalid",
2510                    format!(
2511                        "arguments for delegation from '{}' to '{}' do not satisfy the relationship input schema",
2512                        self.relationship.from, self.relationship.to
2513                    ),
2514                ));
2515            }
2516        }
2517        if let Some(policy) = self.relationship.policy.circuit_breaker {
2518            let mut circuit = self.circuit.lock().unwrap_or_else(|error| error.into_inner());
2519            if let Some(opened_at) = circuit.opened_at {
2520                if opened_at.elapsed() < std::time::Duration::from_millis(policy.reset_after_ms) {
2521                    return self.handle_failure(format!(
2522                        "delegation circuit from '{}' to '{}' is open",
2523                        self.relationship.from, self.relationship.to
2524                    ));
2525                }
2526                circuit.opened_at = None;
2527            }
2528        }
2529
2530        let execution_id = ctx.orchestration_edge_id().map_or_else(
2531            || ctx.function_call_id().to_string(),
2532            |parent| format!("{parent}/{}", ctx.function_call_id()),
2533        );
2534        let lifecycle = TeamLifecycleContext {
2535            team: self.runtime.team_name().to_string(),
2536            invocation_id: root_invocation_id.clone(),
2537            phase: TeamLifecyclePhase::Relationship,
2538            member: None,
2539            edge_id: Some(execution_id.clone()),
2540            from: Some(self.relationship.from.clone()),
2541            to: Some(self.relationship.to.clone()),
2542            kind: Some(RelationshipKind::Delegate),
2543            attempt: Some(1),
2544        };
2545        let relationship_span = adk_telemetry::team_relationship_span_with_context(
2546            self.runtime.team_name(),
2547            &self.relationship.from,
2548            &self.relationship.to,
2549            "delegate",
2550            &execution_id,
2551            &root_invocation_id,
2552            ctx.session_id(),
2553        );
2554        let relationship_started = std::time::Instant::now();
2555        if let TeamLifecycleDecision::Terminate { reason } =
2556            self.runtime.before_lifecycle(&lifecycle).instrument(relationship_span.clone()).await?
2557        {
2558            self.runtime
2559                .after_lifecycle(
2560                    &lifecycle,
2561                    &TeamLifecycleOutcome::Terminated { reason: reason.clone() },
2562                )
2563                .await?;
2564            return Err(TeamRuntimeError::PolicyDenied {
2565                operation: format!(
2566                    "delegation from '{}' to '{}'",
2567                    self.relationship.from, self.relationship.to
2568                ),
2569                reason,
2570            }
2571            .into());
2572        }
2573        self.runtime.start_edge(
2574            &root_invocation_id,
2575            TeamEdgeStart {
2576                execution_id: Some(execution_id.clone()),
2577                parent_id: ctx.orchestration_edge_id().map(str::to_string),
2578                from: &self.relationship.from,
2579                to: &self.relationship.to,
2580                kind: RelationshipKind::Delegate,
2581                attempt: 1,
2582            },
2583        )?;
2584        let mut checkpoint = adk_core::Event::new(ctx.invocation_id());
2585        checkpoint.author = self.relationship.from.clone();
2586        self.runtime.record_event(&root_invocation_id, Some(&execution_id), &mut checkpoint)?;
2587        ctx.emit_event(checkpoint).await;
2588
2589        let (max_attempts, backoff_ms) = match self.relationship.policy.failure {
2590            RelationshipFailureStrategy::Retry { max_attempts, backoff_ms }
2591            | RelationshipFailureStrategy::RetryThenFallback { max_attempts, backoff_ms, .. } => {
2592                (max_attempts, backoff_ms)
2593            }
2594            RelationshipFailureStrategy::Inherit
2595            | RelationshipFailureStrategy::Propagate
2596            | RelationshipFailureStrategy::ReturnError
2597            | RelationshipFailureStrategy::Fallback { .. } => (1, 0),
2598        };
2599        let mut last_error = None;
2600        for attempt in 1..=max_attempts {
2601            match self
2602                .inner
2603                .execute(ctx.clone(), args.clone())
2604                .instrument(relationship_span.clone())
2605                .await
2606            {
2607                Ok(value) => {
2608                    if let Some(schema) = &self.relationship.policy.output_schema {
2609                        let validator = jsonschema::validator_for(schema).map_err(|error| {
2610                            adk_core::AdkError::new(
2611                                adk_core::ErrorComponent::Tool,
2612                                adk_core::ErrorCategory::Internal,
2613                                "tool.team.invalid_compiled_output_schema",
2614                                format!("invalid relationship output schema: {error}"),
2615                            )
2616                        })?;
2617                        if !validator.is_valid(&value) {
2618                            last_error = Some(format!(
2619                                "delegate '{}' returned a value that does not satisfy the relationship output schema",
2620                                self.relationship.to
2621                            ));
2622                        } else {
2623                            self.record_success(&root_invocation_id, &execution_id, &lifecycle)
2624                                .await?;
2625                            relationship_span.record("team.status", "completed");
2626                            relationship_span.record(
2627                                "team.duration_ms",
2628                                relationship_started.elapsed().as_millis() as u64,
2629                            );
2630                            return Ok(value);
2631                        }
2632                    } else {
2633                        self.record_success(&root_invocation_id, &execution_id, &lifecycle).await?;
2634                        relationship_span.record("team.status", "completed");
2635                        relationship_span.record(
2636                            "team.duration_ms",
2637                            relationship_started.elapsed().as_millis() as u64,
2638                        );
2639                        return Ok(value);
2640                    }
2641                }
2642                Err(error) => last_error = Some(error.to_string()),
2643            }
2644            if attempt < max_attempts && backoff_ms > 0 {
2645                tokio::time::sleep(std::time::Duration::from_millis(backoff_ms)).await;
2646            }
2647        }
2648
2649        if let Some(fallback) = &self.fallback {
2650            match fallback.execute(ctx, args).await {
2651                Ok(value) => {
2652                    self.record_success(&root_invocation_id, &execution_id, &lifecycle).await?;
2653                    relationship_span.record("team.status", "completed");
2654                    relationship_span.record(
2655                        "team.duration_ms",
2656                        relationship_started.elapsed().as_millis() as u64,
2657                    );
2658                    return Ok(value);
2659                }
2660                Err(error) => {
2661                    last_error = Some(format!(
2662                        "primary delegate '{}' failed and fallback '{}' also failed: {error}",
2663                        self.relationship.to,
2664                        fallback.name()
2665                    ));
2666                }
2667            }
2668        }
2669
2670        let error = last_error.unwrap_or_else(|| "delegated execution failed".to_string());
2671        self.runtime.finish_edge(&root_invocation_id, &execution_id, Some(error.clone()));
2672        if let Some(policy) = self.relationship.policy.circuit_breaker {
2673            let mut circuit = self.circuit.lock().unwrap_or_else(|failure| failure.into_inner());
2674            circuit.consecutive_failures = circuit.consecutive_failures.saturating_add(1);
2675            if circuit.consecutive_failures >= policy.failure_threshold {
2676                circuit.opened_at = Some(std::time::Instant::now());
2677            }
2678        }
2679        self.runtime
2680            .after_lifecycle(
2681                &lifecycle,
2682                &TeamLifecycleOutcome::Failed { code: None, message: error.clone() },
2683            )
2684            .await?;
2685        relationship_span.record("team.status", "failed");
2686        relationship_span
2687            .record("team.duration_ms", relationship_started.elapsed().as_millis() as u64);
2688        self.handle_failure(error)
2689    }
2690}
2691
2692#[cfg(feature = "team-tools")]
2693impl BoundedDelegateTool {
2694    async fn record_success(
2695        &self,
2696        invocation_id: &str,
2697        execution_id: &str,
2698        lifecycle: &TeamLifecycleContext,
2699    ) -> Result<()> {
2700        self.runtime.finish_edge(invocation_id, execution_id, None);
2701        {
2702            let mut circuit = self.circuit.lock().unwrap_or_else(|error| error.into_inner());
2703            circuit.consecutive_failures = 0;
2704            circuit.opened_at = None;
2705        }
2706        self.runtime.after_lifecycle(lifecycle, &TeamLifecycleOutcome::Succeeded).await
2707    }
2708
2709    fn handle_failure(&self, error: String) -> Result<serde_json::Value> {
2710        let return_error =
2711            matches!(self.relationship.policy.failure, RelationshipFailureStrategy::ReturnError)
2712                || matches!(self.relationship.policy.failure, RelationshipFailureStrategy::Inherit)
2713                    && self.team_failure == TeamFailurePolicy::ReturnDelegateError;
2714        if return_error {
2715            Ok(serde_json::json!({
2716                "error": error,
2717                "agent": self.relationship.to,
2718            }))
2719        } else {
2720            Err(adk_core::AdkError::new(
2721                adk_core::ErrorComponent::Tool,
2722                adk_core::ErrorCategory::Internal,
2723                "tool.team.delegation_failed",
2724                error,
2725            ))
2726        }
2727    }
2728}
2729
2730#[cfg(test)]
2731mod tests {
2732    use super::*;
2733    use adk_core::{Content, Event, EventStream, ReadonlyContext, Session, State};
2734    use async_stream::stream;
2735    use std::sync::atomic::{AtomicUsize, Ordering};
2736
2737    struct StubAgent(String);
2738
2739    #[async_trait]
2740    impl Agent for StubAgent {
2741        fn name(&self) -> &str {
2742            &self.0
2743        }
2744
2745        fn description(&self) -> &str {
2746            "stub"
2747        }
2748
2749        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
2750            &[]
2751        }
2752
2753        fn capabilities(&self) -> adk_core::AgentCapabilities {
2754            adk_core::AgentCapabilities {
2755                runtime_tools: true,
2756                handoff: true,
2757                relationship_confirmation: true,
2758                checkpoint_resume: false,
2759                shared_state: true,
2760                invocation_metadata: true,
2761            }
2762        }
2763
2764        async fn run(&self, _ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
2765            Ok(Box::pin(stream! { yield Ok(Event::new("stub")); }))
2766        }
2767    }
2768
2769    struct TestState;
2770
2771    impl State for TestState {
2772        fn get(&self, _key: &str) -> Option<serde_json::Value> {
2773            None
2774        }
2775
2776        fn set(&mut self, _key: String, _value: serde_json::Value) {}
2777
2778        fn all(&self) -> HashMap<String, serde_json::Value> {
2779            HashMap::new()
2780        }
2781    }
2782
2783    struct TestSession;
2784
2785    impl Session for TestSession {
2786        fn id(&self) -> &str {
2787            "team-session"
2788        }
2789
2790        fn app_name(&self) -> &str {
2791            "team-app"
2792        }
2793
2794        fn user_id(&self) -> &str {
2795            "team-user"
2796        }
2797
2798        fn state(&self) -> &dyn State {
2799            &TestState
2800        }
2801
2802        fn conversation_history(&self) -> Vec<Content> {
2803            Vec::new()
2804        }
2805    }
2806
2807    struct TestContext {
2808        content: Content,
2809        config: RunConfig,
2810        session: TestSession,
2811    }
2812
2813    #[async_trait]
2814    impl ReadonlyContext for TestContext {
2815        fn invocation_id(&self) -> &str {
2816            "team-invocation"
2817        }
2818
2819        fn agent_name(&self) -> &str {
2820            "support_team"
2821        }
2822
2823        fn user_id(&self) -> &str {
2824            "team-user"
2825        }
2826
2827        fn app_name(&self) -> &str {
2828            "team-app"
2829        }
2830
2831        fn session_id(&self) -> &str {
2832            "team-session"
2833        }
2834
2835        fn branch(&self) -> &str {
2836            ""
2837        }
2838
2839        fn user_content(&self) -> &Content {
2840            &self.content
2841        }
2842    }
2843
2844    #[async_trait]
2845    impl adk_core::CallbackContext for TestContext {
2846        fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
2847            None
2848        }
2849    }
2850
2851    #[async_trait]
2852    impl InvocationContext for TestContext {
2853        fn agent(&self) -> Arc<dyn Agent> {
2854            panic!("agent identity is not used by this test")
2855        }
2856
2857        fn memory(&self) -> Option<Arc<dyn adk_core::Memory>> {
2858            None
2859        }
2860
2861        fn session(&self) -> &dyn Session {
2862            &self.session
2863        }
2864
2865        fn run_config(&self) -> &RunConfig {
2866            &self.config
2867        }
2868
2869        fn end_invocation(&self) {}
2870
2871        fn ended(&self) -> bool {
2872            false
2873        }
2874    }
2875
2876    fn valid_spec() -> TeamSpec {
2877        TeamSpec {
2878            name: "support_team".to_string(),
2879            description: "Routes support work".to_string(),
2880            coordinator: "supervisor".to_string(),
2881            members: vec![
2882                TeamMemberSpec::new("supervisor"),
2883                TeamMemberSpec::new("billing"),
2884                TeamMemberSpec::new("technical"),
2885            ],
2886            relationships: vec![
2887                TeamRelationship::new("supervisor", "billing", RelationshipKind::Handoff),
2888                TeamRelationship::new("supervisor", "technical", RelationshipKind::Handoff),
2889            ],
2890            policy: TeamPolicy::default(),
2891        }
2892    }
2893
2894    #[test]
2895    fn validates_and_round_trips_schema() {
2896        let spec = valid_spec();
2897        spec.validate().unwrap();
2898        let json = serde_json::to_string(&spec).unwrap();
2899        assert_eq!(serde_json::from_str::<TeamSpec>(&json).unwrap(), spec);
2900        let schema = schemars::schema_for!(TeamSpec);
2901        assert_eq!(schema.get("title").and_then(serde_json::Value::as_str), Some("TeamSpec"));
2902    }
2903
2904    #[test]
2905    fn rejects_duplicates_cycles_and_unreachable_members() {
2906        let mut duplicate = valid_spec();
2907        duplicate.members.push(TeamMemberSpec::new("billing"));
2908        assert_eq!(duplicate.validate(), Err(TeamError::DuplicateMember("billing".to_string())));
2909
2910        let mut cyclic = valid_spec();
2911        cyclic.relationships.push(TeamRelationship::new(
2912            "billing",
2913            "supervisor",
2914            RelationshipKind::Delegate,
2915        ));
2916        assert!(matches!(cyclic.validate(), Err(TeamError::CyclicTopology(_))));
2917
2918        let mut unreachable = valid_spec();
2919        unreachable.relationships.pop();
2920        assert_eq!(
2921            unreachable.validate(),
2922            Err(TeamError::UnreachableMember("technical".to_string()))
2923        );
2924    }
2925
2926    #[test]
2927    fn validates_relationship_contracts_budgets_and_fallback_edges() {
2928        let mut invalid_schema = valid_spec();
2929        invalid_schema.relationships[0].policy.input_schema = Some(serde_json::json!({"type": 7}));
2930        assert!(matches!(
2931            invalid_schema.validate(),
2932            Err(TeamError::InvalidRelationshipPolicy { .. })
2933        ));
2934
2935        let mut ignored_handoff_contract = valid_spec();
2936        ignored_handoff_contract.relationships[0].policy.input_schema =
2937            Some(serde_json::json!({"type": "object"}));
2938        let error = ignored_handoff_contract.validate().unwrap_err();
2939        assert!(error.to_string().contains("applies only to Delegate"));
2940
2941        let mut zero_budget = valid_spec();
2942        zero_budget.policy.budget.max_events = Some(0);
2943        assert_eq!(zero_budget.validate(), Err(TeamError::InvalidBudget("maxEvents")));
2944
2945        let mut undeclared_fallback = valid_spec();
2946        undeclared_fallback.relationships[0].policy.failure =
2947            RelationshipFailureStrategy::Fallback { target: "supervisor".to_string() };
2948        assert!(matches!(
2949            undeclared_fallback.validate(),
2950            Err(TeamError::InvalidRelationshipPolicy { .. })
2951        ));
2952    }
2953
2954    #[test]
2955    fn compiles_exact_handoff_allowlists() {
2956        let team = valid_spec()
2957            .compile(vec![
2958                Arc::new(StubAgent("supervisor".into())) as Arc<dyn Agent>,
2959                Arc::new(StubAgent("billing".into())),
2960                Arc::new(StubAgent("technical".into())),
2961            ])
2962            .unwrap();
2963        assert_eq!(
2964            team.transfer_targets_for("supervisor").unwrap(),
2965            vec!["billing".to_string(), "technical".to_string()]
2966        );
2967        assert_eq!(team.transfer_targets_for("billing"), Some(Vec::new()));
2968        assert!(team.strict_transfer_policy());
2969        let topology = team.topology().unwrap();
2970        assert_eq!(topology.root, "support_team");
2971        assert_eq!(topology.coordinator, "supervisor");
2972        assert_eq!(topology.members.len(), 3);
2973        assert!(topology.members[0].coordinator);
2974        assert_eq!(topology.relationships.len(), 2);
2975        assert!(topology.relationships.iter().all(|relationship| {
2976            relationship.kind == adk_core::AgentRelationshipKind::Handoff
2977                && relationship.from == "supervisor"
2978        }));
2979    }
2980
2981    /// A member that sets its own run policy, as a governed harness does in `configure_run`.
2982    struct PolicyAgent(String);
2983
2984    #[async_trait]
2985    impl Agent for PolicyAgent {
2986        fn name(&self) -> &str {
2987            &self.0
2988        }
2989
2990        fn description(&self) -> &str {
2991            "applies its own run policy"
2992        }
2993
2994        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
2995            &[]
2996        }
2997
2998        fn configure_run(&self, _agent_name: &str, config: &mut RunConfig) {
2999            config.history_max_events = Some(7);
3000            config.transfer_targets = vec!["anywhere".to_string()];
3001        }
3002
3003        async fn run(&self, _ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
3004            Ok(Box::pin(stream! { yield Ok(Event::new("policy")); }))
3005        }
3006    }
3007
3008    /// A member's own `configure_run` applies to its runs, and the team's transfer targets
3009    /// still take precedence (spec 3.5 §7.19: a harness member runs governed).
3010    #[test]
3011    fn a_member_applies_its_own_run_policy_under_the_teams() {
3012        let team = valid_spec()
3013            .compile(vec![
3014                Arc::new(PolicyAgent("supervisor".into())) as Arc<dyn Agent>,
3015                Arc::new(PolicyAgent("billing".into())),
3016                Arc::new(StubAgent("technical".into())),
3017            ])
3018            .unwrap();
3019        let mut coordinator = RunConfig::default();
3020        team.configure_run("support_team", &mut coordinator);
3021        assert_eq!(coordinator.history_max_events, Some(7));
3022        assert_eq!(coordinator.transfer_targets, ["billing", "technical"]);
3023
3024        let mut billing = RunConfig::default();
3025        team.configure_run("billing", &mut billing);
3026        assert_eq!(billing.history_max_events, Some(7));
3027        assert!(billing.transfer_targets.is_empty(), "billing hands off to no one");
3028
3029        let mut technical = RunConfig::default();
3030        team.configure_run("technical", &mut technical);
3031        assert_eq!(technical.history_max_events, None, "a member without a policy adds none");
3032    }
3033
3034    #[test]
3035    fn rejects_missing_agent_binding() {
3036        let error = valid_spec()
3037            .compile(vec![
3038                Arc::new(StubAgent("supervisor".into())) as Arc<dyn Agent>,
3039                Arc::new(StubAgent("billing".into())),
3040            ])
3041            .unwrap_err();
3042        assert_eq!(error, TeamError::MissingAgent("technical".to_string()));
3043    }
3044
3045    struct EmittingAgent {
3046        name: String,
3047        target: Option<String>,
3048        runs: Arc<AtomicUsize>,
3049    }
3050
3051    #[cfg(feature = "team-tools")]
3052    struct FlakyAgent {
3053        name: String,
3054        failures_before_success: usize,
3055        runs: Arc<AtomicUsize>,
3056    }
3057
3058    #[cfg(feature = "team-tools")]
3059    #[async_trait]
3060    impl Agent for FlakyAgent {
3061        fn name(&self) -> &str {
3062            &self.name
3063        }
3064
3065        fn description(&self) -> &str {
3066            "deterministic failure test member"
3067        }
3068
3069        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
3070            &[]
3071        }
3072
3073        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
3074            let attempt = self.runs.fetch_add(1, Ordering::SeqCst) + 1;
3075            if attempt <= self.failures_before_success {
3076                return Err(adk_core::AdkError::agent(format!(
3077                    "planned failure from '{}'",
3078                    self.name
3079                )));
3080            }
3081            let mut event = Event::new(ctx.invocation_id());
3082            event.author = self.name.clone();
3083            event.llm_response.content = Some(Content::new("model").with_text("recovered"));
3084            Ok(Box::pin(stream! { yield Ok(event); }))
3085        }
3086    }
3087
3088    #[async_trait]
3089    impl Agent for EmittingAgent {
3090        fn name(&self) -> &str {
3091            &self.name
3092        }
3093
3094        fn description(&self) -> &str {
3095            "deterministic test member"
3096        }
3097
3098        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
3099            &[]
3100        }
3101
3102        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
3103            self.runs.fetch_add(1, Ordering::SeqCst);
3104            let mut event = Event::new(ctx.invocation_id());
3105            event.author = self.name.clone();
3106            event.actions.transfer_to_agent = self.target.clone();
3107            event.llm_response.content = Some(Content::new("model").with_text(&self.name));
3108            Ok(Box::pin(stream! { yield Ok(event); }))
3109        }
3110    }
3111
3112    #[tokio::test]
3113    async fn handoff_transfers_control_without_invoking_target_inline() {
3114        let supervisor_runs = Arc::new(AtomicUsize::new(0));
3115        let specialist_runs = Arc::new(AtomicUsize::new(0));
3116        let team = TeamSpec {
3117            name: "handoff_team".to_string(),
3118            description: String::new(),
3119            coordinator: "supervisor".to_string(),
3120            members: vec![TeamMemberSpec::new("supervisor"), TeamMemberSpec::new("specialist")],
3121            relationships: vec![TeamRelationship::new(
3122                "supervisor",
3123                "specialist",
3124                RelationshipKind::Handoff,
3125            )],
3126            policy: TeamPolicy::default(),
3127        }
3128        .compile(vec![
3129            Arc::new(EmittingAgent {
3130                name: "supervisor".to_string(),
3131                target: Some("specialist".to_string()),
3132                runs: supervisor_runs.clone(),
3133            }) as Arc<dyn Agent>,
3134            Arc::new(EmittingAgent {
3135                name: "specialist".to_string(),
3136                target: None,
3137                runs: specialist_runs.clone(),
3138            }),
3139        ])
3140        .unwrap();
3141        let context = Arc::new(TestContext {
3142            content: Content::new("user").with_text("route"),
3143            config: RunConfig::default(),
3144            session: TestSession,
3145        });
3146        let events = team.run(context).await.unwrap().collect::<Vec<_>>().await;
3147        assert_eq!(events.len(), 1);
3148        assert_eq!(
3149            events[0].as_ref().unwrap().actions.transfer_to_agent.as_deref(),
3150            Some("specialist")
3151        );
3152        assert_eq!(supervisor_runs.load(Ordering::SeqCst), 1);
3153        assert_eq!(specialist_runs.load(Ordering::SeqCst), 0);
3154    }
3155
3156    #[tokio::test]
3157    async fn restored_active_handoff_resumes_at_frozen_target() {
3158        let supervisor_runs = Arc::new(AtomicUsize::new(0));
3159        let specialist_runs = Arc::new(AtomicUsize::new(0));
3160        let team = TeamSpec {
3161            name: "resume_team".to_string(),
3162            description: String::new(),
3163            coordinator: "supervisor".to_string(),
3164            members: vec![TeamMemberSpec::new("supervisor"), TeamMemberSpec::new("specialist")],
3165            relationships: vec![TeamRelationship::new(
3166                "supervisor",
3167                "specialist",
3168                RelationshipKind::Handoff,
3169            )],
3170            policy: TeamPolicy::default(),
3171        }
3172        .compile([
3173            Arc::new(EmittingAgent {
3174                name: "supervisor".to_string(),
3175                target: Some("specialist".to_string()),
3176                runs: supervisor_runs.clone(),
3177            }) as Arc<dyn Agent>,
3178            Arc::new(EmittingAgent {
3179                name: "specialist".to_string(),
3180                target: None,
3181                runs: specialist_runs.clone(),
3182            }),
3183        ])
3184        .unwrap();
3185        team.runtime
3186            .start_edge(
3187                "team-invocation",
3188                TeamEdgeStart {
3189                    execution_id: Some("persisted-handoff".to_string()),
3190                    parent_id: None,
3191                    from: "supervisor",
3192                    to: "specialist",
3193                    kind: RelationshipKind::Handoff,
3194                    attempt: 1,
3195                },
3196            )
3197            .unwrap();
3198        let context = Arc::new(TestContext {
3199            content: Content::new("user").with_text("resume"),
3200            config: RunConfig::default(),
3201            session: TestSession,
3202        });
3203        let events = team.run(context).await.unwrap().collect::<Vec<_>>().await;
3204        assert_eq!(events.len(), 1);
3205        assert_eq!(events[0].as_ref().unwrap().author, "specialist");
3206        assert_eq!(supervisor_runs.load(Ordering::SeqCst), 0);
3207        assert_eq!(specialist_runs.load(Ordering::SeqCst), 1);
3208        assert_eq!(
3209            team.execution_snapshot("team-invocation").unwrap().edges[0].status,
3210            TeamExecutionStatus::Completed
3211        );
3212    }
3213
3214    #[tokio::test]
3215    async fn runner_handoff_keeps_one_completed_team_receipt() {
3216        let supervisor_runs = Arc::new(AtomicUsize::new(0));
3217        let specialist_runs = Arc::new(AtomicUsize::new(0));
3218        let team = Arc::new(
3219            TeamSpec {
3220                name: "runner_receipt_team".to_string(),
3221                description: String::new(),
3222                coordinator: "supervisor".to_string(),
3223                members: vec![TeamMemberSpec::new("supervisor"), TeamMemberSpec::new("specialist")],
3224                relationships: vec![TeamRelationship::new(
3225                    "supervisor",
3226                    "specialist",
3227                    RelationshipKind::Handoff,
3228                )],
3229                policy: TeamPolicy::default(),
3230            }
3231            .compile([
3232                Arc::new(EmittingAgent {
3233                    name: "supervisor".to_string(),
3234                    target: Some("specialist".to_string()),
3235                    runs: supervisor_runs.clone(),
3236                }) as Arc<dyn Agent>,
3237                Arc::new(EmittingAgent {
3238                    name: "specialist".to_string(),
3239                    target: None,
3240                    runs: specialist_runs.clone(),
3241                }),
3242            ])
3243            .unwrap(),
3244        );
3245        let sessions = Arc::new(adk_session::InMemorySessionService::new());
3246        adk_session::SessionService::create(
3247            sessions.as_ref(),
3248            adk_session::CreateRequest {
3249                app_name: "runner-receipt".to_string(),
3250                user_id: "user".to_string(),
3251                session_id: Some("session".to_string()),
3252                state: HashMap::new(),
3253            },
3254        )
3255        .await
3256        .unwrap();
3257        let runner = adk_runner::Runner::builder()
3258            .app_name("runner-receipt")
3259            .agent(team.clone() as Arc<dyn Agent>)
3260            .session_service(sessions)
3261            .build()
3262            .unwrap();
3263        let stream = runner
3264            .run_str("user", "session", Content::new("user").with_text("route"))
3265            .await
3266            .unwrap();
3267        let results = stream.collect::<Vec<_>>().await;
3268        assert!(results.into_iter().all(|result| result.is_ok()));
3269        assert_eq!(supervisor_runs.load(Ordering::SeqCst), 1);
3270        assert_eq!(specialist_runs.load(Ordering::SeqCst), 1);
3271        let receipts = team.execution_snapshots();
3272        assert_eq!(receipts.len(), 1);
3273        assert_eq!(receipts[0].edges.len(), 1);
3274        assert_eq!(receipts[0].edges[0].status, TeamExecutionStatus::Completed);
3275    }
3276
3277    #[tokio::test]
3278    async fn exact_allowlist_rejects_undeclared_handoff() {
3279        let team = valid_spec()
3280            .compile(vec![
3281                Arc::new(EmittingAgent {
3282                    name: "supervisor".to_string(),
3283                    target: Some("undeclared".to_string()),
3284                    runs: Arc::new(AtomicUsize::new(0)),
3285                }) as Arc<dyn Agent>,
3286                Arc::new(StubAgent("billing".to_string())),
3287                Arc::new(StubAgent("technical".to_string())),
3288            ])
3289            .unwrap();
3290        let context = Arc::new(TestContext {
3291            content: Content::new("user").with_text("route"),
3292            config: RunConfig::default(),
3293            session: TestSession,
3294        });
3295        let results = team.run(context).await.unwrap().collect::<Vec<_>>().await;
3296        let error = results[0].as_ref().unwrap_err();
3297        assert_eq!(error.code, "agent.team.policy_denied");
3298        assert!(error.to_string().contains("exact edge is not declared"));
3299    }
3300
3301    #[cfg(feature = "team-tools")]
3302    #[tokio::test]
3303    async fn delegate_edge_lowers_to_only_the_declared_agent_tool() {
3304        let spec = TeamSpec {
3305            name: "delegate_team".to_string(),
3306            description: String::new(),
3307            coordinator: "supervisor".to_string(),
3308            members: vec![TeamMemberSpec::new("supervisor"), TeamMemberSpec::new("researcher")],
3309            relationships: vec![TeamRelationship::new(
3310                "supervisor",
3311                "researcher",
3312                RelationshipKind::Delegate,
3313            )],
3314            policy: TeamPolicy::default(),
3315        };
3316        let team = spec
3317            .compile(vec![
3318                Arc::new(StubAgent("supervisor".to_string())) as Arc<dyn Agent>,
3319                Arc::new(StubAgent("researcher".to_string())),
3320            ])
3321            .unwrap();
3322        let mut config = RunConfig::default();
3323        team.configure_run(team.name(), &mut config);
3324        assert!(config.transfer_targets.is_empty());
3325        assert_eq!(config.runtime_toolsets.len(), 1);
3326        let context = Arc::new(TestContext {
3327            content: Content::new("user").with_text("research"),
3328            config: config.clone(),
3329            session: TestSession,
3330        });
3331        let tools = config.runtime_toolsets[0]
3332            .toolset()
3333            .tools(context as Arc<dyn ReadonlyContext>)
3334            .await
3335            .unwrap();
3336        assert_eq!(tools.iter().map(|tool| tool.name()).collect::<Vec<_>>(), vec!["researcher"]);
3337    }
3338
3339    #[cfg(feature = "team-tools")]
3340    struct ScriptedModel {
3341        responses: std::sync::Mutex<std::collections::VecDeque<adk_core::LlmResponse>>,
3342        /// Conversation contents of every request, in call order.
3343        requests: std::sync::Mutex<Vec<Vec<Content>>>,
3344    }
3345
3346    #[cfg(feature = "team-tools")]
3347    impl ScriptedModel {
3348        fn new(responses: Vec<adk_core::LlmResponse>) -> Self {
3349            Self {
3350                responses: std::sync::Mutex::new(responses.into()),
3351                requests: std::sync::Mutex::new(Vec::new()),
3352            }
3353        }
3354
3355        fn text(text: &str) -> adk_core::LlmResponse {
3356            adk_core::LlmResponse {
3357                content: Some(Content::new("model").with_text(text)),
3358                usage_metadata: None,
3359                finish_reason: Some(adk_core::FinishReason::Stop),
3360                citation_metadata: None,
3361                partial: false,
3362                turn_complete: true,
3363                interrupted: false,
3364                error_code: None,
3365                error_message: None,
3366                provider_metadata: None,
3367                interaction_id: None,
3368                model: None,
3369                provider: None,
3370            }
3371        }
3372
3373        fn call(name: &str) -> adk_core::LlmResponse {
3374            adk_core::LlmResponse {
3375                content: Some(Content {
3376                    role: "model".to_string(),
3377                    parts: vec![adk_core::Part::FunctionCall {
3378                        name: name.to_string(),
3379                        args: serde_json::json!({"request": "research this"}),
3380                        id: Some("delegate-1".to_string()),
3381                        thought_signature: None,
3382                    }],
3383                }),
3384                ..Self::text("")
3385            }
3386        }
3387
3388        fn transfer(target: &str) -> adk_core::LlmResponse {
3389            adk_core::LlmResponse {
3390                content: Some(Content {
3391                    role: "model".to_string(),
3392                    parts: vec![adk_core::Part::FunctionCall {
3393                        name: "transfer_to_agent".to_string(),
3394                        args: serde_json::json!({"agent_name": target}),
3395                        id: Some("handoff-1".to_string()),
3396                        thought_signature: None,
3397                    }],
3398                }),
3399                ..Self::text("")
3400            }
3401        }
3402    }
3403
3404    #[cfg(feature = "team-tools")]
3405    #[async_trait]
3406    impl adk_core::Llm for ScriptedModel {
3407        fn name(&self) -> &str {
3408            "scripted-team-model"
3409        }
3410
3411        async fn generate_content(
3412            &self,
3413            request: adk_core::LlmRequest,
3414            _stream: bool,
3415        ) -> Result<adk_core::LlmResponseStream> {
3416            self.requests.lock().expect("request log lock").push(request.contents);
3417            let response = self
3418                .responses
3419                .lock()
3420                .expect("script lock")
3421                .pop_front()
3422                .expect("script should have another response");
3423            Ok(Box::pin(stream! { yield Ok(response); }))
3424        }
3425    }
3426
3427    #[cfg(feature = "team-tools")]
3428    #[tokio::test]
3429    async fn delegation_returns_to_the_scripted_supervisor() {
3430        let supervisor = Arc::new(
3431            crate::LlmAgentBuilder::new("supervisor")
3432                .model(Arc::new(ScriptedModel::new(vec![
3433                    ScriptedModel::call("researcher"),
3434                    ScriptedModel::text("supervisor final"),
3435                ])))
3436                .build()
3437                .unwrap(),
3438        ) as Arc<dyn Agent>;
3439        let researcher = Arc::new(
3440            crate::LlmAgentBuilder::new("researcher")
3441                .model(Arc::new(ScriptedModel::new(vec![ScriptedModel::text("research result")])))
3442                .build()
3443                .unwrap(),
3444        ) as Arc<dyn Agent>;
3445        let team = TeamSpec {
3446            name: "scripted_delegate_team".to_string(),
3447            description: String::new(),
3448            coordinator: "supervisor".to_string(),
3449            members: vec![TeamMemberSpec::new("supervisor"), TeamMemberSpec::new("researcher")],
3450            relationships: vec![TeamRelationship::new(
3451                "supervisor",
3452                "researcher",
3453                RelationshipKind::Delegate,
3454            )],
3455            policy: TeamPolicy::default(),
3456        }
3457        .compile([supervisor, researcher])
3458        .unwrap();
3459        let context = Arc::new(TestContext {
3460            content: Content::new("user").with_text("delegate"),
3461            config: RunConfig::default(),
3462            session: TestSession,
3463        });
3464        let results = team.run(context).await.unwrap().collect::<Vec<_>>().await;
3465        let events = results.into_iter().collect::<Result<Vec<_>>>().unwrap();
3466        assert!(events.iter().any(|event| event.author == "researcher"));
3467        assert!(events.iter().all(|event| event.actions.transfer_to_agent.is_none()));
3468        let active_receipt = events
3469            .iter()
3470            .filter_map(|event| event.actions.state_delta.get(TEAM_EXECUTION_STATE_KEY))
3471            .filter_map(|value| serde_json::from_value::<TeamExecutionSnapshot>(value.clone()).ok())
3472            .find(|snapshot| {
3473                snapshot
3474                    .edges
3475                    .first()
3476                    .is_some_and(|edge| edge.status == TeamExecutionStatus::Running)
3477            })
3478            .expect("delegate start should emit a durable receipt before child execution");
3479        assert_eq!(active_receipt.edges[0].status, TeamExecutionStatus::Running);
3480        assert!(events.iter().any(|event| {
3481            event.author == "supervisor"
3482                && event
3483                    .content()
3484                    .into_iter()
3485                    .flat_map(|content| &content.parts)
3486                    .any(|part| part.text() == Some("supervisor final"))
3487        }));
3488    }
3489
3490    #[cfg(feature = "team-tools")]
3491    #[tokio::test]
3492    async fn nested_handoff_inside_delegation_is_consumed_losslessly() {
3493        let supervisor = Arc::new(
3494            crate::LlmAgentBuilder::new("supervisor")
3495                .model(Arc::new(ScriptedModel::new(vec![
3496                    ScriptedModel::call("researcher"),
3497                    ScriptedModel::text("supervisor resumed"),
3498                ])))
3499                .build()
3500                .unwrap(),
3501        ) as Arc<dyn Agent>;
3502        let researcher = Arc::new(
3503            crate::LlmAgentBuilder::new("researcher")
3504                .model(Arc::new(ScriptedModel::new(vec![ScriptedModel::transfer("writer")])))
3505                .build()
3506                .unwrap(),
3507        ) as Arc<dyn Agent>;
3508        let writer = Arc::new(
3509            crate::LlmAgentBuilder::new("writer")
3510                .model(Arc::new(ScriptedModel::new(vec![ScriptedModel::text("writer result")])))
3511                .build()
3512                .unwrap(),
3513        ) as Arc<dyn Agent>;
3514        let team = TeamSpec {
3515            name: "nested_team".to_string(),
3516            description: String::new(),
3517            coordinator: "supervisor".to_string(),
3518            members: vec![
3519                TeamMemberSpec::new("supervisor"),
3520                TeamMemberSpec::new("researcher"),
3521                TeamMemberSpec::new("writer"),
3522            ],
3523            relationships: vec![
3524                TeamRelationship::new("supervisor", "researcher", RelationshipKind::Delegate),
3525                TeamRelationship::new("researcher", "writer", RelationshipKind::Handoff),
3526            ],
3527            policy: TeamPolicy::default(),
3528        }
3529        .compile([supervisor, researcher, writer])
3530        .unwrap();
3531        let context = Arc::new(TestContext {
3532            content: Content::new("user").with_text("delegate then hand off"),
3533            config: RunConfig::default(),
3534            session: TestSession,
3535        });
3536        let events = team
3537            .run(context)
3538            .await
3539            .unwrap()
3540            .collect::<Vec<_>>()
3541            .await
3542            .into_iter()
3543            .collect::<Result<Vec<_>>>()
3544            .unwrap();
3545        assert!(events.iter().all(|event| event.actions.transfer_to_agent.is_none()));
3546        assert!(events.iter().any(|event| event.author == "writer"));
3547        assert!(events.iter().any(|event| {
3548            event.author == "supervisor"
3549                && event
3550                    .content()
3551                    .into_iter()
3552                    .flat_map(|content| &content.parts)
3553                    .any(|part| part.text() == Some("supervisor resumed"))
3554        }));
3555        let snapshot = team.execution_snapshot("team-invocation").unwrap();
3556        assert_eq!(snapshot.usage.delegations, 1);
3557        assert_eq!(snapshot.usage.handoffs, 1);
3558        assert_eq!(snapshot.edges[1].parent_id.as_deref(), Some("delegate-1"));
3559    }
3560
3561    #[cfg(feature = "team-tools")]
3562    #[tokio::test]
3563    async fn delegate_retry_and_exact_fallback_are_enforced() {
3564        let supervisor = Arc::new(
3565            crate::LlmAgentBuilder::new("supervisor")
3566                .model(Arc::new(ScriptedModel::new(vec![
3567                    ScriptedModel::call("primary"),
3568                    ScriptedModel::text("supervisor final"),
3569                ])))
3570                .build()
3571                .unwrap(),
3572        ) as Arc<dyn Agent>;
3573        let primary_runs = Arc::new(AtomicUsize::new(0));
3574        let backup_runs = Arc::new(AtomicUsize::new(0));
3575        let primary = Arc::new(FlakyAgent {
3576            name: "primary".to_string(),
3577            failures_before_success: usize::MAX,
3578            runs: primary_runs.clone(),
3579        }) as Arc<dyn Agent>;
3580        let backup = Arc::new(FlakyAgent {
3581            name: "backup".to_string(),
3582            failures_before_success: 0,
3583            runs: backup_runs.clone(),
3584        }) as Arc<dyn Agent>;
3585        let primary_edge =
3586            TeamRelationship::new("supervisor", "primary", RelationshipKind::Delegate).with_policy(
3587                RelationshipPolicy {
3588                    failure: RelationshipFailureStrategy::RetryThenFallback {
3589                        max_attempts: 2,
3590                        backoff_ms: 0,
3591                        target: "backup".to_string(),
3592                    },
3593                    ..RelationshipPolicy::default()
3594                },
3595            );
3596        let team = TeamSpec {
3597            name: "failure_team".to_string(),
3598            description: String::new(),
3599            coordinator: "supervisor".to_string(),
3600            members: vec![
3601                TeamMemberSpec::new("supervisor"),
3602                TeamMemberSpec::new("primary"),
3603                TeamMemberSpec::new("backup"),
3604            ],
3605            relationships: vec![
3606                primary_edge,
3607                TeamRelationship::new("supervisor", "backup", RelationshipKind::Delegate),
3608            ],
3609            policy: TeamPolicy::default(),
3610        }
3611        .compile([supervisor, primary, backup])
3612        .unwrap();
3613        let context = Arc::new(TestContext {
3614            content: Content::new("user").with_text("use a fallback"),
3615            config: RunConfig::default(),
3616            session: TestSession,
3617        });
3618        let events = team
3619            .run(context)
3620            .await
3621            .unwrap()
3622            .collect::<Vec<_>>()
3623            .await
3624            .into_iter()
3625            .collect::<Result<Vec<_>>>()
3626            .unwrap();
3627        assert_eq!(primary_runs.load(Ordering::SeqCst), 2);
3628        assert_eq!(backup_runs.load(Ordering::SeqCst), 1);
3629        assert!(events.iter().any(|event| event.author == "backup"));
3630        assert!(events.iter().any(|event| event.author == "supervisor"));
3631    }
3632
3633    #[cfg(feature = "team-tools")]
3634    #[tokio::test]
3635    async fn relationship_approval_interrupts_before_delegate_execution() {
3636        let supervisor = Arc::new(
3637            crate::LlmAgentBuilder::new("supervisor")
3638                .model(Arc::new(ScriptedModel::new(vec![ScriptedModel::call("researcher")])))
3639                .build()
3640                .unwrap(),
3641        ) as Arc<dyn Agent>;
3642        let researcher_runs = Arc::new(AtomicUsize::new(0));
3643        let researcher = Arc::new(FlakyAgent {
3644            name: "researcher".to_string(),
3645            failures_before_success: 0,
3646            runs: researcher_runs.clone(),
3647        }) as Arc<dyn Agent>;
3648        let team = TeamSpec {
3649            name: "approval_team".to_string(),
3650            description: String::new(),
3651            coordinator: "supervisor".to_string(),
3652            members: vec![TeamMemberSpec::new("supervisor"), TeamMemberSpec::new("researcher")],
3653            relationships: vec![
3654                TeamRelationship::new("supervisor", "researcher", RelationshipKind::Delegate)
3655                    .with_policy(RelationshipPolicy {
3656                        approval: RelationshipApprovalPolicy::Required,
3657                        ..RelationshipPolicy::default()
3658                    }),
3659            ],
3660            policy: TeamPolicy::default(),
3661        }
3662        .compile([supervisor, researcher])
3663        .unwrap();
3664        let context = Arc::new(TestContext {
3665            content: Content::new("user").with_text("approval required"),
3666            config: RunConfig::default(),
3667            session: TestSession,
3668        });
3669        let events = team
3670            .run(context)
3671            .await
3672            .unwrap()
3673            .collect::<Vec<_>>()
3674            .await
3675            .into_iter()
3676            .collect::<Result<Vec<_>>>()
3677            .unwrap();
3678        assert!(events.iter().any(|event| event.actions.tool_confirmation.is_some()));
3679        assert_eq!(researcher_runs.load(Ordering::SeqCst), 0);
3680    }
3681
3682    /// Runs a supervisor whose delegate edge requires approval while its own agent policy is
3683    /// `Never`, with a static decision recorded for the delegate call.
3684    #[cfg(feature = "team-tools")]
3685    async fn run_approved_delegate_with_decision(
3686        decision: adk_core::ToolConfirmationDecision,
3687    ) -> (Vec<Event>, usize, Vec<Vec<Content>>) {
3688        let model = Arc::new(ScriptedModel::new(vec![
3689            ScriptedModel::call("researcher"),
3690            ScriptedModel::text("supervisor final"),
3691        ]));
3692        let supervisor = Arc::new(
3693            crate::LlmAgentBuilder::new("supervisor")
3694                .model(model.clone())
3695                .tool_confirmation_policy(adk_core::ToolConfirmationPolicy::Never)
3696                .build()
3697                .unwrap(),
3698        ) as Arc<dyn Agent>;
3699        let researcher_runs = Arc::new(AtomicUsize::new(0));
3700        let researcher = Arc::new(FlakyAgent {
3701            name: "researcher".to_string(),
3702            failures_before_success: 0,
3703            runs: researcher_runs.clone(),
3704        }) as Arc<dyn Agent>;
3705        let team = TeamSpec {
3706            name: "approval_team".to_string(),
3707            description: String::new(),
3708            coordinator: "supervisor".to_string(),
3709            members: vec![TeamMemberSpec::new("supervisor"), TeamMemberSpec::new("researcher")],
3710            relationships: vec![
3711                TeamRelationship::new("supervisor", "researcher", RelationshipKind::Delegate)
3712                    .with_policy(RelationshipPolicy {
3713                        approval: RelationshipApprovalPolicy::Required,
3714                        ..RelationshipPolicy::default()
3715                    }),
3716            ],
3717            policy: TeamPolicy::default(),
3718        }
3719        .compile([supervisor, researcher])
3720        .unwrap();
3721        let config = RunConfig::builder()
3722            .tool_confirmation_decisions(HashMap::from([("delegate-1".to_string(), decision)]))
3723            .build();
3724        let context = Arc::new(TestContext {
3725            content: Content::new("user").with_text("approval decided"),
3726            config,
3727            session: TestSession,
3728        });
3729        let events = team
3730            .run(context)
3731            .await
3732            .unwrap()
3733            .collect::<Vec<_>>()
3734            .await
3735            .into_iter()
3736            .collect::<Result<Vec<_>>>()
3737            .unwrap();
3738        let requests = model.requests.lock().expect("request log lock").clone();
3739        (events, researcher_runs.load(Ordering::SeqCst), requests)
3740    }
3741
3742    #[cfg(feature = "team-tools")]
3743    #[tokio::test]
3744    async fn relationship_approval_deny_blocks_delegate_execution() {
3745        let (events, researcher_runs, requests) =
3746            run_approved_delegate_with_decision(adk_core::ToolConfirmationDecision::Deny).await;
3747
3748        assert_eq!(researcher_runs, 0);
3749        assert!(events.iter().all(|event| event.actions.tool_confirmation.is_none()));
3750        let denied = serde_json::to_value(Content {
3751            role: "function".to_string(),
3752            parts: vec![adk_core::Part::FunctionResponse {
3753                function_response: adk_core::FunctionResponseData::new(
3754                    "researcher",
3755                    serde_json::json!({
3756                        "error": "Tool 'researcher' execution denied by confirmation policy"
3757                    }),
3758                ),
3759                id: Some("delegate-1".to_string()),
3760                annotations: Some(
3761                    serde_json::json!({ adk_core::TOOL_RESULT_STATUS_KEY: "refused" }),
3762                ),
3763            }],
3764        })
3765        .unwrap();
3766        let denial_event = events
3767            .iter()
3768            .find(|event| {
3769                event.actions.tool_confirmation_decision
3770                    == Some(adk_core::ToolConfirmationDecision::Deny)
3771            })
3772            .expect("the denied delegate call should produce a function response event");
3773        assert_eq!(serde_json::to_value(denial_event.content()).unwrap(), denied);
3774        assert_eq!(requests.len(), 2);
3775        assert!(
3776            requests[1].iter().any(|content| serde_json::to_value(content).unwrap() == denied),
3777            "the follow-up model request should carry the denial"
3778        );
3779    }
3780
3781    #[cfg(feature = "team-tools")]
3782    #[tokio::test]
3783    async fn relationship_approval_approve_runs_delegate() {
3784        let (events, researcher_runs, requests) =
3785            run_approved_delegate_with_decision(adk_core::ToolConfirmationDecision::Approve).await;
3786
3787        assert_eq!(researcher_runs, 1);
3788        assert!(events.iter().all(|event| event.actions.tool_confirmation.is_none()));
3789        assert!(events.iter().any(|event| {
3790            event.actions.tool_confirmation_decision
3791                == Some(adk_core::ToolConfirmationDecision::Approve)
3792        }));
3793        assert!(events.iter().any(|event| event.author == "researcher"));
3794        assert_eq!(requests.len(), 2);
3795    }
3796
3797    #[cfg(feature = "team-tools")]
3798    #[tokio::test]
3799    async fn output_contract_failure_can_return_to_supervisor_as_data() {
3800        let supervisor = Arc::new(
3801            crate::LlmAgentBuilder::new("supervisor")
3802                .model(Arc::new(ScriptedModel::new(vec![
3803                    ScriptedModel::call("researcher"),
3804                    ScriptedModel::text("handled contract failure"),
3805                ])))
3806                .build()
3807                .unwrap(),
3808        ) as Arc<dyn Agent>;
3809        let researcher_runs = Arc::new(AtomicUsize::new(0));
3810        let researcher = Arc::new(FlakyAgent {
3811            name: "researcher".to_string(),
3812            failures_before_success: 0,
3813            runs: researcher_runs.clone(),
3814        }) as Arc<dyn Agent>;
3815        let team = TeamSpec {
3816            name: "contract_team".to_string(),
3817            description: String::new(),
3818            coordinator: "supervisor".to_string(),
3819            members: vec![TeamMemberSpec::new("supervisor"), TeamMemberSpec::new("researcher")],
3820            relationships: vec![
3821                TeamRelationship::new("supervisor", "researcher", RelationshipKind::Delegate)
3822                    .with_policy(RelationshipPolicy {
3823                        output_schema: Some(serde_json::json!({
3824                            "type": "object",
3825                            "properties": { "score": { "type": "number" } },
3826                            "required": ["score"]
3827                        })),
3828                        failure: RelationshipFailureStrategy::ReturnError,
3829                        ..RelationshipPolicy::default()
3830                    }),
3831            ],
3832            policy: TeamPolicy::default(),
3833        }
3834        .compile([supervisor, researcher])
3835        .unwrap();
3836        let context = Arc::new(TestContext {
3837            content: Content::new("user").with_text("validate output"),
3838            config: RunConfig::default(),
3839            session: TestSession,
3840        });
3841        let events = team
3842            .run(context)
3843            .await
3844            .unwrap()
3845            .collect::<Vec<_>>()
3846            .await
3847            .into_iter()
3848            .collect::<Result<Vec<_>>>()
3849            .unwrap();
3850        assert_eq!(researcher_runs.load(Ordering::SeqCst), 1);
3851        assert!(events.iter().any(|event| {
3852            event.author == "supervisor"
3853                && event
3854                    .content()
3855                    .into_iter()
3856                    .flat_map(|content| &content.parts)
3857                    .any(|part| part.text() == Some("handled contract failure"))
3858        }));
3859    }
3860
3861    struct RecordingLifecycleHook {
3862        calls: Arc<std::sync::Mutex<Vec<String>>>,
3863    }
3864
3865    #[async_trait]
3866    impl TeamLifecycleHook for RecordingLifecycleHook {
3867        fn name(&self) -> &str {
3868            "recording"
3869        }
3870
3871        async fn before(&self, context: &TeamLifecycleContext) -> Result<TeamLifecycleDecision> {
3872            self.calls
3873                .lock()
3874                .expect("lifecycle calls lock")
3875                .push(format!("before:{:?}", context.phase));
3876            Ok(TeamLifecycleDecision::Continue)
3877        }
3878
3879        async fn after(
3880            &self,
3881            context: &TeamLifecycleContext,
3882            outcome: &TeamLifecycleOutcome,
3883        ) -> Result<()> {
3884            self.calls
3885                .lock()
3886                .expect("lifecycle calls lock")
3887                .push(format!("after:{:?}:{outcome:?}", context.phase));
3888            Ok(())
3889        }
3890    }
3891
3892    #[tokio::test]
3893    async fn invokes_team_and_member_lifecycle_hooks_around_execution() {
3894        let calls = Arc::new(std::sync::Mutex::new(Vec::new()));
3895        let team = valid_spec()
3896            .compile_with_hooks(
3897                [
3898                    Arc::new(StubAgent("supervisor".into())) as Arc<dyn Agent>,
3899                    Arc::new(StubAgent("billing".into())),
3900                    Arc::new(StubAgent("technical".into())),
3901                ],
3902                [Arc::new(RecordingLifecycleHook { calls: calls.clone() })
3903                    as Arc<dyn TeamLifecycleHook>],
3904            )
3905            .unwrap();
3906        let context = Arc::new(TestContext {
3907            content: Content::new("user").with_text("run hooks"),
3908            config: RunConfig::default(),
3909            session: TestSession,
3910        });
3911        team.run(context)
3912            .await
3913            .unwrap()
3914            .collect::<Vec<_>>()
3915            .await
3916            .into_iter()
3917            .collect::<Result<Vec<_>>>()
3918            .unwrap();
3919        let calls = calls.lock().expect("lifecycle calls lock");
3920        assert_eq!(calls.first().map(String::as_str), Some("before:Team"));
3921        assert!(calls.iter().any(|call| call == "before:Member"));
3922        assert!(calls.iter().any(|call| call.starts_with("after:Member:Succeeded")));
3923        assert!(calls.iter().any(|call| call.starts_with("after:Team:Succeeded")));
3924    }
3925
3926    struct DenyRelationshipHook;
3927
3928    #[async_trait]
3929    impl TeamLifecycleHook for DenyRelationshipHook {
3930        fn name(&self) -> &str {
3931            "deny-relationship"
3932        }
3933
3934        async fn before(&self, context: &TeamLifecycleContext) -> Result<TeamLifecycleDecision> {
3935            if context.phase == TeamLifecyclePhase::Relationship {
3936                Ok(TeamLifecycleDecision::Terminate {
3937                    reason: "operator policy denied transition".to_string(),
3938                })
3939            } else {
3940                Ok(TeamLifecycleDecision::Continue)
3941            }
3942        }
3943    }
3944
3945    #[tokio::test]
3946    async fn relationship_hook_denies_handoff_before_target_runs() {
3947        let supervisor_runs = Arc::new(AtomicUsize::new(0));
3948        let specialist_runs = Arc::new(AtomicUsize::new(0));
3949        let spec = TeamSpec {
3950            name: "governed_handoff".to_string(),
3951            description: String::new(),
3952            coordinator: "supervisor".to_string(),
3953            members: vec![TeamMemberSpec::new("supervisor"), TeamMemberSpec::new("specialist")],
3954            relationships: vec![TeamRelationship::new(
3955                "supervisor",
3956                "specialist",
3957                RelationshipKind::Handoff,
3958            )],
3959            policy: TeamPolicy::default(),
3960        };
3961        let team = spec
3962            .compile_with_hooks(
3963                [
3964                    Arc::new(EmittingAgent {
3965                        name: "supervisor".to_string(),
3966                        target: Some("specialist".to_string()),
3967                        runs: supervisor_runs.clone(),
3968                    }) as Arc<dyn Agent>,
3969                    Arc::new(EmittingAgent {
3970                        name: "specialist".to_string(),
3971                        target: None,
3972                        runs: specialist_runs.clone(),
3973                    }),
3974                ],
3975                [Arc::new(DenyRelationshipHook) as Arc<dyn TeamLifecycleHook>],
3976            )
3977            .unwrap();
3978        let context = Arc::new(TestContext {
3979            content: Content::new("user").with_text("route"),
3980            config: RunConfig::default(),
3981            session: TestSession,
3982        });
3983        let error = team
3984            .run(context)
3985            .await
3986            .unwrap()
3987            .collect::<Vec<_>>()
3988            .await
3989            .into_iter()
3990            .find_map(std::result::Result::err)
3991            .expect("relationship hook should deny handoff");
3992        assert_eq!(error.code, "agent.team.policy_denied");
3993        assert_eq!(supervisor_runs.load(Ordering::SeqCst), 1);
3994        assert_eq!(specialist_runs.load(Ordering::SeqCst), 0);
3995    }
3996
3997    #[cfg(feature = "team-tools")]
3998    struct LegacyRuntimeToolBlindAgent;
3999
4000    #[cfg(feature = "team-tools")]
4001    #[async_trait]
4002    impl Agent for LegacyRuntimeToolBlindAgent {
4003        fn name(&self) -> &str {
4004            "supervisor"
4005        }
4006
4007        fn description(&self) -> &str {
4008            "does not consume runtime tools"
4009        }
4010
4011        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
4012            &[]
4013        }
4014
4015        async fn run(&self, _ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
4016            Ok(Box::pin(futures::stream::empty()))
4017        }
4018    }
4019
4020    #[cfg(feature = "team-tools")]
4021    #[test]
4022    fn compile_rejects_delegate_source_without_runtime_tool_capability() {
4023        let spec = TeamSpec {
4024            name: "capability_team".to_string(),
4025            description: String::new(),
4026            coordinator: "supervisor".to_string(),
4027            members: vec![TeamMemberSpec::new("supervisor"), TeamMemberSpec::new("worker")],
4028            relationships: vec![TeamRelationship::new(
4029                "supervisor",
4030                "worker",
4031                RelationshipKind::Delegate,
4032            )],
4033            policy: TeamPolicy::default(),
4034        };
4035        assert!(matches!(
4036            spec.compile([
4037                Arc::new(LegacyRuntimeToolBlindAgent) as Arc<dyn Agent>,
4038                Arc::new(StubAgent("worker".into())),
4039            ]),
4040            Err(TeamError::UnsupportedAgentCapability { capability: "runtimeTools", .. })
4041        ));
4042    }
4043
4044    #[test]
4045    fn validates_replay_and_reports_topology_coverage() {
4046        let team = valid_spec()
4047            .compile([
4048                Arc::new(StubAgent("supervisor".into())) as Arc<dyn Agent>,
4049                Arc::new(StubAgent("billing".into())),
4050                Arc::new(StubAgent("technical".into())),
4051            ])
4052            .unwrap();
4053        team.runtime
4054            .start_edge(
4055                "evaluation",
4056                TeamEdgeStart {
4057                    execution_id: Some("edge-1".to_string()),
4058                    parent_id: None,
4059                    from: "supervisor",
4060                    to: "billing",
4061                    kind: RelationshipKind::Handoff,
4062                    attempt: 1,
4063                },
4064            )
4065            .unwrap();
4066        team.runtime.finish_edge("evaluation", "edge-1", None);
4067        let analysis = team.analyze_execution("evaluation").unwrap().unwrap();
4068        assert_eq!(analysis.declared_relationships, 2);
4069        assert_eq!(analysis.covered_relationships, 1);
4070        assert_eq!(analysis.coverage_basis_points, 5_000);
4071        assert_eq!(analysis.uncovered, ["supervisor -Handoff-> technical"]);
4072    }
4073
4074    #[cfg(feature = "team-tools")]
4075    struct CheckpointAgent;
4076
4077    #[cfg(feature = "team-tools")]
4078    #[async_trait]
4079    impl Agent for CheckpointAgent {
4080        fn name(&self) -> &str {
4081            "worker"
4082        }
4083
4084        fn description(&self) -> &str {
4085            "checkpoint-aware worker"
4086        }
4087
4088        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
4089            &[]
4090        }
4091
4092        fn capabilities(&self) -> adk_core::AgentCapabilities {
4093            adk_core::AgentCapabilities {
4094                runtime_tools: false,
4095                handoff: true,
4096                relationship_confirmation: false,
4097                checkpoint_resume: true,
4098                shared_state: true,
4099                invocation_metadata: true,
4100            }
4101        }
4102
4103        async fn run(&self, _ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
4104            Ok(Box::pin(futures::stream::empty()))
4105        }
4106    }
4107
4108    #[cfg(feature = "team-tools")]
4109    #[test]
4110    fn exposes_checkpoint_resume_plan_without_replaying_delegate() {
4111        let spec = TeamSpec {
4112            name: "durable_team".to_string(),
4113            description: String::new(),
4114            coordinator: "supervisor".to_string(),
4115            members: vec![TeamMemberSpec::new("supervisor"), TeamMemberSpec::new("worker")],
4116            relationships: vec![
4117                TeamRelationship::new("supervisor", "worker", RelationshipKind::Delegate)
4118                    .with_policy(RelationshipPolicy {
4119                        resume: TeamResumePolicy::RequireCheckpoint {
4120                            token_state_key: "temp:worker_checkpoint".to_string(),
4121                        },
4122                        ..RelationshipPolicy::default()
4123                    }),
4124            ],
4125            policy: TeamPolicy::default(),
4126        };
4127        let team = spec
4128            .compile([
4129                Arc::new(StubAgent("supervisor".into())) as Arc<dyn Agent>,
4130                Arc::new(CheckpointAgent),
4131            ])
4132            .unwrap();
4133        team.runtime
4134            .start_edge(
4135                "durable-run",
4136                TeamEdgeStart {
4137                    execution_id: Some("delegate-edge".to_string()),
4138                    parent_id: None,
4139                    from: "supervisor",
4140                    to: "worker",
4141                    kind: RelationshipKind::Delegate,
4142                    attempt: 1,
4143                },
4144            )
4145            .unwrap();
4146        assert_eq!(
4147            team.resume_plan("durable-run"),
4148            Some(TeamResumePlan::DelegateCheckpoint {
4149                edge_id: "delegate-edge".to_string(),
4150                target: "worker".to_string(),
4151                token_state_key: "temp:worker_checkpoint".to_string(),
4152            })
4153        );
4154    }
4155}