1use std::collections::HashMap;
10use std::sync::{Arc, Mutex, OnceLock};
11
12use adk_core::audit_log::{AuditActor, AuditTrail};
13use adk_core::{
14 AdkError, BudgetTracker, BudgetUsage, ErrorCategory, ErrorComponent, EventStream,
15 InvocationContext, LlmRequest, Part, ReadonlyContext, ReservationId, Result, RunBudget,
16 SpendKey, SpendLedger, SpendPeriod, SubjectRef,
17};
18use adk_eval::{ToolCallRecord, TraceAnalyzer, TracePattern};
19use async_trait::async_trait;
20use futures::StreamExt as _;
21use serde::{Deserialize, Serialize};
22use serde_json::{Value, json};
23use tracing::{Instrument as _, Span};
24
25use crate::audit::HarnessAudit;
26use crate::builder::LoopGuard;
27use crate::mode::{HarnessMode, ModeSource, ModeStore, write_mode_change};
28use crate::policy::{Isolation, ToolKind};
29use crate::shell::IsolationStatus;
30use crate::toolset::RequestObserver;
31
32pub const ATTR_MODE: &str = "harness.mode";
40pub const ATTR_TOOL_KIND: &str = "harness.tool_kind";
48pub const ATTR_ISOLATION: &str = "harness.isolation";
56pub const ATTR_RULE_ID: &str = "harness.rule_id";
64pub const ATTR_MEMBER: &str = "harness.member";
72pub const ATTR_GOAL_ITERATION: &str = "harness.goal.iteration";
80
81pub const LOOP_DETECTED_CODE: &str = "harness.loop_detected";
89
90pub fn tool_kind_label(kind: &ToolKind) -> String {
103 let isolation = |isolation: &Isolation| match isolation {
104 Isolation::OsSandbox => "os_sandbox",
105 Isolation::Container => "container",
106 Isolation::Host => "host",
107 };
108 match kind {
109 ToolKind::Read => "read".to_string(),
110 ToolKind::Todo => "todo".to_string(),
111 ToolKind::PlanExit => "plan_exit".to_string(),
112 ToolKind::Edit => "edit".to_string(),
113 ToolKind::Shell(iso) => format!("shell:{}", isolation(iso)),
114 ToolKind::ShellEscalation => "shell_escalation".to_string(),
115 ToolKind::Delegate => "delegate".to_string(),
116 ToolKind::MemoryWrite => "memory_write".to_string(),
117 ToolKind::MemoryPropose => "memory_propose".to_string(),
118 ToolKind::Web { allowlisted } => {
119 format!("web:{}", if *allowlisted { "allowlisted" } else { "other" })
120 }
121 ToolKind::Payment => "payment".to_string(),
122 ToolKind::ComputerUse => "computer_use".to_string(),
123 ToolKind::External { effect, trusted_origin } => format!(
124 "external:{}:{}",
125 serde_json::to_value(effect)
126 .ok()
127 .and_then(|v| v.as_str().map(String::from))
128 .unwrap_or_default(),
129 if *trusted_origin { "trusted" } else { "untrusted" }
130 ),
131 }
132}
133
134pub fn isolation_label(status: &IsolationStatus) -> String {
146 match status {
147 IsolationStatus::Host => "host".to_string(),
148 IsolationStatus::OsSandbox { enforcer } => format!("os_sandbox:{enforcer}"),
149 IsolationStatus::Container { image } => format!("container:{image}"),
150 IsolationStatus::Remote { provider, .. } => format!("remote:{provider}"),
151 IsolationStatus::Degraded { requested, .. } => format!("degraded:{requested}"),
152 }
153}
154
155pub fn run_span(
167 agent: &str,
168 invocation_id: &str,
169 mode: HarnessMode,
170 isolation: &IsolationStatus,
171) -> Span {
172 tracing::info_span!(
173 "harness.run",
174 agent.name = agent,
175 invocation.id = invocation_id,
176 harness.mode = %mode,
177 harness.isolation = isolation_label(isolation),
178 otel.kind = "internal"
179 )
180}
181
182pub(crate) fn decision_span(tool: &str, isolation: &IsolationStatus) -> Span {
185 tracing::info_span!(
186 "harness.decide",
187 tool.name = tool,
188 harness.isolation = isolation_label(isolation),
189 harness.tool_kind = tracing::field::Empty,
190 harness.mode = tracing::field::Empty,
191 harness.rule_id = tracing::field::Empty,
192 harness.member = tracing::field::Empty,
193 harness.decision = tracing::field::Empty,
194 )
195}
196
197pub fn member_span(member: &str, invocation_id: &str) -> Span {
206 tracing::info_span!("harness.member", harness.member = member, invocation.id = invocation_id)
207}
208
209pub fn goal_iteration_span(iteration: u32, max_iterations: u32) -> Span {
219 tracing::info_span!(
220 "harness.goal",
221 harness.goal.iteration = iteration,
222 harness.goal.max_iterations = max_iterations
223 )
224}
225
226#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
240#[serde(rename_all = "camelCase")]
241pub struct SpendEntry {
242 pub key: SpendKey,
244 #[serde(default, skip_serializing_if = "Option::is_none")]
246 pub subject: Option<SubjectRef>,
247 pub charges: u64,
249 pub cost_micro_usd: u64,
251}
252
253#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
264#[serde(rename_all = "camelCase")]
265pub struct SpendReport {
266 pub entries: Vec<SpendEntry>,
268 pub charges: u64,
270 pub cost_micro_usd: u64,
272 pub runs: u64,
274 pub model_calls: u64,
276 pub total_tokens: u64,
278 #[serde(default)]
280 pub prompt_tokens: u64,
281 #[serde(default)]
283 pub cached_prompt_tokens: u64,
284 #[serde(default, skip_serializing_if = "Vec::is_empty")]
286 pub turns: Vec<TurnTokens>,
287}
288
289#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
299#[serde(rename_all = "camelCase")]
300pub struct TurnTokens {
301 pub model_calls: u64,
303 pub prompt_tokens: u64,
305 pub cached_prompt_tokens: u64,
307}
308
309impl TurnTokens {
310 pub fn uncached_prompt_tokens(&self) -> u64 {
312 self.prompt_tokens.saturating_sub(self.cached_prompt_tokens)
313 }
314}
315
316impl SpendReport {
317 pub const TURNS_KEPT: usize = 20;
319
320 pub fn cost_usd(&self) -> f64 {
322 self.cost_micro_usd as f64 / 1_000_000.0
323 }
324
325 pub fn render(&self) -> String {
327 let usd = |micro: u64| format!("${}.{:06}", micro / 1_000_000, micro % 1_000_000);
328 let mut out = format!(
329 "{} over {} runs: {} model calls, {} tokens\n",
330 usd(self.cost_micro_usd),
331 self.runs,
332 self.model_calls,
333 self.total_tokens
334 );
335 out.push_str(&format!(
336 "prompt tokens: {} ({} cached, {} uncached)\n",
337 self.prompt_tokens,
338 self.cached_prompt_tokens,
339 self.prompt_tokens.saturating_sub(self.cached_prompt_tokens)
340 ));
341 for (i, turn) in self.turns.iter().enumerate() {
342 out.push_str(&format!(
343 " turn {}: {} model calls, {} prompt tokens ({} cached, {} uncached)\n",
344 i + 1,
345 turn.model_calls,
346 turn.prompt_tokens,
347 turn.cached_prompt_tokens,
348 turn.uncached_prompt_tokens()
349 ));
350 }
351 for entry in &self.entries {
352 out.push_str(&format!(
353 " {} {} {}: {} charges, {}\n",
354 entry.subject.as_ref().map_or("-", |subject| subject.id.as_str()),
355 entry.key.agent.as_deref().unwrap_or("-"),
356 entry.key.vendor.as_deref().unwrap_or("-"),
357 entry.charges,
358 usd(entry.cost_micro_usd)
359 ));
360 }
361 out
362 }
363}
364
365#[derive(Default)]
366struct RunTotals {
367 runs: u64,
368 model_calls: u64,
369 total_tokens: u64,
370 prompt_tokens: u64,
371 cached_prompt_tokens: u64,
372 turns: Vec<TurnTokens>,
373}
374
375type Entries = HashMap<(SpendKey, Option<SubjectRef>), (u64, u64)>;
377type Ledgers = Vec<(usize, Option<SubjectRef>, Arc<SubjectLedger>)>;
379
380#[derive(Default)]
382pub(crate) struct SpendAccounts {
383 entries: Mutex<Entries>,
384 runs: Mutex<HashMap<Option<SubjectRef>, RunTotals>>,
385 ledgers: Mutex<Ledgers>,
386}
387
388impl std::fmt::Debug for SpendAccounts {
389 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
390 f.debug_struct("SpendAccounts").finish_non_exhaustive()
391 }
392}
393
394fn address(ledger: &Arc<dyn SpendLedger>) -> usize {
395 Arc::as_ptr(ledger).cast::<()>() as usize
396}
397
398impl SpendAccounts {
399 fn ledger_for(
402 self: &Arc<Self>,
403 base: Arc<dyn SpendLedger>,
404 subject: Option<SubjectRef>,
405 ) -> Arc<dyn SpendLedger> {
406 let mut ledgers = self.ledgers.lock().unwrap_or_else(|e| e.into_inner());
407 let key = address(&base);
408 if let Some((_, _, ledger)) =
409 ledgers.iter().find(|(base, owner, _)| *base == key && *owner == subject)
410 {
411 return ledger.clone();
412 }
413 if ledgers.len() > 4096 {
414 ledgers.clear();
415 }
416 let ledger = Arc::new(SubjectLedger {
417 inner: base,
418 subject: subject.clone(),
419 accounts: Arc::downgrade(self),
420 holds: Mutex::new(HashMap::new()),
421 });
422 ledgers.push((key, subject, ledger.clone()));
423 ledger
424 }
425
426 fn is_ours(&self, ledger: &Arc<dyn SpendLedger>) -> bool {
427 let key = address(ledger);
428 self.ledgers
429 .lock()
430 .unwrap_or_else(|e| e.into_inner())
431 .iter()
432 .any(|(_, _, ours)| Arc::as_ptr(ours).cast::<()>() as usize == key)
433 }
434
435 fn charge(&self, key: SpendKey, subject: Option<SubjectRef>, amount: u64) {
436 let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
437 let entry = entries.entry((key, subject)).or_insert((0, 0));
438 entry.0 += 1;
439 entry.1 = entry.1.saturating_add(amount);
440 }
441
442 fn finish_run(&self, subject: Option<SubjectRef>, usage: &BudgetUsage, turn: TurnTokens) {
443 let mut runs = self.runs.lock().unwrap_or_else(|e| e.into_inner());
444 let totals = runs.entry(subject).or_default();
445 totals.runs += 1;
446 totals.model_calls += usage.model_calls;
447 totals.total_tokens += usage.total_tokens;
448 totals.prompt_tokens += turn.prompt_tokens;
449 totals.cached_prompt_tokens += turn.cached_prompt_tokens;
450 if totals.turns.len() >= SpendReport::TURNS_KEPT {
451 totals.turns.remove(0);
452 }
453 totals.turns.push(turn);
454 }
455
456 pub(crate) fn report(&self, subject: Option<&str>) -> SpendReport {
458 let matches = |owner: &Option<SubjectRef>| {
459 subject.is_none_or(|id| owner.as_ref().is_some_and(|owner| owner.id == id))
460 };
461 let mut entries: Vec<SpendEntry> = self
462 .entries
463 .lock()
464 .unwrap_or_else(|e| e.into_inner())
465 .iter()
466 .filter(|((_, owner), _)| matches(owner))
467 .map(|((key, owner), (charges, cost))| SpendEntry {
468 key: key.clone(),
469 subject: owner.clone(),
470 charges: *charges,
471 cost_micro_usd: *cost,
472 })
473 .collect();
474 entries.sort_by(|a, b| {
475 let subject = |entry: &SpendEntry| entry.subject.as_ref().map(|s| s.id.clone());
476 subject(a).cmp(&subject(b)).then_with(|| a.key.to_string().cmp(&b.key.to_string()))
477 });
478 let mut report = SpendReport {
479 charges: entries.iter().map(|entry| entry.charges).sum(),
480 cost_micro_usd: entries.iter().map(|entry| entry.cost_micro_usd).sum(),
481 entries,
482 ..SpendReport::default()
483 };
484 for (owner, totals) in self.runs.lock().unwrap_or_else(|e| e.into_inner()).iter() {
485 if matches(owner) {
486 report.runs += totals.runs;
487 report.model_calls += totals.model_calls;
488 report.total_tokens += totals.total_tokens;
489 report.prompt_tokens += totals.prompt_tokens;
490 report.cached_prompt_tokens += totals.cached_prompt_tokens;
491 report.turns.extend(totals.turns.iter().copied());
492 }
493 }
494 let excess = report.turns.len().saturating_sub(SpendReport::TURNS_KEPT);
495 report.turns.drain(..excess);
496 report
497 }
498}
499
500struct SubjectLedger {
503 inner: Arc<dyn SpendLedger>,
504 subject: Option<SubjectRef>,
505 accounts: std::sync::Weak<SpendAccounts>,
506 holds: Mutex<HashMap<ReservationId, SpendKey>>,
507}
508
509impl std::fmt::Debug for SubjectLedger {
510 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
511 f.debug_struct("SubjectLedger")
512 .field("inner", &self.inner)
513 .field("subject", &self.subject)
514 .finish()
515 }
516}
517
518#[async_trait]
519impl SpendLedger for SubjectLedger {
520 async fn reserve(&self, key: &SpendKey, amount_micro_usd: u64) -> Result<ReservationId> {
521 let id = self.inner.reserve(key, amount_micro_usd).await?;
522 let mut holds = self.holds.lock().unwrap_or_else(|e| e.into_inner());
523 if holds.len() > 65_536 {
524 holds.clear();
525 }
526 holds.insert(id.clone(), key.clone());
527 Ok(id)
528 }
529
530 async fn commit(&self, id: ReservationId, actual_micro_usd: u64) -> Result<()> {
531 let key = self.holds.lock().unwrap_or_else(|e| e.into_inner()).remove(&id);
532 self.inner.commit(id, actual_micro_usd).await?;
533 if let (Some(key), Some(accounts)) = (key, self.accounts.upgrade()) {
534 accounts.charge(key, self.subject.clone(), actual_micro_usd);
535 }
536 Ok(())
537 }
538
539 async fn release(&self, id: ReservationId) -> Result<()> {
540 self.holds.lock().unwrap_or_else(|e| e.into_inner()).remove(&id);
541 self.inner.release(id).await
542 }
543
544 async fn spent(&self, key: &SpendKey, period: SpendPeriod) -> Result<u64> {
545 self.inner.spent(key, period).await
546 }
547}
548
549pub(crate) fn meter_run(accounts: &Arc<SpendAccounts>, config: &mut adk_core::RunConfig) {
552 if let Some(base) = config.spend_ledger.take() {
553 config.spend_ledger = Some(if accounts.is_ours(&base) {
554 base
555 } else {
556 accounts.ledger_for(base, config.acting.on_behalf_of.clone())
557 });
558 }
559 if config.budget_tracker.is_none() {
560 config.budget_tracker = Some(Arc::new(BudgetTracker::new(RunBudget::new())));
561 }
562}
563
564pub(crate) fn observe_run(
567 events: EventStream,
568 ctx: &Arc<dyn InvocationContext>,
569 span: Span,
570 accounts: Arc<SpendAccounts>,
571 trails: Arc<RunTrails>,
572 effort: crate::posture::Effort,
573) -> EventStream {
574 let config = ctx.run_config();
575 let acting = ctx.acting_context();
576 let audit = config.audit.clone().map(|trail| {
577 HarnessAudit::new(trail, AuditActor::for_context(ctx.as_ref()), ctx.session_id())
578 });
579 let tracker = config.budget_tracker.clone();
580 let session_key =
581 (ctx.app_name().to_string(), ctx.user_id().to_string(), ctx.session_id().to_string());
582 let spend_key = SpendKey::org(ctx.app_name()).with_agent(acting.agent.id.to_string());
583 if let Some(trail) = &config.audit {
584 trails.set(&session_key, trail.clone());
585 }
586 if let Some(tracker) = &tracker {
587 trails.usage_begin(&session_key, tracker.clone());
588 }
589 #[cfg(feature = "kernel")]
590 let tools = trails.tool_events(acting.agent.id.as_str(), ctx.invocation_id());
591 struct Finish {
592 audit: Option<HarnessAudit>,
593 tracker: Option<Arc<BudgetTracker>>,
594 accounts: Arc<SpendAccounts>,
595 trails: Arc<RunTrails>,
596 session_key: (String, String, String),
597 spend_key: SpendKey,
598 subject: Option<SubjectRef>,
599 effort: crate::posture::Effort,
600 tokens: TurnTokens,
601 settled: bool,
602 }
603 impl Finish {
604 fn observe(&mut self, event: &adk_core::Event) {
606 if event.llm_response.partial {
607 return;
608 }
609 if let Some(usage) = &event.llm_response.usage_metadata {
610 self.tokens.model_calls += 1;
611 self.tokens.prompt_tokens += u64::try_from(usage.prompt_token_count).unwrap_or(0);
612 self.tokens.cached_prompt_tokens +=
613 u64::try_from(usage.cache_read_input_token_count.unwrap_or(0)).unwrap_or(0);
614 }
615 }
616
617 fn settle(&mut self) -> BudgetUsage {
619 let usage = self.tracker.as_ref().map(|tracker| tracker.usage()).unwrap_or_default();
620 if !self.settled {
621 self.settled = true;
622 let units =
623 self.tracker.as_ref().map(|tracker| tracker.units()).unwrap_or_default();
624 self.trails.usage_settle(&self.session_key, &usage, &units);
625 self.trails.clear(&self.session_key);
626 self.accounts.finish_run(self.subject.clone(), &usage, self.tokens);
627 }
628 usage
629 }
630
631 async fn run(mut self) -> Result<()> {
632 let usage = self.settle();
633 let Some(audit) = &self.audit else {
634 return Ok(());
635 };
636 let remaining = self.tracker.as_ref().map(|tracker| {
637 let budget = tracker.budget();
638 json!({
639 "modelCalls": budget.max_model_calls.map(|max| max.saturating_sub(usage.model_calls)),
640 "totalTokens": budget.max_total_tokens.map(|max| max.saturating_sub(usage.total_tokens)),
641 "costMicroUsd": budget.max_cost_micro_usd.map(|max| max.saturating_sub(usage.cost_micro_usd)),
642 "toolCalls": budget.max_tool_calls.map(|max| max.saturating_sub(usage.tool_calls)),
643 })
644 });
645 audit
646 .record(
647 "harness.spend",
648 json!({
649 "spendKey": { "org": self.spend_key.org, "agent": self.spend_key.agent, "subject": self.subject },
650 "modelCalls": usage.model_calls,
651 "tokens": usage.total_tokens,
652 "promptTokens": self.tokens.prompt_tokens,
653 "cachedTokens": self.tokens.cached_prompt_tokens,
654 "effort": self.effort,
655 "cost": usage.cost_micro_usd,
656 "toolCalls": usage.tool_calls,
657 "budgetRemaining": remaining,
658 }),
659 )
660 .await
661 }
662 }
663 impl Drop for Finish {
667 fn drop(&mut self) {
668 self.settle();
669 }
670 }
671 let finish = Finish {
672 audit,
673 tracker,
674 accounts,
675 trails,
676 session_key,
677 spend_key,
678 subject: acting.on_behalf_of,
679 effort,
680 tokens: TurnTokens::default(),
681 settled: false,
682 };
683 #[cfg(not(feature = "kernel"))]
684 let tools: Option<()> = None;
685 let state = (events, Some(finish), span, tools, true);
686 Box::pin(futures::stream::unfold(
687 state,
688 |(mut events, mut finish, span, tools, first)| async move {
689 #[cfg(feature = "kernel")]
690 let mut tools = tools;
691 #[cfg(not(feature = "kernel"))]
692 let _ = first;
693 #[cfg(feature = "kernel")]
694 if first && let Some(tools) = &tools {
695 tools.intent().await;
696 }
697 let next = events.next().instrument(span.clone()).await;
698 match next {
699 Some(Ok(event)) => {
700 if let Some(finish) = finish.as_mut() {
701 finish.observe(&event);
702 }
703 #[cfg(feature = "kernel")]
704 if let Some(tools) = tools.as_mut() {
705 tools.observe(&event).await;
706 }
707 Some((Ok(event), (events, finish, span, tools, false)))
708 }
709 Some(Err(error)) => {
710 if let Some(finish) = finish
711 && let Err(audit_error) = finish.run().instrument(span.clone()).await
712 {
713 tracing::warn!(error = %audit_error, "could not record harness.spend");
714 }
715 Some((Err(error), (events, None, span, tools, false)))
716 }
717 None => match finish {
718 Some(finish) => match finish.run().instrument(span.clone()).await {
719 Ok(()) => None,
720 Err(error) => Some((Err(error), (events, None, span, tools, false))),
721 },
722 None => None,
723 },
724 }
725 },
726 ))
727}
728
729#[derive(Default)]
732struct SessionUsage {
733 model_calls: u64,
734 tool_calls: u64,
735 cost_micro_usd: u64,
736 total_tokens: u64,
737 units: adk_core::UsageVector,
738 live: Option<Arc<BudgetTracker>>,
739}
740
741#[derive(Default)]
746pub(crate) struct RunTrails {
747 trails: Mutex<HashMap<(String, String, String), AuditTrail>>,
748 usage: Mutex<HashMap<(String, String, String), SessionUsage>>,
749 verdicts: Mutex<HashMap<(String, String, String), String>>,
750 #[cfg(feature = "kernel")]
753 ledger: OnceLock<(adk_kernel::proc::LateLedgerSink, Arc<HashMap<String, String>>)>,
754}
755
756impl std::fmt::Debug for RunTrails {
757 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
758 f.debug_struct("RunTrails").finish_non_exhaustive()
759 }
760}
761
762fn session_key(app: &str, user: &str, session: &str) -> (String, String, String) {
763 (app.to_string(), user.to_string(), session.to_string())
764}
765
766impl RunTrails {
767 #[cfg(feature = "kernel")]
770 pub(crate) fn attach_ledger(
771 &self,
772 ledger: adk_kernel::proc::LateLedgerSink,
773 tools: &[Arc<dyn adk_core::Tool>],
774 ) {
775 let effects = tools
776 .iter()
777 .filter_map(|tool| {
778 let effect = serde_json::to_value(tool.effect()).ok()?.as_str()?.to_string();
779 Some((tool.name().to_string(), effect))
780 })
781 .collect();
782 let _ = self.ledger.set((ledger, Arc::new(effects)));
783 }
784
785 #[cfg(feature = "kernel")]
787 fn tool_events(&self, agent: &str, invocation: &str) -> Option<crate::kernel::ToolEvents> {
788 let (sink, effects) = self.ledger.get()?;
789 crate::kernel::ToolEvents::new(sink, effects, agent, invocation)
790 }
791
792 fn usage_begin(&self, key: &(String, String, String), tracker: Arc<BudgetTracker>) {
794 let mut usage = self.usage.lock().unwrap_or_else(|e| e.into_inner());
795 if usage.len() > 4096 {
796 usage.clear();
797 }
798 usage.entry(key.clone()).or_default().live = Some(tracker);
799 }
800
801 fn usage_settle(
803 &self,
804 key: &(String, String, String),
805 run: &BudgetUsage,
806 units: &adk_core::UsageVector,
807 ) {
808 let mut usage = self.usage.lock().unwrap_or_else(|e| e.into_inner());
809 let entry = usage.entry(key.clone()).or_default();
810 entry.model_calls += run.model_calls;
811 entry.tool_calls += run.tool_calls;
812 entry.cost_micro_usd = entry.cost_micro_usd.saturating_add(run.cost_micro_usd);
813 entry.total_tokens = entry.total_tokens.saturating_add(run.total_tokens);
814 entry.units.merge(units);
815 entry.live = None;
816 }
817
818 #[cfg(feature = "kernel")]
821 pub(crate) fn session_usage(
822 &self,
823 app: &str,
824 user: &str,
825 session: &str,
826 ) -> Option<adk_kernel::RunUsage> {
827 let usage = self.usage.lock().unwrap_or_else(|e| e.into_inner());
828 let entry = usage.get(&session_key(app, user, session))?;
829 let live = entry.live.as_ref().map(|tracker| tracker.usage()).unwrap_or_default();
830 let mut units = entry.units.clone();
831 if let Some(tracker) = &entry.live {
832 units.merge(&tracker.units());
833 }
834 Some(
835 adk_kernel::RunUsage::new(
836 entry.model_calls + live.model_calls,
837 entry.tool_calls + live.tool_calls,
838 entry.cost_micro_usd.saturating_add(live.cost_micro_usd),
839 )
840 .with_total_tokens(entry.total_tokens.saturating_add(live.total_tokens))
841 .with_units(units),
842 )
843 }
844
845 fn set_verdict(&self, key: (String, String, String), verdict: String) {
846 let mut verdicts = self.verdicts.lock().unwrap_or_else(|e| e.into_inner());
847 if verdicts.len() > 4096 {
848 verdicts.clear();
849 }
850 verdicts.insert(key, verdict);
851 }
852
853 #[cfg(feature = "kernel")]
855 pub(crate) fn verdict(&self, app: &str, user: &str, session: &str) -> Option<String> {
856 self.verdicts
857 .lock()
858 .unwrap_or_else(|e| e.into_inner())
859 .get(&session_key(app, user, session))
860 .cloned()
861 }
862
863 fn set(&self, key: &(String, String, String), trail: AuditTrail) {
864 let mut trails = self.trails.lock().unwrap_or_else(|e| e.into_inner());
865 if trails.len() > 4096 {
866 trails.clear();
867 }
868 trails.insert(key.clone(), trail);
869 }
870
871 fn clear(&self, key: &(String, String, String)) {
872 self.trails.lock().unwrap_or_else(|e| e.into_inner()).remove(key);
873 }
874
875 fn get(&self, ctx: &dyn ReadonlyContext) -> Option<AuditTrail> {
876 let key =
877 (ctx.app_name().to_string(), ctx.user_id().to_string(), ctx.session_id().to_string());
878 self.trails.lock().unwrap_or_else(|e| e.into_inner()).get(&key).cloned()
879 }
880}
881
882impl Default for LoopGuard {
885 fn default() -> Self {
888 Self { window: 20, max_identical_calls: 3, max_redundant: 6 }
889 }
890}
891
892#[derive(Clone, Copy, Debug, PartialEq, Eq)]
894pub(crate) struct LoopFinding {
895 pub(crate) identical: usize,
896 pub(crate) redundant: usize,
897}
898
899impl LoopGuard {
900 pub(crate) fn analyze(&self, calls: &[(String, Value)]) -> LoopFinding {
904 let start = calls.len().saturating_sub(self.window.max(1));
905 let records: Vec<ToolCallRecord> = calls[start..]
906 .iter()
907 .map(|(name, args)| ToolCallRecord {
908 name: adk_core::tool_call_fingerprint(name, args),
909 args: args.clone(),
910 })
911 .collect();
912 let analysis = analyzer().analyze_tool_calls(&records);
913 let identical = analysis
914 .diagnostics
915 .iter()
916 .filter(|diagnostic| matches!(diagnostic.pattern_type, TracePattern::RedundantCall))
917 .map(|diagnostic| diagnostic.occurrence_count + 1)
918 .max()
919 .unwrap_or(usize::from(!records.is_empty()));
920 let redundant = analysis.total_tool_calls.saturating_sub(analysis.useful_tool_calls);
921 LoopFinding { identical, redundant }
922 }
923
924 pub(crate) fn is_loop(&self, finding: LoopFinding) -> bool {
926 finding.identical >= self.max_identical_calls.max(2)
927 || finding.redundant >= self.max_redundant.max(1)
928 }
929}
930
931fn analyzer() -> &'static TraceAnalyzer {
932 static ANALYZER: OnceLock<TraceAnalyzer> = OnceLock::new();
933 ANALYZER.get_or_init(TraceAnalyzer::new)
934}
935
936fn function_calls(request: &LlmRequest) -> Vec<(String, Value)> {
938 request
939 .contents
940 .iter()
941 .flat_map(|content| content.parts.iter())
942 .filter_map(|part| match part {
943 Part::FunctionCall { name, args, .. } => Some((name.clone(), args.clone())),
944 _ => None,
945 })
946 .collect()
947}
948
949#[derive(Clone, Copy)]
950struct Seen {
951 start: usize,
953 checked: usize,
955}
956
957pub(crate) struct LoopGuardObserver {
959 guard: LoopGuard,
960 mode_store: Arc<dyn ModeStore>,
961 default_mode: HarnessMode,
962 trails: Arc<RunTrails>,
963 seen: Mutex<HashMap<(String, String), Seen>>,
964}
965
966impl LoopGuardObserver {
967 pub(crate) fn new(
968 guard: LoopGuard,
969 mode_store: Arc<dyn ModeStore>,
970 default_mode: HarnessMode,
971 trails: Arc<RunTrails>,
972 ) -> Self {
973 Self { guard, mode_store, default_mode, trails, seen: Mutex::new(HashMap::new()) }
974 }
975}
976
977#[async_trait]
978impl RequestObserver for LoopGuardObserver {
979 async fn before_request(
980 &self,
981 ctx: &Arc<dyn ReadonlyContext>,
982 request: &mut LlmRequest,
983 ) -> Result<()> {
984 let calls = function_calls(request);
985 let window = {
986 let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
987 if seen.len() > 4096 {
988 seen.clear();
989 }
990 let key = (ctx.invocation_id().to_string(), ctx.agent_name().to_string());
991 let entry =
992 seen.entry(key).or_insert(Seen { start: calls.len(), checked: calls.len() });
993 if calls.len() < entry.start {
994 *entry = Seen { start: calls.len(), checked: calls.len() };
996 }
997 if calls.len() == entry.checked {
998 return Ok(());
999 }
1000 entry.checked = calls.len();
1001 calls[entry.start..].to_vec()
1002 };
1003 let finding = self.guard.analyze(&window);
1004 let looping = self.guard.is_loop(finding);
1005 self.trails.set_verdict(
1006 session_key(ctx.app_name(), ctx.user_id(), ctx.session_id()),
1007 format!(
1008 "{}: {} identical, {} redundant in the last {}",
1009 if looping { "loop" } else { "ok" },
1010 finding.identical,
1011 finding.redundant,
1012 window.len().min(self.guard.window)
1013 ),
1014 );
1015 if !looping {
1016 return Ok(());
1017 }
1018 let reason = format!(
1019 "the loop guard stopped the turn: {} identical tool calls in a row and {} redundant \
1020 calls in the last {}; the session is now read-only until a person changes the mode",
1021 finding.identical,
1022 finding.redundant,
1023 window.len().min(self.guard.window)
1024 );
1025 tracing::warn!(
1026 harness.loop.identical = finding.identical,
1027 harness.loop.redundant = finding.redundant,
1028 agent.name = %ctx.agent_name(),
1029 "loop detected; tightening the session to read_only"
1030 );
1031 let audit = self.trails.get(ctx.as_ref()).map(|trail| {
1032 HarnessAudit::new(trail, AuditActor::for_context(ctx.as_ref()), ctx.session_id())
1033 });
1034 if let Some(audit) = &audit {
1035 audit
1036 .record(
1037 "harness.loop.detected",
1038 json!({
1039 "window": self.guard.window,
1040 "identicalCalls": finding.identical,
1041 "redundantCalls": finding.redundant,
1042 "agent": ctx.agent_name(),
1043 "action": "tighten_read_only",
1044 }),
1045 )
1046 .await?;
1047 }
1048 write_mode_change(
1049 self.mode_store.as_ref(),
1050 self.default_mode,
1051 (ctx.app_name(), ctx.user_id(), ctx.session_id()),
1052 HarnessMode::ReadOnly,
1053 ModeSource::SystemTighten,
1054 None,
1055 audit.as_ref(),
1056 &[],
1057 )
1058 .await?;
1059 Err(AdkError::new(
1060 ErrorComponent::Agent,
1061 ErrorCategory::ResourceExhausted,
1062 LOOP_DETECTED_CODE,
1063 reason,
1064 ))
1065 }
1066}
1067
1068pub(crate) async fn run_mode(
1070 store: &dyn ModeStore,
1071 default_mode: HarnessMode,
1072 ctx: &dyn ReadonlyContext,
1073) -> HarnessMode {
1074 match store.get(ctx.app_name(), ctx.user_id(), ctx.session_id()).await {
1075 Ok(Some(record)) => record.mode_for_invocation(ctx.invocation_id()),
1076 Ok(None) => default_mode,
1077 Err(_) => HarnessMode::ReadOnly,
1078 }
1079}
1080
1081#[cfg(test)]
1082mod tests {
1083 use super::*;
1084
1085 fn calls(names: &[(&str, Value)]) -> Vec<(String, Value)> {
1086 names.iter().map(|(name, args)| ((*name).to_string(), args.clone())).collect()
1087 }
1088
1089 #[test]
1090 fn identical_calls_in_a_row_are_a_loop() {
1091 let guard = LoopGuard::default();
1092 let read = ("read_file", json!({ "path": "a.rs" }));
1093 let finding = guard.analyze(&calls(&[read.clone(), read.clone(), read]));
1094 assert_eq!(finding.identical, 3);
1095 assert!(guard.is_loop(finding));
1096 }
1097
1098 #[test]
1099 fn an_edit_and_test_cycle_with_new_edits_is_not_a_loop() {
1100 let guard = LoopGuard::default();
1101 let mut cycle = Vec::new();
1102 for i in 0..5 {
1103 cycle.push(("edit_file", json!({ "path": "a.rs", "new": format!("v{i}") })));
1104 cycle.push(("bash", json!({ "command": "cargo test" })));
1105 }
1106 let finding = guard.analyze(&calls(&cycle));
1107 assert!(!guard.is_loop(finding), "{finding:?}");
1108 }
1109
1110 #[test]
1111 fn a_repeated_sequence_of_identical_calls_is_redundant() {
1112 let guard = LoopGuard { window: 20, max_identical_calls: 10, max_redundant: 4 };
1113 let a = ("read_file", json!({ "path": "a" }));
1114 let b = ("grep", json!({ "pattern": "x" }));
1115 let finding = guard.analyze(&calls(&[a.clone(), b.clone(), a.clone(), b.clone(), a, b]));
1116 assert_eq!(finding.redundant, 4);
1117 assert!(guard.is_loop(finding));
1118 }
1119
1120 #[test]
1121 fn spend_is_reported_per_subject() {
1122 let accounts = SpendAccounts::default();
1123 let alice = Some(SubjectRef::human("alice"));
1124 let key =
1125 SpendKey::org("app").with_agent("urn:adk:agent:app/harness").with_vendor("openai");
1126 accounts.charge(key.clone(), alice.clone(), 10);
1127 accounts.charge(key.clone(), alice, 5);
1128 accounts.charge(key, Some(SubjectRef::human("bob")), 7);
1129 let report = accounts.report(Some("alice"));
1130 assert_eq!((report.charges, report.cost_micro_usd), (2, 15));
1131 assert_eq!(accounts.report(None).cost_micro_usd, 22);
1132 }
1133}