Skip to main content

adk_agent/team/
runtime.rs

1use std::collections::{HashMap, VecDeque};
2use std::sync::{Arc, Mutex, RwLock};
3use std::time::{Duration, SystemTime, UNIX_EPOCH};
4
5use adk_core::{BudgetTracker, BudgetUsage, Event, Part, Result, RunBudget};
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8
9use super::{
10    RelationshipKind, TeamBudget, TeamError, TeamLifecycleContext, TeamLifecycleDecision,
11    TeamLifecycleHook, TeamLifecycleOutcome, TeamRuntimeError, TeamTerminationPolicy,
12    lifecycle::TeamLifecycleManager,
13};
14
15/// Session state key containing the latest serializable team execution receipt.
16pub const TEAM_EXECUTION_STATE_KEY: &str = "__adk_team_execution_v1";
17/// Event metadata key containing the stable root team invocation identifier.
18pub const TEAM_ROOT_INVOCATION_KEY: &str = "adk.team.root_invocation_id";
19/// Event metadata key containing the causal relationship execution identifier.
20pub const TEAM_EDGE_ID_KEY: &str = "adk.team.edge_id";
21
22/// Aggregate resource usage recorded for a team invocation.
23#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
24#[serde(rename_all = "camelCase")]
25pub struct TeamExecutionUsage {
26    /// Non-partial events emitted by all members and nested delegates.
27    pub events: u64,
28    /// Model calls made by members and nested delegates.
29    pub model_requests: u64,
30    /// Tool calls dispatched by members and nested delegates.
31    pub tool_calls: u64,
32    /// Total reported input and output tokens.
33    pub tokens: u64,
34    /// Cost in millionths of a US dollar, from the providers' priced usage.
35    pub cost_microusd: u64,
36    /// Delegation relationship executions.
37    pub delegations: u64,
38    /// Handoff relationship executions.
39    pub handoffs: u64,
40}
41
42/// Lifecycle state of a team or relationship execution.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
44#[serde(rename_all = "camelCase")]
45pub enum TeamExecutionStatus {
46    /// Execution is active.
47    Running,
48    /// Execution reached a normal terminal response.
49    Completed,
50    /// A configured clean termination condition matched.
51    Terminated,
52    /// A member or relationship failed.
53    Failed,
54    /// A hard team budget was exceeded.
55    BudgetExceeded,
56}
57
58/// One causal relationship execution in a team invocation.
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
60#[serde(rename_all = "camelCase")]
61pub struct TeamEdgeExecution {
62    /// Unique execution identifier.
63    pub id: String,
64    /// Parent relationship execution for nested delegation.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub parent_id: Option<String>,
67    /// Relationship source member.
68    pub from: String,
69    /// Relationship target member.
70    pub to: String,
71    /// Relationship control-flow semantics.
72    pub kind: RelationshipKind,
73    /// One-based attempt number.
74    pub attempt: u32,
75    /// Unix timestamp in milliseconds.
76    pub started_at_ms: u64,
77    /// Unix timestamp in milliseconds when terminal.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub finished_at_ms: Option<u64>,
80    /// Terminal or active state.
81    pub status: TeamExecutionStatus,
82    /// Failure message when present.
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub error: Option<String>,
85}
86
87/// Serializable execution receipt for one root team invocation.
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
89#[serde(rename_all = "camelCase")]
90pub struct TeamExecutionSnapshot {
91    /// Team root name.
92    pub team: String,
93    /// Stable root invocation identifier.
94    pub invocation_id: String,
95    /// Frozen member-to-binding roster used for this execution.
96    pub roster: Vec<ResolvedTeamMember>,
97    /// Unix timestamp in milliseconds.
98    pub started_at_ms: u64,
99    /// Most recent update timestamp in milliseconds.
100    pub updated_at_ms: u64,
101    /// Current execution state.
102    pub status: TeamExecutionStatus,
103    /// Aggregate resource usage.
104    pub usage: TeamExecutionUsage,
105    /// Causal relationship executions in start order.
106    pub edges: Vec<TeamEdgeExecution>,
107    /// Reason for termination or failure.
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub reason: Option<String>,
110}
111
112/// Immutable member binding captured when a team is compiled or discovered.
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
114#[serde(rename_all = "camelCase")]
115pub struct ResolvedTeamMember {
116    /// Portable member name in [`super::TeamSpec`].
117    pub member: String,
118    /// Concrete registry or agent binding identifier.
119    pub binding: String,
120    /// Capabilities frozen at resolution time.
121    #[serde(default, skip_serializing_if = "Vec::is_empty")]
122    pub capabilities: Vec<String>,
123    /// Frozen provider or semantic version.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub version: Option<String>,
126    /// Frozen immutable content/configuration digest.
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub digest: Option<String>,
129    /// Frozen trust labels used during resolution.
130    #[serde(default, skip_serializing_if = "Vec::is_empty")]
131    pub trust_labels: Vec<String>,
132}
133
134#[derive(Debug)]
135pub(crate) enum EventDisposition {
136    Continue,
137    Terminate,
138}
139
140pub(crate) struct TeamEdgeStart<'a> {
141    pub(crate) execution_id: Option<String>,
142    pub(crate) parent_id: Option<String>,
143    pub(crate) from: &'a str,
144    pub(crate) to: &'a str,
145    pub(crate) kind: RelationshipKind,
146    pub(crate) attempt: u32,
147}
148
149/// Finished invocations whose receipts stay readable through
150/// `execution_snapshot`; older finished receipts are evicted. Every receipt is
151/// also persisted to session state under [`TEAM_EXECUTION_STATE_KEY`].
152pub(crate) const RETAINED_FINISHED_INVOCATIONS: usize = 64;
153
154/// Runtime state of one root team invocation.
155struct TeamInvocation {
156    snapshot: Mutex<TeamExecutionSnapshot>,
157    /// Shared counters for the team budget, chained to the run budget.
158    tracker: Mutex<Option<Arc<BudgetTracker>>>,
159    /// Team streams of this invocation currently alive.
160    active_streams: Mutex<usize>,
161}
162
163pub(crate) struct TeamRuntimeRegistry {
164    team: String,
165    roster: Vec<ResolvedTeamMember>,
166    budget: TeamBudget,
167    termination: TeamTerminationPolicy,
168    lifecycle: TeamLifecycleManager,
169    invocations: RwLock<HashMap<String, Arc<TeamInvocation>>>,
170    finished: Mutex<VecDeque<String>>,
171}
172
173impl TeamRuntimeRegistry {
174    pub(crate) fn team_name(&self) -> &str {
175        &self.team
176    }
177
178    pub(crate) fn new(
179        team: String,
180        roster: Vec<ResolvedTeamMember>,
181        budget: TeamBudget,
182        termination: TeamTerminationPolicy,
183        hooks: Vec<Arc<dyn TeamLifecycleHook>>,
184    ) -> Self {
185        Self {
186            team,
187            roster,
188            budget,
189            termination,
190            lifecycle: TeamLifecycleManager::new(hooks),
191            invocations: RwLock::new(HashMap::new()),
192            finished: Mutex::new(VecDeque::new()),
193        }
194    }
195
196    pub(crate) async fn before_lifecycle(
197        &self,
198        context: &TeamLifecycleContext,
199    ) -> Result<TeamLifecycleDecision> {
200        self.lifecycle.before(context).await
201    }
202
203    pub(crate) async fn after_lifecycle(
204        &self,
205        context: &TeamLifecycleContext,
206        outcome: &TeamLifecycleOutcome,
207    ) -> Result<()> {
208        self.lifecycle.after(context, outcome).await
209    }
210
211    pub(crate) fn snapshot(&self, invocation_id: &str) -> Option<TeamExecutionSnapshot> {
212        let ledger = self
213            .invocations
214            .read()
215            .unwrap_or_else(|error| error.into_inner())
216            .get(invocation_id)
217            .cloned()?;
218        Some(ledger.synced_snapshot())
219    }
220
221    pub(crate) fn snapshots(&self) -> Vec<TeamExecutionSnapshot> {
222        self.invocations
223            .read()
224            .unwrap_or_else(|error| error.into_inner())
225            .values()
226            .map(|ledger| ledger.synced_snapshot())
227            .collect()
228    }
229
230    /// Returns the invocation's team budget tracker, creating it on first use.
231    ///
232    /// `run_tracker` is the run budget the team runs under; the team tracker
233    /// counts against it, so members stop at whichever limit is reached first.
234    pub(crate) fn budget_tracker(
235        &self,
236        invocation_id: &str,
237        run_tracker: Option<Arc<BudgetTracker>>,
238    ) -> Arc<BudgetTracker> {
239        let ledger = self.ledger(invocation_id);
240        self.tracker_for(&ledger, run_tracker)
241    }
242
243    fn tracker_for(
244        &self,
245        ledger: &TeamInvocation,
246        run_tracker: Option<Arc<BudgetTracker>>,
247    ) -> Arc<BudgetTracker> {
248        let mut slot = ledger.tracker.lock().unwrap_or_else(|error| error.into_inner());
249        if let Some(tracker) = slot.as_ref() {
250            return tracker.clone();
251        }
252        let snapshot = ledger.snapshot.lock().unwrap_or_else(|error| error.into_inner());
253        // A restored receipt continues from its recorded usage and start time.
254        let usage = BudgetUsage {
255            model_calls: snapshot.usage.model_requests,
256            total_tokens: snapshot.usage.tokens,
257            cost_micro_usd: snapshot.usage.cost_microusd,
258            tool_calls: snapshot.usage.tool_calls,
259            elapsed: Duration::from_millis(now_ms().saturating_sub(snapshot.started_at_ms)),
260        };
261        let tracker = Arc::new(BudgetTracker::resume(self.budget.run_budget(), usage, run_tracker));
262        *slot = Some(tracker.clone());
263        tracker
264    }
265
266    /// Marks one team stream of the invocation as alive.
267    pub(crate) fn enter(self: &Arc<Self>, invocation_id: &str) -> ActiveTeamStream {
268        let ledger = self.ledger(invocation_id);
269        *ledger.active_streams.lock().unwrap_or_else(|error| error.into_inner()) += 1;
270        ActiveTeamStream { runtime: self.clone(), invocation_id: invocation_id.to_string() }
271    }
272
273    /// Ends one team stream; the invocation finishes when none remain and no
274    /// handoff is in flight.
275    fn leave(&self, invocation_id: &str) {
276        let Some(ledger) = self
277            .invocations
278            .read()
279            .unwrap_or_else(|error| error.into_inner())
280            .get(invocation_id)
281            .cloned()
282        else {
283            return;
284        };
285        let mut active = ledger.active_streams.lock().unwrap_or_else(|error| error.into_inner());
286        *active = active.saturating_sub(1);
287        if *active > 0 || ledger.has_running_edges() {
288            return;
289        }
290        drop(active);
291        // Counters move into the receipt; a later resume builds a fresh tracker from it.
292        ledger.synced_snapshot();
293        ledger.tracker.lock().unwrap_or_else(|error| error.into_inner()).take();
294        let mut finished = self.finished.lock().unwrap_or_else(|error| error.into_inner());
295        if !finished.iter().any(|id| id == invocation_id) {
296            finished.push_back(invocation_id.to_string());
297        }
298        while finished.len() > RETAINED_FINISHED_INVOCATIONS {
299            let Some(evicted) = finished.pop_front() else {
300                break;
301            };
302            let mut invocations =
303                self.invocations.write().unwrap_or_else(|error| error.into_inner());
304            if invocations.get(&evicted).is_some_and(|ledger| ledger.is_idle()) {
305                invocations.remove(&evicted);
306            }
307        }
308    }
309
310    pub(crate) fn restore(
311        &self,
312        snapshot: TeamExecutionSnapshot,
313    ) -> std::result::Result<(), TeamError> {
314        if snapshot.team != self.team {
315            return Err(TeamError::IncompatibleExecutionSnapshot(format!(
316                "snapshot belongs to team '{}', expected '{}'",
317                snapshot.team, self.team
318            )));
319        }
320        if snapshot.roster != self.roster {
321            return Err(TeamError::IncompatibleExecutionSnapshot(
322                "the frozen member roster does not match".to_string(),
323            ));
324        }
325        if snapshot.invocation_id.trim().is_empty() {
326            return Err(TeamError::IncompatibleExecutionSnapshot(
327                "invocationId must not be empty".to_string(),
328            ));
329        }
330        self.invocations
331            .write()
332            .unwrap_or_else(|error| error.into_inner())
333            .insert(snapshot.invocation_id.clone(), Arc::new(TeamInvocation::new(snapshot)));
334        Ok(())
335    }
336
337    pub(crate) fn resume_handoff_target(&self, invocation_id: &str) -> Result<Option<String>> {
338        let Some(snapshot) = self.snapshot(invocation_id) else {
339            return Ok(None);
340        };
341        let Some(active) =
342            snapshot.edges.iter().rev().find(|edge| edge.status == TeamExecutionStatus::Running)
343        else {
344            return Ok(None);
345        };
346        match active.kind {
347            RelationshipKind::Handoff => Ok(Some(active.to.clone())),
348            RelationshipKind::Delegate => Err(TeamRuntimeError::UnsafeResume(format!(
349                "cannot replay unresolved delegation '{}' from '{}' to '{}'; inspect CompiledTeam::resume_plan and use a checkpoint-aware durable host",
350                active.id, active.from, active.to
351            ))
352            .into()),
353        }
354    }
355
356    fn ledger(&self, invocation_id: &str) -> Arc<TeamInvocation> {
357        if let Some(ledger) = self
358            .invocations
359            .read()
360            .unwrap_or_else(|error| error.into_inner())
361            .get(invocation_id)
362            .cloned()
363        {
364            return ledger;
365        }
366        let now = now_ms();
367        let ledger = Arc::new(TeamInvocation::new(TeamExecutionSnapshot {
368            team: self.team.clone(),
369            invocation_id: invocation_id.to_string(),
370            roster: self.roster.clone(),
371            started_at_ms: now,
372            updated_at_ms: now,
373            status: TeamExecutionStatus::Running,
374            usage: TeamExecutionUsage::default(),
375            edges: Vec::new(),
376            reason: None,
377        }));
378        self.invocations
379            .write()
380            .unwrap_or_else(|error| error.into_inner())
381            .entry(invocation_id.to_string())
382            .or_insert_with(|| ledger.clone())
383            .clone()
384    }
385
386    pub(crate) fn check_budget(&self, invocation_id: &str) -> Result<()> {
387        let ledger = self.ledger(invocation_id);
388        let tracker = self.tracker_for(&ledger, None);
389        let mut snapshot = ledger.snapshot.lock().unwrap_or_else(|error| error.into_inner());
390        sync_usage(&mut snapshot, &tracker);
391        if let Err(exceeded) = tracker.check() {
392            snapshot.status = TeamExecutionStatus::BudgetExceeded;
393            snapshot.reason = Some(exceeded.to_string());
394            snapshot.updated_at_ms = now_ms();
395            return Err(exceeded.into());
396        }
397        if let Some(reason) = self.budget_violation(&snapshot) {
398            snapshot.status = TeamExecutionStatus::BudgetExceeded;
399            snapshot.reason = Some(reason.clone());
400            snapshot.updated_at_ms = now_ms();
401            return Err(TeamRuntimeError::BudgetExceeded(reason).into());
402        }
403        Ok(())
404    }
405
406    pub(crate) fn start_edge(
407        &self,
408        invocation_id: &str,
409        start: TeamEdgeStart<'_>,
410    ) -> Result<String> {
411        self.check_budget(invocation_id)?;
412        let ledger = self.ledger(invocation_id);
413        let mut snapshot = ledger.snapshot.lock().unwrap_or_else(|error| error.into_inner());
414        snapshot.status = TeamExecutionStatus::Running;
415        snapshot.reason = None;
416        match start.kind {
417            RelationshipKind::Delegate => snapshot.usage.delegations += 1,
418            RelationshipKind::Handoff => snapshot.usage.handoffs += 1,
419        }
420        let id = start.execution_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
421        snapshot.edges.push(TeamEdgeExecution {
422            id: id.clone(),
423            parent_id: start.parent_id,
424            from: start.from.to_string(),
425            to: start.to.to_string(),
426            kind: start.kind,
427            attempt: start.attempt,
428            started_at_ms: now_ms(),
429            finished_at_ms: None,
430            status: TeamExecutionStatus::Running,
431            error: None,
432        });
433        snapshot.updated_at_ms = now_ms();
434        if let Some(reason) = self.budget_violation(&snapshot) {
435            snapshot.status = TeamExecutionStatus::BudgetExceeded;
436            snapshot.reason = Some(reason.clone());
437            return Err(TeamRuntimeError::BudgetExceeded(reason).into());
438        }
439        Ok(id)
440    }
441
442    pub(crate) fn finish_edge(&self, invocation_id: &str, id: &str, error: Option<String>) {
443        let ledger = self.ledger(invocation_id);
444        let mut snapshot = ledger.snapshot.lock().unwrap_or_else(|failure| failure.into_inner());
445        if let Some(edge) = snapshot.edges.iter_mut().find(|edge| edge.id == id) {
446            edge.finished_at_ms = Some(now_ms());
447            edge.status = if error.is_some() {
448                TeamExecutionStatus::Failed
449            } else {
450                TeamExecutionStatus::Completed
451            };
452            edge.error = error;
453        }
454        snapshot.updated_at_ms = now_ms();
455    }
456
457    pub(crate) fn record_event(
458        &self,
459        invocation_id: &str,
460        edge_id: Option<&str>,
461        event: &mut Event,
462    ) -> Result<EventDisposition> {
463        let ledger = self.ledger(invocation_id);
464        let tracker = self.tracker_for(&ledger, None);
465        let mut snapshot = ledger.snapshot.lock().unwrap_or_else(|error| error.into_inner());
466        let already_recorded = event
467            .provider_metadata
468            .get(TEAM_ROOT_INVOCATION_KEY)
469            .is_some_and(|root| root == invocation_id);
470        // Partial streaming chunks repeat their usage and are never counted.
471        if !already_recorded && !event.llm_response.partial {
472            snapshot.usage.events += 1;
473        }
474        // Model calls metered by their call site are already in the tracker; this
475        // counts usage from members that call models directly and audits the limits.
476        let tracker_violation =
477            if already_recorded { tracker.exceeded() } else { tracker.record_event(event).err() };
478        sync_usage(&mut snapshot, &tracker);
479        snapshot.updated_at_ms = now_ms();
480        event
481            .provider_metadata
482            .insert(TEAM_ROOT_INVOCATION_KEY.to_string(), invocation_id.to_string());
483        if let Some(edge_id) = edge_id {
484            event.provider_metadata.insert(TEAM_EDGE_ID_KEY.to_string(), edge_id.to_string());
485        }
486
487        // Tracker violations keep their `budget.*` code and limit details.
488        if let Some(exceeded) = tracker_violation {
489            snapshot.status = TeamExecutionStatus::BudgetExceeded;
490            snapshot.reason = Some(exceeded.to_string());
491            persist_snapshot_if_absent(event, &snapshot);
492            return Err(exceeded.into());
493        }
494        if let Some(reason) = self.budget_violation(&snapshot) {
495            snapshot.status = TeamExecutionStatus::BudgetExceeded;
496            snapshot.reason = Some(reason.clone());
497            persist_snapshot_if_absent(event, &snapshot);
498            return Err(TeamRuntimeError::BudgetExceeded(reason).into());
499        }
500
501        let termination = self.termination_reason(event);
502        if let Some(reason) = &termination {
503            snapshot.status = TeamExecutionStatus::Terminated;
504            snapshot.reason = Some(reason.clone());
505        } else if event.is_final_response()
506            && edge_id.is_none_or(|id| {
507                snapshot
508                    .edges
509                    .iter()
510                    .find(|edge| edge.id == id)
511                    .is_none_or(|edge| edge.kind != RelationshipKind::Delegate)
512            })
513        {
514            snapshot.status = TeamExecutionStatus::Completed;
515        }
516        persist_snapshot_if_absent(event, &snapshot);
517        Ok(termination.map_or(EventDisposition::Continue, |_| EventDisposition::Terminate))
518    }
519
520    pub(crate) fn fail(&self, invocation_id: &str, error: &adk_core::AdkError) {
521        let ledger = self.ledger(invocation_id);
522        let mut snapshot = ledger.snapshot.lock().unwrap_or_else(|error| error.into_inner());
523        snapshot.status = if error.category == adk_core::ErrorCategory::ResourceExhausted {
524            TeamExecutionStatus::BudgetExceeded
525        } else {
526            TeamExecutionStatus::Failed
527        };
528        snapshot.reason = Some(error.to_string());
529        snapshot.updated_at_ms = now_ms();
530    }
531
532    fn termination_reason(&self, event: &Event) -> Option<String> {
533        if self.termination.stop_on_escalation && event.actions.escalate {
534            return Some("team terminated on escalation".to_string());
535        }
536        if event.is_final_response()
537            && self.termination.final_authors.iter().any(|author| author == &event.author)
538        {
539            return Some(format!("team terminated after final response from '{}'", event.author));
540        }
541        for marker in &self.termination.text_markers {
542            let matched = event
543                .content()
544                .into_iter()
545                .flat_map(|content| &content.parts)
546                .any(|part| matches!(part, Part::Text { text } if text.contains(marker)));
547            if matched {
548                return Some(format!("team termination marker matched: {marker}"));
549            }
550        }
551        None
552    }
553
554    /// Limits the budget tracker does not own: events, delegations and handoffs.
555    fn budget_violation(&self, snapshot: &TeamExecutionSnapshot) -> Option<String> {
556        let usage = &snapshot.usage;
557        let limits = [
558            ("events", usage.events, self.budget.max_events),
559            ("delegations", usage.delegations, self.budget.max_delegations),
560            ("handoffs", usage.handoffs, self.budget.max_handoffs),
561        ];
562        let (name, used, limit) =
563            limits.into_iter().find(|(_, used, limit)| limit.is_some_and(|max| *used > max))?;
564        Some(format!(
565            "team budget exceeded for {name}: used {used}, maximum {}",
566            limit.unwrap_or_default()
567        ))
568    }
569}
570
571impl TeamInvocation {
572    fn new(snapshot: TeamExecutionSnapshot) -> Self {
573        Self {
574            snapshot: Mutex::new(snapshot),
575            tracker: Mutex::new(None),
576            active_streams: Mutex::new(0),
577        }
578    }
579
580    /// The receipt with its usage refreshed from the live tracker.
581    fn synced_snapshot(&self) -> TeamExecutionSnapshot {
582        let tracker = self.tracker.lock().unwrap_or_else(|error| error.into_inner()).clone();
583        let mut snapshot = self.snapshot.lock().unwrap_or_else(|error| error.into_inner());
584        if let Some(tracker) = tracker {
585            sync_usage(&mut snapshot, &tracker);
586        }
587        snapshot.clone()
588    }
589
590    fn has_running_edges(&self) -> bool {
591        self.snapshot
592            .lock()
593            .unwrap_or_else(|error| error.into_inner())
594            .edges
595            .iter()
596            .any(|edge| edge.status == TeamExecutionStatus::Running)
597    }
598
599    fn is_idle(&self) -> bool {
600        *self.active_streams.lock().unwrap_or_else(|error| error.into_inner()) == 0
601            && !self.has_running_edges()
602    }
603}
604
605/// Keeps a team invocation active while a team stream is alive.
606pub(crate) struct ActiveTeamStream {
607    runtime: Arc<TeamRuntimeRegistry>,
608    invocation_id: String,
609}
610
611impl Drop for ActiveTeamStream {
612    fn drop(&mut self) {
613        self.runtime.leave(&self.invocation_id);
614    }
615}
616
617impl TeamBudget {
618    /// The limits the budget tracker enforces before each model and tool call.
619    pub(crate) fn run_budget(&self) -> RunBudget {
620        let mut budget = RunBudget::new();
621        if let Some(max) = self.max_model_requests {
622            budget = budget.max_model_calls(max);
623        }
624        if let Some(max) = self.max_tokens {
625            budget = budget.max_total_tokens(max);
626        }
627        if let Some(max) = self.max_cost_microusd {
628            budget = budget.max_cost_micro_usd(max);
629        }
630        if let Some(max) = self.max_tool_calls {
631            budget = budget.max_tool_calls(max);
632        }
633        if let Some(max) = self.max_wall_time_ms {
634            budget = budget.max_wall_time(Duration::from_millis(max));
635        }
636        if self.allow_unpriced_models {
637            budget = budget.allow_unpriced_models();
638        }
639        budget
640    }
641}
642
643fn sync_usage(snapshot: &mut TeamExecutionSnapshot, tracker: &BudgetTracker) {
644    let usage = tracker.usage();
645    snapshot.usage.model_requests = usage.model_calls;
646    snapshot.usage.tool_calls = usage.tool_calls;
647    snapshot.usage.tokens = usage.total_tokens;
648    snapshot.usage.cost_microusd = usage.cost_micro_usd;
649}
650
651fn persist_snapshot(event: &mut Event, snapshot: &TeamExecutionSnapshot) {
652    if let Ok(value) = serde_json::to_value(snapshot) {
653        event.actions.state_delta.insert(TEAM_EXECUTION_STATE_KEY.to_string(), value);
654    }
655}
656
657fn persist_snapshot_if_absent(event: &mut Event, snapshot: &TeamExecutionSnapshot) {
658    if !event.actions.state_delta.contains_key(TEAM_EXECUTION_STATE_KEY) {
659        persist_snapshot(event, snapshot);
660    }
661}
662
663fn now_ms() -> u64 {
664    SystemTime::now()
665        .duration_since(UNIX_EPOCH)
666        .unwrap_or_default()
667        .as_millis()
668        .try_into()
669        .unwrap_or(u64::MAX)
670}
671
672#[cfg(test)]
673mod tests {
674    use super::*;
675    use adk_core::Content;
676
677    fn registry(budget: TeamBudget, termination: TeamTerminationPolicy) -> TeamRuntimeRegistry {
678        TeamRuntimeRegistry::new(
679            "portable_team".to_string(),
680            vec![ResolvedTeamMember {
681                member: "root".to_string(),
682                binding: "root-v1".to_string(),
683                capabilities: vec!["route".to_string()],
684                version: None,
685                digest: None,
686                trust_labels: Vec::new(),
687            }],
688            budget,
689            termination,
690            Vec::new(),
691        )
692    }
693
694    #[test]
695    fn enforces_aggregate_event_budget_and_persists_receipt() {
696        let runtime = registry(
697            TeamBudget { max_events: Some(1), ..TeamBudget::default() },
698            TeamTerminationPolicy::default(),
699        );
700        let mut first = Event::new("invocation");
701        assert!(matches!(
702            runtime.record_event("invocation", None, &mut first),
703            Ok(EventDisposition::Continue)
704        ));
705        assert!(first.actions.state_delta.contains_key(TEAM_EXECUTION_STATE_KEY));
706
707        let mut second = Event::new("invocation");
708        let error = runtime.record_event("invocation", None, &mut second).unwrap_err();
709        assert!(error.to_string().contains("events"));
710        assert_eq!(error.code, "agent.team.budget_exceeded");
711        assert_eq!(
712            runtime.snapshot("invocation").unwrap().status,
713            TeamExecutionStatus::BudgetExceeded
714        );
715    }
716
717    #[test]
718    fn records_causal_edges_and_terminates_on_marker() {
719        let runtime = registry(
720            TeamBudget::default(),
721            TeamTerminationPolicy {
722                text_markers: vec!["APPROVED".to_string()],
723                ..TeamTerminationPolicy::default()
724            },
725        );
726        let parent = runtime
727            .start_edge(
728                "invocation",
729                TeamEdgeStart {
730                    execution_id: Some("edge-1".to_string()),
731                    parent_id: None,
732                    from: "root",
733                    to: "a",
734                    kind: RelationshipKind::Delegate,
735                    attempt: 1,
736                },
737            )
738            .unwrap();
739        let child = runtime
740            .start_edge(
741                "invocation",
742                TeamEdgeStart {
743                    execution_id: Some("edge-2".to_string()),
744                    parent_id: Some(parent.clone()),
745                    from: "a",
746                    to: "b",
747                    kind: RelationshipKind::Handoff,
748                    attempt: 1,
749                },
750            )
751            .unwrap();
752        runtime.finish_edge("invocation", &child, None);
753        runtime.finish_edge("invocation", &parent, None);
754        let mut event = Event::new("invocation");
755        event.author = "b".to_string();
756        event.llm_response.content = Some(Content::new("model").with_text("APPROVED"));
757        assert!(matches!(
758            runtime.record_event("invocation", Some(&child), &mut event),
759            Ok(EventDisposition::Terminate)
760        ));
761        let snapshot = runtime.snapshot("invocation").unwrap();
762        assert_eq!(snapshot.status, TeamExecutionStatus::Terminated);
763        assert_eq!(snapshot.edges[1].parent_id.as_deref(), Some("edge-1"));
764        assert_eq!(event.provider_metadata.get(TEAM_EDGE_ID_KEY), Some(&child));
765    }
766
767    #[test]
768    fn restores_only_matching_frozen_rosters() {
769        let source = registry(TeamBudget::default(), TeamTerminationPolicy::default());
770        source.check_budget("resume-me").unwrap();
771        let snapshot = source.snapshot("resume-me").unwrap();
772
773        let restored = registry(TeamBudget::default(), TeamTerminationPolicy::default());
774        restored.restore(snapshot.clone()).unwrap();
775        assert_eq!(restored.snapshot("resume-me"), Some(snapshot.clone()));
776
777        let other = TeamRuntimeRegistry::new(
778            "portable_team".to_string(),
779            vec![ResolvedTeamMember {
780                member: "root".to_string(),
781                binding: "root-v2".to_string(),
782                capabilities: vec!["route".to_string()],
783                version: None,
784                digest: None,
785                trust_labels: Vec::new(),
786            }],
787            TeamBudget::default(),
788            TeamTerminationPolicy::default(),
789            Vec::new(),
790        );
791        assert!(matches!(
792            other.restore(snapshot),
793            Err(TeamError::IncompatibleExecutionSnapshot(_))
794        ));
795    }
796
797    #[test]
798    fn resumes_handoffs_but_refuses_unsafe_delegate_replay() {
799        let handoff = registry(TeamBudget::default(), TeamTerminationPolicy::default());
800        handoff
801            .start_edge(
802                "handoff-run",
803                TeamEdgeStart {
804                    execution_id: Some("handoff-edge".to_string()),
805                    parent_id: None,
806                    from: "root",
807                    to: "specialist",
808                    kind: RelationshipKind::Handoff,
809                    attempt: 1,
810                },
811            )
812            .unwrap();
813        assert_eq!(
814            handoff.resume_handoff_target("handoff-run").unwrap().as_deref(),
815            Some("specialist")
816        );
817
818        let delegate = registry(TeamBudget::default(), TeamTerminationPolicy::default());
819        delegate
820            .start_edge(
821                "delegate-run",
822                TeamEdgeStart {
823                    execution_id: Some("delegate-edge".to_string()),
824                    parent_id: None,
825                    from: "root",
826                    to: "worker",
827                    kind: RelationshipKind::Delegate,
828                    attempt: 1,
829                },
830            )
831            .unwrap();
832        let error = delegate.resume_handoff_target("delegate-run").unwrap_err();
833        assert!(error.to_string().contains("cannot replay unresolved delegation"));
834        assert_eq!(error.code, "agent.team.resume_unsafe");
835    }
836}