1use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
9use std::sync::{Arc, Mutex, Weak};
10
11use adk_core::audit_log::{AuditActor, AuditTrail};
12use adk_core::{
13 ActingContext, BUILTIN_TOOL_ORIGIN, PolicyCall, PolicyDecision, STATIC_TOOL_ORIGIN,
14 ToolConfirmationRequest, ToolEffect, ToolOrigin, ToolPolicy, ToolPolicyRequest, async_trait,
15 tool_call_fingerprint,
16};
17use adk_devtools::Workspace;
18use chrono::Utc;
19use serde::{Deserialize, Serialize};
20use serde_json::{Value, json};
21
22use crate::approvals::StandingRuleStore;
23use crate::approvals::matcher::{
24 RuleCall, RuleEvaluation, RuleOutcome, evaluate_standing_rules, is_protected_path,
25 is_protected_target,
26};
27use crate::audit::HarnessAudit;
28use crate::mode::{HarnessMode, ModeStore};
29use crate::shell::{IsolationStatus, ShellLedger};
30
31pub const HARNESS_POLICY_REF: &str = "adk-harness";
39
40pub(crate) const HARNESS_TOOL_NAMES: &[&str] = &[
42 "read_file",
43 "glob",
44 "grep",
45 "harness_help",
46 "write_file",
47 "edit_file",
48 "apply_patch",
49 "bash",
50 "shell_output",
51 "shell_kill",
52 "write_todos",
53 "update_todo",
54 "exit_plan_mode",
55 "list_skills",
56 "load_skill",
57 "load_skill_resource",
58 "search_skills",
59 "memory_read",
60 "memory_write",
61 "memory_delete",
62 "memory_search",
63 "memory_remember",
64 "web_fetch",
65 "web_search",
66 "mcp_list_resources",
67 "mcp_read_resource",
68];
69
70static COMPOSED_LAYERS: Mutex<Vec<(usize, Weak<dyn ToolPolicy>)>> = Mutex::new(Vec::new());
72
73fn address(policy: &dyn ToolPolicy) -> *const () {
74 std::ptr::from_ref(policy).cast::<()>()
75}
76
77pub(crate) fn register_composed_layer(owner: usize, policy: &Arc<dyn ToolPolicy>) {
79 let mut layers = COMPOSED_LAYERS.lock().unwrap_or_else(|e| e.into_inner());
80 layers.retain(|(_, layer)| layer.strong_count() > 0);
81 layers.push((owner, Arc::downgrade(policy)));
82}
83
84pub(crate) fn composed_layer_owner(policy: &dyn ToolPolicy) -> Option<usize> {
86 let target = address(policy);
87 let layers = COMPOSED_LAYERS.lock().unwrap_or_else(|e| e.into_inner());
88 layers
89 .iter()
90 .find(|(_, layer)| layer.strong_count() > 0 && layer.as_ptr().cast::<()>() == target)
91 .map(|(owner, _)| *owner)
92}
93
94pub fn has_harness_layer(policy: &dyn ToolPolicy) -> bool {
124 composed_layer_owner(policy).is_some()
125}
126
127#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
137#[serde(rename_all = "snake_case")]
138pub enum Isolation {
139 OsSandbox,
141 Container,
143 Host,
145}
146
147#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
164#[serde(rename_all = "snake_case")]
165#[non_exhaustive]
166pub enum ToolKind {
167 Read,
171 Todo,
173 PlanExit,
175 Edit,
177 Shell(Isolation),
179 ShellEscalation,
181 Delegate,
183 MemoryWrite,
185 MemoryPropose,
188 Web {
191 allowlisted: bool,
193 },
194 Payment,
196 ComputerUse,
199 External {
201 effect: ToolEffect,
203 trusted_origin: bool,
205 },
206}
207
208impl ToolKind {
209 pub fn rule_eligible(&self) -> bool {
211 !matches!(self, Self::PlanExit | Self::Payment | Self::MemoryWrite | Self::ComputerUse)
212 }
213
214 pub fn is_shell(&self) -> bool {
216 matches!(self, Self::Shell(_) | Self::ShellEscalation)
217 }
218}
219
220#[derive(Clone, Debug, Default)]
242pub struct ToolClassRegistry {
243 agents: BTreeSet<String>,
244 classes: BTreeMap<String, ToolKind>,
245 web_allowlist: Vec<String>,
247 fetch_domains: Option<crate::web::SearchDomains>,
249 origin_classes: Vec<Arc<dyn OriginClasses>>,
252 call_classes: Vec<Arc<dyn CallClasses>>,
254}
255
256pub trait OriginClasses: std::fmt::Debug + Send + Sync {
286 fn class_of(&self, source: &str, tool: &str) -> Option<ToolKind>;
289}
290
291pub trait CallClasses: std::fmt::Debug + Send + Sync {
322 fn class_of_call(&self, tool: &str, args: &Value) -> Option<ToolKind>;
324
325 fn denial_in_mode(&self, tool: &str, args: &Value, mode: HarnessMode) -> Option<String> {
329 let _ = (tool, args, mode);
330 None
331 }
332}
333
334impl ToolClassRegistry {
335 pub fn new() -> Self {
337 Self::default()
338 }
339
340 pub fn harness_defaults(agent: &str) -> Self {
342 let mut registry = Self::new().with_agent(agent);
343 for name in [
344 "read_file",
345 "glob",
346 "grep",
347 "harness_help",
348 "list_skills",
349 "load_skill",
350 "load_skill_resource",
351 "search_skills",
352 ] {
353 registry.register(name, ToolKind::Read);
354 }
355 registry.register("write_todos", ToolKind::Todo);
356 registry.register("update_todo", ToolKind::Todo);
357 #[cfg(feature = "kernel")]
359 registry.register(crate::kernel::PROPOSE_FOLLOWUP, ToolKind::Todo);
360 #[cfg(feature = "kernel")]
362 registry.register(crate::agents::PROPOSE_AGENT, ToolKind::Todo);
363 registry.register("exit_plan_mode", ToolKind::PlanExit);
364 registry.register("write_file", ToolKind::Edit);
365 registry.register("edit_file", ToolKind::Edit);
366 registry.register("apply_patch", ToolKind::Edit);
367 registry.register("bash", ToolKind::Shell(Isolation::Host));
368 registry.register(crate::shell::SHELL_OUTPUT, ToolKind::Read);
370 registry.register(crate::shell::SHELL_KILL, ToolKind::Read);
371 registry.register("memory_read", ToolKind::Read);
372 registry.register("memory_write", ToolKind::MemoryWrite);
373 registry.register("memory_delete", ToolKind::MemoryWrite);
374 registry.register("memory_search", ToolKind::Read);
375 registry.register("memory_remember", ToolKind::MemoryPropose);
376 registry.register("web_fetch", ToolKind::Web { allowlisted: false });
378 registry.register("web_search", ToolKind::Web { allowlisted: false });
379 registry.register("mcp_list_resources", ToolKind::Read);
380 registry.register("mcp_read_resource", ToolKind::Read);
381 registry
382 }
383
384 #[must_use]
402 pub fn with_web_allowlist(
403 mut self,
404 domains: impl IntoIterator<Item = impl Into<String>>,
405 ) -> Self {
406 self.web_allowlist = domains.into_iter().map(|d| d.into().to_ascii_lowercase()).collect();
407 self
408 }
409
410 #[must_use]
413 pub fn with_call_classes(mut self, classes: Arc<dyn CallClasses>) -> Self {
414 self.call_classes.push(classes);
415 self
416 }
417
418 #[must_use]
421 pub fn with_origin_classes(mut self, classes: Arc<dyn OriginClasses>) -> Self {
422 self.origin_classes.push(classes);
423 self
424 }
425
426 pub fn web_allowlist(&self) -> &[String] {
428 &self.web_allowlist
429 }
430
431 #[must_use]
446 pub fn with_fetch_domains(mut self, filter: Option<crate::web::SearchDomains>) -> Self {
447 self.fetch_domains = filter;
448 self
449 }
450
451 pub fn fetch_domains(&self) -> Option<&crate::web::SearchDomains> {
453 self.fetch_domains.as_ref()
454 }
455
456 fn web_allowlisted(&self, tool: &str, args: &Value) -> bool {
460 match tool {
461 "web_search" => args.get("site").and_then(Value::as_str).is_some_and(|site| {
462 crate::web::ParsedUrl::parse(&format!("https://{site}/")).is_ok_and(|parsed| {
463 crate::web::host_allowlisted(&parsed.host, &self.web_allowlist)
464 })
465 }),
466 _ => args
467 .get("url")
468 .and_then(Value::as_str)
469 .is_some_and(|url| crate::web::url_allowlisted(url, &self.web_allowlist)),
470 }
471 }
472
473 #[must_use]
475 pub fn with_agent(mut self, agent: impl Into<String>) -> Self {
476 self.agents.insert(agent.into());
477 self
478 }
479
480 pub fn register(&mut self, name: impl Into<String>, kind: ToolKind) {
482 self.classes.insert(name.into(), kind);
483 }
484
485 pub fn unregister(&mut self, name: &str) {
487 self.classes.remove(name);
488 }
489
490 pub fn is_registered(&self, name: &str) -> bool {
492 self.classes.contains_key(name)
493 }
494
495 pub fn denial_in_mode(
498 &self,
499 agent: &str,
500 tool: &str,
501 origin: Option<&ToolOrigin>,
502 args: &Value,
503 mode: HarnessMode,
504 ) -> Option<String> {
505 let static_origin = origin.is_none_or(|origin| origin.source == STATIC_TOOL_ORIGIN);
506 (static_origin && self.agents.contains(agent))
507 .then(|| {
508 self.call_classes
509 .iter()
510 .find_map(|classes| classes.denial_in_mode(tool, args, mode))
511 })
512 .flatten()
513 }
514
515 #[allow(clippy::too_many_arguments)]
517 pub fn classify(
518 &self,
519 agent: &str,
520 tool: &str,
521 origin: Option<&ToolOrigin>,
522 args: &Value,
523 effect: ToolEffect,
524 isolation: Isolation,
525 trust_mcp_read_only_hints: bool,
526 ) -> ToolKind {
527 let static_origin = origin.is_none_or(|origin| origin.source == STATIC_TOOL_ORIGIN);
528 if static_origin && self.agents.contains(agent) {
529 if let Some(kind) =
530 self.call_classes.iter().find_map(|classes| classes.class_of_call(tool, args))
531 {
532 return kind;
533 }
534 match self.classes.get(tool) {
535 Some(ToolKind::Shell(_)) => {
536 return if args.get("unsandboxed").and_then(Value::as_bool) == Some(true) {
537 ToolKind::ShellEscalation
538 } else {
539 ToolKind::Shell(isolation)
540 };
541 }
542 Some(ToolKind::Web { .. }) => {
543 return ToolKind::Web { allowlisted: self.web_allowlisted(tool, args) };
544 }
545 Some(kind) => return *kind,
546 None => {}
547 }
548 }
549 if let Some(origin) = origin.filter(|origin| origin.source != STATIC_TOOL_ORIGIN)
550 && let Some(kind) = self
551 .origin_classes
552 .iter()
553 .find_map(|classes| classes.class_of(&origin.source, tool))
554 {
555 return kind;
556 }
557 let trusted_origin = match origin {
558 Some(origin) if origin.source == STATIC_TOOL_ORIGIN => true,
559 Some(origin) if origin.source.starts_with("mcp:") => trust_mcp_read_only_hints,
560 _ => false,
561 };
562 ToolKind::External { effect, trusted_origin }
563 }
564}
565
566#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
577pub enum TableRow {
578 ReadTodoDelegate,
580 PlanExit,
582 Edit,
584 EditProtected,
586 ShellOsSandbox,
588 ShellContainer,
590 ShellHost,
592 ShellEscalation,
594 MemoryWrite,
596 MemoryPropose,
598 WebAllowlisted,
600 WebOther,
602 Payment,
604 ComputerUse,
606 ExternalReadOnlyTrusted,
608 ExternalOther,
610}
611
612impl TableRow {
613 pub const ALL: [TableRow; 16] = [
615 Self::ReadTodoDelegate,
616 Self::PlanExit,
617 Self::Edit,
618 Self::EditProtected,
619 Self::ShellOsSandbox,
620 Self::ShellContainer,
621 Self::ShellHost,
622 Self::ShellEscalation,
623 Self::MemoryWrite,
624 Self::MemoryPropose,
625 Self::WebAllowlisted,
626 Self::WebOther,
627 Self::Payment,
628 Self::ComputerUse,
629 Self::ExternalReadOnlyTrusted,
630 Self::ExternalOther,
631 ];
632
633 pub fn of(kind: &ToolKind, protected_path: bool) -> Self {
635 match kind {
636 ToolKind::Read | ToolKind::Todo | ToolKind::Delegate => Self::ReadTodoDelegate,
637 ToolKind::PlanExit => Self::PlanExit,
638 ToolKind::Edit if protected_path => Self::EditProtected,
639 ToolKind::Edit => Self::Edit,
640 ToolKind::Shell(Isolation::OsSandbox) => Self::ShellOsSandbox,
641 ToolKind::Shell(Isolation::Container) => Self::ShellContainer,
642 ToolKind::Shell(Isolation::Host) => Self::ShellHost,
643 ToolKind::ShellEscalation => Self::ShellEscalation,
644 ToolKind::MemoryWrite => Self::MemoryWrite,
645 ToolKind::MemoryPropose => Self::MemoryPropose,
646 ToolKind::Web { allowlisted: true } => Self::WebAllowlisted,
647 ToolKind::Web { allowlisted: false } => Self::WebOther,
648 ToolKind::Payment => Self::Payment,
649 ToolKind::ComputerUse => Self::ComputerUse,
650 ToolKind::External { effect: ToolEffect::ReadOnly, trusted_origin: true } => {
651 Self::ExternalReadOnlyTrusted
652 }
653 ToolKind::External { .. } => Self::ExternalOther,
654 }
655 }
656
657 pub fn is_non_waivable(self) -> bool {
660 matches!(
661 self,
662 Self::PlanExit
663 | Self::EditProtected
664 | Self::ShellEscalation
665 | Self::MemoryWrite
666 | Self::Payment
667 | Self::ComputerUse
668 )
669 }
670
671 fn index(self) -> usize {
672 Self::ALL.iter().position(|row| *row == self).unwrap_or(Self::ALL.len() - 1)
673 }
674}
675
676#[derive(Clone, Copy, Debug, PartialEq, Eq)]
687pub enum ModeCell {
688 Allow,
690 Deny,
692 Ask,
694 AskNonWaivable,
696 AllowWithActiveEnforcer,
699 AskOrAutoAllowSandboxed,
701 AllowWithS3,
704 AskOrHostShellInAuto,
706}
707
708#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
717pub struct PolicySwitches {
718 pub auto_allow_sandboxed: bool,
720 pub allow_host_shell_in_auto: bool,
722 pub enforcer_active: bool,
724 pub sandbox_protects_paths: bool,
726}
727
728#[derive(Clone, Copy, Debug, PartialEq, Eq)]
738pub enum TableDecision {
739 Allow,
741 Deny,
743 RequireApproval {
745 non_waivable: bool,
747 },
748}
749
750impl TableDecision {
751 pub fn is_non_waivable(self) -> bool {
753 matches!(self, Self::RequireApproval { non_waivable: true })
754 }
755}
756
757impl ModeCell {
758 pub fn resolve(self, switches: &PolicySwitches) -> TableDecision {
760 let ask = TableDecision::RequireApproval { non_waivable: false };
761 match self {
762 Self::Allow => TableDecision::Allow,
763 Self::Deny => TableDecision::Deny,
764 Self::Ask => ask,
765 Self::AskNonWaivable => TableDecision::RequireApproval { non_waivable: true },
766 Self::AllowWithActiveEnforcer => {
767 if switches.enforcer_active {
768 TableDecision::Allow
769 } else {
770 TableDecision::Deny
771 }
772 }
773 Self::AskOrAutoAllowSandboxed => {
774 if switches.auto_allow_sandboxed && switches.sandbox_protects_paths {
775 TableDecision::Allow
776 } else {
777 ask
778 }
779 }
780 Self::AllowWithS3 => {
781 if switches.sandbox_protects_paths {
782 TableDecision::Allow
783 } else {
784 ask
785 }
786 }
787 Self::AskOrHostShellInAuto => {
788 if switches.allow_host_shell_in_auto {
789 TableDecision::Allow
790 } else {
791 ask
792 }
793 }
794 }
795 }
796}
797
798pub const MODE_TABLE: [[ModeCell; 4]; 16] = {
811 use ModeCell::{
812 Allow, AllowWithActiveEnforcer, AllowWithS3, Ask, AskNonWaivable, AskOrAutoAllowSandboxed,
813 AskOrHostShellInAuto, Deny,
814 };
815 [
816 [Allow, Allow, Allow, Allow], [Deny, AskNonWaivable, Deny, Deny], [Deny, Deny, Ask, Allow], [Deny, Deny, AskNonWaivable, AskNonWaivable], [Deny, AllowWithActiveEnforcer, AskOrAutoAllowSandboxed, AllowWithS3], [Deny, Deny, AskOrAutoAllowSandboxed, Allow], [Deny, Deny, Ask, AskOrHostShellInAuto], [Deny, Deny, AskNonWaivable, AskNonWaivable], [Deny, Deny, AskNonWaivable, AskNonWaivable], [Deny, Deny, Allow, Allow], [Allow, Allow, Allow, Allow], [Deny, Deny, Ask, Ask], [Deny, Deny, AskNonWaivable, AskNonWaivable], [Deny, Deny, AskNonWaivable, AskNonWaivable], [Allow, Allow, Allow, Allow], [Deny, Deny, Ask, Ask], ]
834};
835
836fn mode_index(mode: HarnessMode) -> usize {
837 HarnessMode::ALL.iter().position(|m| *m == mode).unwrap_or(0)
838}
839
840pub fn decision_cell(mode: HarnessMode, row: TableRow) -> ModeCell {
850 MODE_TABLE[row.index()][mode_index(mode)]
851}
852
853pub fn apply_rule(base: TableDecision, rule: &RuleOutcome, reason: &str) -> PolicyDecision {
872 if base == TableDecision::Deny {
873 return PolicyDecision::deny(reason);
874 }
875 if let RuleOutcome::Deny { reason, .. } = rule {
876 return PolicyDecision::deny(format!("a standing rule denies it: {reason}"));
877 }
878 match base {
879 TableDecision::Allow => PolicyDecision::Allow,
880 TableDecision::RequireApproval { non_waivable: true } => PolicyDecision::require_approval(
881 format!("{reason}; it needs a one-time approval and no standing rule applies"),
882 ),
883 TableDecision::RequireApproval { non_waivable: false } => match rule {
884 RuleOutcome::Allow { .. } => PolicyDecision::Allow,
885 _ => PolicyDecision::require_approval(reason),
886 },
887 TableDecision::Deny => PolicyDecision::deny(reason),
888 }
889}
890
891#[derive(Clone, Debug)]
893pub(crate) struct Evaluated {
894 pub(crate) decision: PolicyDecision,
895 pub(crate) kind: ToolKind,
896 pub(crate) mode: HarnessMode,
897 pub(crate) base: TableDecision,
898 pub(crate) rule: Option<crate::approvals::RuleHit>,
900}
901
902#[derive(Clone, Debug)]
904pub(crate) struct PromptContext {
905 pub(crate) harness_held: bool,
908 pub(crate) peers: Option<Arc<dyn ToolPolicy>>,
910 pub(crate) governance: Vec<adk_core::GovernanceControl>,
912 pub(crate) app_name: String,
913 pub(crate) user_id: String,
914 pub(crate) session_id: String,
915 pub(crate) invocation_id: String,
916 pub(crate) agent_name: String,
917 pub(crate) effect: ToolEffect,
918 pub(crate) acting: Option<ActingContext>,
919 pub(crate) audit: Option<AuditTrail>,
920}
921
922impl PromptContext {
923 pub(crate) fn policy_request(&self, tool_name: &str, args: &Value) -> ToolPolicyRequest {
924 let mut request = ToolPolicyRequest::new(tool_name, args.clone())
925 .with_effect(self.effect)
926 .with_agent_name(self.agent_name.clone())
927 .with_identity(self.app_name.clone(), self.user_id.clone(), self.session_id.clone())
928 .with_invocation_id(self.invocation_id.clone());
929 if let Some(acting) = &self.acting {
930 request = request.with_acting_context(acting.clone());
931 }
932 request
933 }
934
935 pub(crate) fn audit(&self) -> Option<HarnessAudit> {
936 let trail = self.audit.clone()?;
937 let actor = match &self.acting {
938 Some(acting) => AuditActor::new(acting, self.invocation_id.clone()),
939 None => AuditActor::for_invocation(
940 &self.app_name,
941 &self.agent_name,
942 &self.user_id,
943 &self.invocation_id,
944 ),
945 };
946 Some(HarnessAudit::new(trail, actor, self.session_id.clone()))
947 }
948}
949
950const PROMPT_CONTEXT_CAP: usize = 4096;
952
953fn call_key(agent: &str, subject: &str, tool: &str, args: &Value) -> String {
954 format!("{agent}\u{1f}{subject}\u{1f}{}", tool_call_fingerprint(tool, args))
955}
956
957#[derive(Debug, Default)]
960struct ByCall {
961 entries: HashMap<String, (u64, PromptContext)>,
962 order: VecDeque<(u64, String)>,
963 next: u64,
964}
965
966#[derive(Debug, Default)]
968pub(crate) struct PromptContexts {
969 by_call: Mutex<ByCall>,
970 by_key: Mutex<HashMap<String, VecDeque<PromptContext>>>,
971}
972
973impl PromptContexts {
974 fn insert(&self, call_id: Option<&str>, key: String, context: PromptContext) {
975 if let Some(call_id) = call_id {
976 let mut by_call = self.by_call.lock().unwrap_or_else(|e| e.into_inner());
977 by_call.next += 1;
978 let seq = by_call.next;
979 by_call.entries.insert(call_id.to_string(), (seq, context.clone()));
980 by_call.order.push_back((seq, call_id.to_string()));
981 while by_call.order.len() > PROMPT_CONTEXT_CAP {
982 let Some((seq, oldest)) = by_call.order.pop_front() else { break };
983 if by_call.entries.get(&oldest).is_some_and(|(at, _)| *at == seq) {
984 by_call.entries.remove(&oldest);
985 }
986 }
987 }
988 if !context.harness_held {
989 return;
991 }
992 let mut by_key = self.by_key.lock().unwrap_or_else(|e| e.into_inner());
993 if by_key.len() >= PROMPT_CONTEXT_CAP {
994 by_key.clear();
995 }
996 let queue = by_key.entry(key).or_default();
997 queue.push_back(context);
998 while queue.len() > 16 {
999 queue.pop_front();
1000 }
1001 }
1002
1003 #[cfg(feature = "acp-server")]
1005 pub(crate) fn by_call_id(&self, call_id: &str) -> Option<PromptContext> {
1006 let by_call = self.by_call.lock().unwrap_or_else(|e| e.into_inner());
1007 by_call.entries.get(call_id).map(|(_, context)| context.clone())
1008 }
1009
1010 pub(crate) fn take(&self, request: &ToolConfirmationRequest) -> Option<PromptContext> {
1012 if let Some(call_id) = request.function_call_id.as_deref() {
1013 let found = self
1014 .by_call
1015 .lock()
1016 .unwrap_or_else(|e| e.into_inner())
1017 .entries
1018 .remove(call_id)
1019 .map(|(_, context)| context);
1020 if found.is_some() {
1021 return found;
1022 }
1023 }
1024 let acting = request.acting.as_deref()?;
1025 let subject = acting.on_behalf_of.as_ref().map(|s| s.id.as_str()).unwrap_or_default();
1026 let key = call_key(acting.agent.id.as_str(), subject, &request.tool_name, &request.args);
1027 let mut by_key = self.by_key.lock().unwrap_or_else(|e| e.into_inner());
1028 let queue = by_key.get_mut(&key)?;
1029 let context = queue.pop_front();
1030 if queue.is_empty() {
1031 by_key.remove(&key);
1032 }
1033 context
1034 }
1035}
1036
1037#[derive(Clone, Debug)]
1039pub(crate) struct ShellView {
1040 pub(crate) status: IsolationStatus,
1041 pub(crate) allow_unsandboxed_retry: bool,
1042 pub(crate) fail_if_unavailable: bool,
1043 pub(crate) guards_protected_names: bool,
1045}
1046
1047pub(crate) struct PolicyInner {
1048 pub(crate) registry: ToolClassRegistry,
1049 pub(crate) mode_store: Arc<dyn ModeStore>,
1050 pub(crate) default_mode: HarnessMode,
1051 pub(crate) rules: Arc<dyn StandingRuleStore>,
1052 pub(crate) ledger: Arc<dyn ShellLedger>,
1053 pub(crate) workspace: Workspace,
1054 pub(crate) shell: ShellView,
1055 pub(crate) switches: PolicySwitches,
1056 pub(crate) trust_mcp_read_only_hints: bool,
1057 pub(crate) prompts: PromptContexts,
1058 pub(crate) provider_web_tools: BTreeSet<String>,
1060 #[cfg(feature = "hooks")]
1061 pub(crate) hooks: Option<Arc<crate::hooks::HookRunner>>,
1062 #[cfg(feature = "auth")]
1063 pub(crate) identity: Arc<crate::identity::IdentityGate>,
1064 #[cfg(feature = "observe")]
1065 pub(crate) root_agent: String,
1066 pub(crate) rule_observer: std::sync::OnceLock<Arc<dyn crate::approvals::ApprovalPrompter>>,
1068}
1069
1070#[derive(Clone)]
1085pub struct HarnessPolicy {
1086 pub(crate) inner: Arc<PolicyInner>,
1087 audit: Option<AuditTrail>,
1088 peers: Option<Arc<dyn ToolPolicy>>,
1089 governance: Vec<adk_core::GovernanceControl>,
1090}
1091
1092impl std::fmt::Debug for HarnessPolicy {
1093 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1094 f.debug_struct("HarnessPolicy")
1095 .field("default_mode", &self.inner.default_mode)
1096 .field("isolation", &self.inner.shell.status)
1097 .field("audit", &self.audit.is_some())
1098 .finish()
1099 }
1100}
1101
1102impl HarnessPolicy {
1103 pub(crate) fn new(inner: PolicyInner) -> Self {
1104 Self { inner: Arc::new(inner), audit: None, peers: None, governance: Vec::new() }
1105 }
1106
1107 pub(crate) fn with_audit(&self, audit: Option<AuditTrail>) -> Self {
1109 Self {
1110 inner: self.inner.clone(),
1111 audit,
1112 peers: self.peers.clone(),
1113 governance: self.governance.clone(),
1114 }
1115 }
1116
1117 pub(crate) fn with_peers(mut self, peers: Option<Arc<dyn ToolPolicy>>) -> Self {
1120 self.peers = peers;
1121 self
1122 }
1123
1124 pub(crate) fn with_governance(mut self, governance: Vec<adk_core::GovernanceControl>) -> Self {
1127 self.governance = governance;
1128 self
1129 }
1130
1131 pub(crate) fn observe_rules(&self, prompter: Arc<dyn crate::approvals::ApprovalPrompter>) {
1134 let _ = self.inner.rule_observer.set(prompter);
1135 }
1136
1137 pub(crate) fn owner_id(&self) -> usize {
1139 Arc::as_ptr(&self.inner) as usize
1140 }
1141
1142 pub fn default_mode(&self) -> HarnessMode {
1144 self.inner.default_mode
1145 }
1146
1147 pub fn registry(&self) -> &ToolClassRegistry {
1149 &self.inner.registry
1150 }
1151
1152 pub async fn mode_for(
1162 &self,
1163 app: &str,
1164 user: &str,
1165 session: &str,
1166 invocation_id: &str,
1167 ) -> HarnessMode {
1168 self.mode_and_plan_exit(app, user, session, invocation_id).await.0
1169 }
1170
1171 async fn mode_and_plan_exit(
1174 &self,
1175 app: &str,
1176 user: &str,
1177 session: &str,
1178 invocation_id: &str,
1179 ) -> (HarnessMode, bool) {
1180 match self.inner.mode_store.get(app, user, session).await {
1181 Ok(Some(record)) => (
1182 record.mode_for_invocation(invocation_id),
1183 record.set_by == crate::mode::ModeSource::PlanApproval
1184 && record.effective_from.as_deref() == Some(invocation_id),
1185 ),
1186 Ok(None) => (self.inner.default_mode, false),
1187 Err(error) => {
1188 tracing::warn!(error = %error, "mode store unavailable; evaluating as read_only");
1189 (HarnessMode::ReadOnly, false)
1190 }
1191 }
1192 }
1193
1194 pub fn classify(&self, request: &ToolPolicyRequest, origin: Option<&ToolOrigin>) -> ToolKind {
1196 if self.inner.provider_web_tools.contains(&request.tool_name) {
1199 return ToolKind::Web { allowlisted: true };
1200 }
1201 self.inner.registry.classify(
1202 &request.agent_name,
1203 &request.tool_name,
1204 origin,
1205 &request.args,
1206 request.effect,
1207 self.inner.shell.status.isolation(),
1208 self.inner.trust_mcp_read_only_hints,
1209 )
1210 }
1211
1212 fn audit_for(&self, request: &ToolPolicyRequest) -> Option<HarnessAudit> {
1213 let trail = self.audit.clone()?;
1214 let actor = match &request.acting {
1215 Some(acting) => AuditActor::new(acting, request.invocation_id.clone()),
1216 None => AuditActor::for_invocation(
1217 &request.app_name,
1218 &request.agent_name,
1219 &request.user_id,
1220 &request.invocation_id,
1221 ),
1222 };
1223 Some(HarnessAudit::new(trail, actor, request.session_id.clone()))
1224 }
1225
1226 async fn hard_deny(
1228 &self,
1229 request: &ToolPolicyRequest,
1230 origin: Option<&ToolOrigin>,
1231 kind: &ToolKind,
1232 ) -> Option<String> {
1233 if request.tool_name == crate::take_over::TAKE_OVER_TOOL {
1236 return Some(format!(
1237 "'{}' is reserved for take over; no tool may carry that name",
1238 request.tool_name
1239 ));
1240 }
1241 if origin.is_some_and(|origin| origin.source == BUILTIN_TOOL_ORIGIN)
1242 && is_provider_shell_builtin(&request.tool_name)
1243 {
1244 return Some(format!(
1245 "'{}' is a provider-executed shell; the harness runs commands only through its own bash",
1246 request.tool_name
1247 ));
1248 }
1249 if matches!(kind, ToolKind::Read | ToolKind::Edit)
1250 && let Some(paths) = crate::edits::edit_paths(&request.tool_name, &request.args)
1251 && let Some(path) =
1252 paths.iter().find(|path| self.inner.workspace.resolve(path).is_err())
1253 {
1254 return Some(format!("path '{path}' is outside the workspace"));
1255 }
1256 if matches!(kind, ToolKind::Shell(_))
1257 && self.inner.shell.fail_if_unavailable
1258 && let IsolationStatus::Degraded { requested, reason } = &self.inner.shell.status
1259 {
1260 return Some(format!("the requested {requested} shell is unavailable: {reason}"));
1261 }
1262 if *kind == ToolKind::ShellEscalation {
1263 return self.retry_refusal(request).await;
1264 }
1265 if matches!(kind, ToolKind::Web { .. })
1268 && let Some(url) = request.args.get("url").and_then(Value::as_str)
1269 && crate::web::url_names_private_target(url)
1270 {
1271 return Some(format!(
1272 "harness.web.private_target: '{}' is a private or local target the harness never fetches",
1273 crate::web::url_host(url).unwrap_or_default()
1274 ));
1275 }
1276 if matches!(kind, ToolKind::Web { .. })
1278 && let Some(filter) = self.inner.registry.fetch_domains()
1279 && let Some(url) = request.args.get("url").and_then(Value::as_str)
1280 && let Some(host) = crate::web::url_host(url)
1281 && !filter.permits(&host)
1282 {
1283 return Some(format!(
1284 "harness.web.domain_not_allowed: '{host}' is outside the harness's fetch filter \
1285 ({filter}), which no approval widens"
1286 ));
1287 }
1288 None
1289 }
1290
1291 async fn retry_refusal(&self, request: &ToolPolicyRequest) -> Option<String> {
1294 if !self.inner.shell.allow_unsandboxed_retry {
1295 return Some("unsandboxed retries are turned off for this harness".to_string());
1296 }
1297 if self.inner.shell.status.behaves_as_host() {
1298 return Some(
1299 "the shell already runs on the host; there is no sandboxed call to retry".into(),
1300 );
1301 }
1302 let Some(retry_of) = request.args.get("retry_of").and_then(Value::as_str) else {
1303 return Some(
1304 "an unsandboxed command needs retry_of naming the failed sandboxed call".into(),
1305 );
1306 };
1307 if request.args.get("reason").and_then(Value::as_str).is_none_or(|r| r.trim().is_empty()) {
1308 return Some("an unsandboxed retry needs a reason".into());
1309 }
1310 let command = request.args.get("command").and_then(Value::as_str).unwrap_or_default();
1311 match self
1312 .inner
1313 .ledger
1314 .get(&request.app_name, &request.user_id, &request.session_id, retry_of)
1315 .await
1316 {
1317 Ok(Some(entry))
1318 if entry.sandboxed
1319 && entry.failed()
1320 && entry.command == command
1321 && entry.retried_by.is_none() =>
1322 {
1323 None
1324 }
1325 Ok(Some(_)) => Some(format!(
1326 "retry_of '{retry_of}' is not a failed sandboxed call with this exact command that \
1327 has not been retried"
1328 )),
1329 Ok(None) => Some(format!("retry_of '{retry_of}' names no bash call in this session")),
1330 Err(error) => Some(format!("the shell ledger is unavailable: {error}")),
1331 }
1332 }
1333
1334 pub async fn decide(
1348 &self,
1349 request: &ToolPolicyRequest,
1350 origin: Option<&ToolOrigin>,
1351 call_id: Option<&str>,
1352 ) -> PolicyDecision {
1353 #[cfg(feature = "observe")]
1354 let span = crate::observe::decision_span(&request.tool_name, &self.inner.shell.status);
1355 #[cfg(feature = "observe")]
1356 let evaluated = {
1357 use tracing::Instrument as _;
1358 self.evaluate_full(request, origin, call_id, true).instrument(span.clone()).await
1359 };
1360 #[cfg(not(feature = "observe"))]
1361 let evaluated = self.evaluate_full(request, origin, call_id, true).await;
1362 #[cfg(feature = "observe")]
1363 {
1364 span.record("harness.tool_kind", crate::observe::tool_kind_label(&evaluated.kind));
1365 span.record("harness.mode", evaluated.mode.as_str());
1366 span.record("harness.decision", format!("{:?}", evaluated.decision).as_str());
1367 if request.agent_name != self.inner.root_agent {
1368 span.record("harness.member", request.agent_name.as_str());
1369 }
1370 }
1371 if evaluated.kind == ToolKind::ShellEscalation {
1372 crate::shell::record_retry_requested(
1373 self.audit_for(request),
1374 self.inner.ledger.as_ref(),
1375 request,
1376 call_id,
1377 &evaluated.decision,
1378 )
1379 .await;
1380 }
1381 evaluated.decision
1382 }
1383
1384 pub(crate) async fn evaluate_full(
1389 &self,
1390 request: &ToolPolicyRequest,
1391 origin: Option<&ToolOrigin>,
1392 call_id: Option<&str>,
1393 governed: bool,
1394 ) -> Evaluated {
1395 let kind = self.classify(request, origin);
1396 let deny = |decision: PolicyDecision, mode: HarnessMode| Evaluated {
1397 rule: None,
1398 decision,
1399 kind,
1400 mode,
1401 base: TableDecision::Deny,
1402 };
1403 if let Some(reason) = self.hard_deny(request, origin, &kind).await {
1404 return deny(PolicyDecision::deny(reason), self.inner.default_mode);
1405 }
1406 let (mode, plan_exited) = self
1407 .mode_and_plan_exit(
1408 &request.app_name,
1409 &request.user_id,
1410 &request.session_id,
1411 &request.invocation_id,
1412 )
1413 .await;
1414 if kind == ToolKind::PlanExit && plan_exited {
1415 return deny(
1418 PolicyDecision::deny(
1419 "the plan was already approved in this turn; the new mode applies from the \
1420 user's next message, so end your turn now",
1421 ),
1422 mode,
1423 );
1424 }
1425 #[cfg(feature = "auth")]
1428 let identity_inert = self.inner.identity.inert(&request.invocation_id);
1429 #[cfg(not(feature = "auth"))]
1430 let identity_inert = false;
1431 let mode =
1432 if identity_inert && mode == HarnessMode::Auto { HarnessMode::Ask } else { mode };
1433 if let Some(reason) = self.inner.registry.denial_in_mode(
1434 &request.agent_name,
1435 &request.tool_name,
1436 origin,
1437 &request.args,
1438 mode,
1439 ) {
1440 return deny(PolicyDecision::deny(reason), mode);
1441 }
1442 let paths = crate::edits::edit_paths(&request.tool_name, &request.args).unwrap_or_default();
1447 let protected_path = paths
1448 .iter()
1449 .find(|path| is_protected_target(self.inner.workspace.root(), path))
1450 .filter(|_| kind == ToolKind::Edit);
1451 let protected = protected_path.is_some();
1452 let row = TableRow::of(&kind, protected);
1453 let mut switches = self.inner.switches;
1454 if matches!(row, TableRow::ShellOsSandbox | TableRow::ShellContainer)
1457 && switches.sandbox_protects_paths
1458 && !(row == TableRow::ShellOsSandbox && self.inner.shell.guards_protected_names)
1459 {
1460 switches.sandbox_protects_paths =
1461 crate::shell::protected_paths_hold(self.inner.workspace.root());
1462 }
1463 let base = decision_cell(mode, row).resolve(&switches);
1464 let mut reason = describe(&request.tool_name, row, mode, base);
1465 if let Some(path) = protected_path {
1466 if is_protected_path(path) {
1467 if paths.len() > 1 {
1468 reason.push_str(&format!(" ({path} is protected)"));
1469 }
1470 } else {
1471 reason
1472 .push_str(&format!(" ({path} resolves through a symlink to a protected path)"));
1473 }
1474 }
1475 if base == TableDecision::Deny {
1476 return deny(PolicyDecision::deny(reason), mode);
1477 }
1478 #[cfg(feature = "hooks")]
1481 if governed && let Some(hooks) = &self.inner.hooks {
1482 let scope = crate::hooks::HookScope::from_request(request, call_id);
1483 let class = crate::hooks::class_label(&kind);
1484 let verdict = hooks
1485 .pre_tool(
1486 &crate::hooks::HookCall {
1487 tool: &request.tool_name,
1488 args: &request.args,
1489 class: &class,
1490 acting: request.acting.as_ref(),
1491 function_call_id: call_id,
1492 },
1493 mode,
1494 &scope,
1495 self.audit_for(request).as_ref(),
1496 )
1497 .await;
1498 if let crate::hooks::PreToolVerdict::Deny { reason: hook_reason } = verdict {
1499 return deny(
1500 PolicyDecision::deny(format!("denied by a hook: {hook_reason}")),
1501 mode,
1502 );
1503 }
1504 }
1505
1506 let mut matched_rules = Vec::new();
1507 let evaluation = if kind.rule_eligible() && !identity_inert {
1508 match self
1509 .inner
1510 .rules
1511 .rules_for(&request.app_name, &request.user_id, &request.session_id)
1512 .await
1513 {
1514 Ok(rules) => {
1515 let call = RuleCall {
1516 app_name: &request.app_name,
1517 user_id: &request.user_id,
1518 session_id: &request.session_id,
1519 acting: request.acting.as_ref(),
1520 tool_name: &request.tool_name,
1521 args: &request.args,
1522 origin,
1523 kind,
1524 workspace_root: self.inner.workspace.root(),
1525 };
1526 let evaluation = evaluate_standing_rules(&rules, &call, Utc::now());
1527 matched_rules = rules;
1528 evaluation
1529 }
1530 Err(error) => {
1531 tracing::warn!(error = %error, "standing rules unavailable; asking instead");
1532 return Evaluated {
1533 rule: None,
1534 decision: PolicyDecision::require_approval(format!(
1535 "{reason}; standing rules are unavailable"
1536 )),
1537 kind,
1538 mode,
1539 base: TableDecision::RequireApproval { non_waivable: true },
1540 };
1541 }
1542 }
1543 } else {
1544 RuleEvaluation::default()
1545 };
1546 if governed {
1547 self.record_rule_observations(request, &evaluation).await;
1548 }
1549
1550 let decision = apply_rule(base, &evaluation.outcome, &reason);
1551 let mut rule_hit = None;
1552 if let (PolicyDecision::Allow, RuleOutcome::Allow { rule_id }) =
1553 (&decision, &evaluation.outcome)
1554 && base != TableDecision::Allow
1555 {
1556 tracing::Span::current().record("harness.rule_id", rule_id.as_str());
1557 if let Some(rule) = matched_rules.iter().find(|rule| rule.id == *rule_id) {
1558 let number = match self.inner.rules.list(&request.app_name, &request.user_id).await
1559 {
1560 Ok(mut all) => {
1561 all.sort_by_key(|rule| rule.created_at);
1562 all.iter().position(|listed| listed.id == rule.id).map(|index| index + 1)
1563 }
1564 Err(_) => None,
1565 };
1566 let mut hit = crate::approvals::RuleHit::new(
1567 rule.id.clone(),
1568 number,
1569 request.tool_name.clone(),
1570 rule.label.clone(),
1571 );
1572 hit.function_call_id = call_id.map(str::to_string);
1573 rule_hit = Some(hit);
1574 }
1575 tracing::info!(
1576 tool.name = %request.tool_name,
1577 harness.rule_id = %rule_id,
1578 harness.mode = %mode,
1579 "tool call allowed by a standing rule"
1580 );
1581 if let (Some(audit), Some(rule)) =
1582 (self.audit_for(request), matched_rules.iter().find(|rule| rule.id == *rule_id))
1583 {
1584 let rule_digest = crate::fsutil::hex_digest(
1585 serde_json::to_string(rule).unwrap_or_default().as_bytes(),
1586 );
1587 let recorded = audit
1588 .record_draft(
1589 adk_core::audit_log::AuditRecordDraft::new(
1590 adk_core::audit_log::AuditRecordKind::Other(
1591 crate::audit::HARNESS_AUDIT_KIND.to_string(),
1592 ),
1593 "harness.rule.matched",
1594 )
1595 .policy_ref(format!("tool_policy:{HARNESS_POLICY_REF}")),
1596 json!({
1597 "ruleId": rule_id,
1598 "ruleDigest": rule_digest,
1599 "tool": request.tool_name,
1600 "toolSource": origin.map(|origin| origin.source.clone()),
1601 "declarationDigest": origin.map(|origin| origin.declaration_digest.clone()),
1602 "functionCallId": call_id,
1603 }),
1604 )
1605 .await;
1606 if let Err(error) = recorded {
1607 tracing::warn!(error = %error, "could not record harness.rule.matched");
1608 return Evaluated {
1609 rule: None,
1610 decision: PolicyDecision::require_approval(format!(
1611 "{reason}; the standing rule's audit record could not be written"
1612 )),
1613 kind,
1614 mode,
1615 base,
1616 };
1617 }
1618 }
1619 }
1620 if governed && !matches!(decision, PolicyDecision::Deny { .. }) {
1624 let subject = request
1625 .acting
1626 .as_ref()
1627 .and_then(|acting| acting.on_behalf_of.as_ref())
1628 .map_or(request.user_id.as_str(), |subject| subject.id.as_str());
1629 let agent = request
1630 .acting
1631 .as_ref()
1632 .map_or(request.agent_name.as_str(), |acting| acting.agent.id.as_str());
1633 self.inner.prompts.insert(
1634 call_id,
1635 call_key(agent, subject, &request.tool_name, &request.args),
1636 PromptContext {
1637 harness_held: matches!(decision, PolicyDecision::RequireApproval { .. }),
1638 peers: self.peers.clone(),
1639 governance: self.governance.clone(),
1640 app_name: request.app_name.clone(),
1641 user_id: request.user_id.clone(),
1642 session_id: request.session_id.clone(),
1643 invocation_id: request.invocation_id.clone(),
1644 agent_name: request.agent_name.clone(),
1645 effect: request.effect,
1646 acting: request.acting.clone(),
1647 audit: self.audit.clone(),
1648 },
1649 );
1650 }
1651 if governed && let (Some(hit), Some(observer)) = (&rule_hit, self.inner.rule_observer.get())
1654 {
1655 observer.rule_applied(hit);
1656 }
1657 Evaluated { decision, kind, mode, base, rule: rule_hit }
1658 }
1659
1660 async fn record_rule_observations(
1661 &self,
1662 request: &ToolPolicyRequest,
1663 evaluation: &RuleEvaluation,
1664 ) {
1665 if evaluation.stale.is_empty() && evaluation.expired.is_empty() {
1666 return;
1667 }
1668 for stale in &evaluation.stale {
1669 tracing::info!(
1670 harness.rule_id = %stale.rule_id,
1671 tool.name = %request.tool_name,
1672 "standing rule is stale: the tool's declaration changed"
1673 );
1674 }
1675 let Some(audit) = self.audit_for(request) else {
1676 return;
1677 };
1678 for stale in &evaluation.stale {
1679 let record = audit
1680 .record(
1681 "harness.rule.stale",
1682 json!({
1683 "ruleId": stale.rule_id,
1684 "subject": request.user_id,
1685 "app": request.app_name,
1686 "tool": request.tool_name,
1687 "source": stale.pinned_source,
1688 "declarationDigest": stale.pinned_digest,
1689 "observedSource": stale.observed_source,
1690 "observedDigest": stale.observed_digest,
1691 }),
1692 )
1693 .await;
1694 if let Err(error) = record {
1695 tracing::warn!(error = %error, "could not record harness.rule.stale");
1696 }
1697 }
1698 for rule_id in &evaluation.expired {
1699 if let Err(error) = audit
1700 .record(
1701 "harness.rule.expired",
1702 json!({ "ruleId": rule_id, "subject": request.user_id, "app": request.app_name, "tool": request.tool_name }),
1703 )
1704 .await
1705 {
1706 tracing::warn!(error = %error, "could not record harness.rule.expired");
1707 }
1708 }
1709 }
1710
1711 pub(crate) fn prompts(&self) -> &PromptContexts {
1712 &self.inner.prompts
1713 }
1714
1715 pub(crate) fn workspace(&self) -> &Workspace {
1716 &self.inner.workspace
1717 }
1718
1719 pub(crate) fn isolation_status(&self) -> &IsolationStatus {
1720 &self.inner.shell.status
1721 }
1722}
1723
1724fn is_provider_shell_builtin(name: &str) -> bool {
1726 name.starts_with("bash_")
1727 || name == "local_shell"
1728 || name == "shell"
1729 || name.starts_with("code_execution")
1730}
1731
1732fn describe(tool: &str, row: TableRow, mode: HarnessMode, base: TableDecision) -> String {
1733 let class = match row {
1734 TableRow::ReadTodoDelegate => "a read",
1735 TableRow::PlanExit => "the plan exit",
1736 TableRow::Edit => "an edit",
1737 TableRow::EditProtected => "an edit of a protected path",
1738 TableRow::ShellOsSandbox => "a sandboxed shell command",
1739 TableRow::ShellContainer => "a container shell command",
1740 TableRow::ShellHost => "a host shell command (full user permissions, network)",
1741 TableRow::ShellEscalation => "an unsandboxed retry",
1742 TableRow::MemoryWrite => "a memory write",
1743 TableRow::MemoryPropose => "a fact proposal",
1744 TableRow::WebAllowlisted => "a web request to an allowlisted host",
1745 TableRow::WebOther => "a web request to a host outside the allowlist",
1746 TableRow::Payment => "a payment",
1747 TableRow::ComputerUse => "a desktop action",
1748 TableRow::ExternalReadOnlyTrusted => "a trusted read-only tool",
1749 TableRow::ExternalOther => "an external tool",
1750 };
1751 match base {
1752 TableDecision::Deny => format!("'{tool}' is {class}, which {mode} mode does not allow"),
1753 TableDecision::RequireApproval { .. } => {
1754 format!("'{tool}' is {class}, which needs approval in {mode} mode")
1755 }
1756 TableDecision::Allow => format!("'{tool}' is {class}, allowed in {mode} mode"),
1757 }
1758}
1759
1760#[async_trait]
1761impl ToolPolicy for HarnessPolicy {
1762 async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
1763 self.evaluate_call(request, &PolicyCall::new()).await
1764 }
1765
1766 async fn evaluate_call(
1767 &self,
1768 request: &ToolPolicyRequest,
1769 call: &PolicyCall<'_>,
1770 ) -> PolicyDecision {
1771 self.decide(request, call.origin, call.function_call_id).await
1772 }
1773
1774 fn policy_ref(&self) -> Option<String> {
1775 Some(HARNESS_POLICY_REF.to_string())
1776 }
1777}
1778
1779pub(crate) struct AutoReview {
1786 inner: Arc<dyn adk_core::ToolReviewer>,
1787 policy: HarnessPolicy,
1788 non_waivable_tools: BTreeSet<String>,
1789 non_waivable_prefixes: Vec<String>,
1790 root: std::path::PathBuf,
1791}
1792
1793impl std::fmt::Debug for AutoReview {
1794 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1795 f.debug_struct("AutoReview").field("inner", &self.inner).finish_non_exhaustive()
1796 }
1797}
1798
1799impl AutoReview {
1800 pub(crate) fn new(
1801 inner: Arc<dyn adk_core::ToolReviewer>,
1802 policy: HarnessPolicy,
1803 non_waivable_tools: BTreeSet<String>,
1804 non_waivable_prefixes: Vec<String>,
1805 root: std::path::PathBuf,
1806 ) -> Self {
1807 Self { inner, policy, non_waivable_tools, non_waivable_prefixes, root }
1808 }
1809}
1810
1811#[async_trait]
1812impl adk_core::ToolReviewer for AutoReview {
1813 fn reviewer(&self) -> adk_core::principal::SubjectRef {
1814 self.inner.reviewer()
1815 }
1816
1817 fn timeout(&self) -> std::time::Duration {
1818 self.inner.timeout()
1819 }
1820
1821 async fn covers(&self, review: &adk_core::ToolReview) -> bool {
1822 if crate::agent::names_non_waivable(
1823 &review.fingerprint,
1824 &self.non_waivable_tools,
1825 &self.non_waivable_prefixes,
1826 &self.root,
1827 ) {
1828 return false;
1829 }
1830 let mut request =
1831 ToolPolicyRequest::new(review.request.tool_name.clone(), review.request.args.clone())
1832 .with_effect(review.effect)
1833 .with_agent_name(review.agent_name.clone())
1834 .with_identity(
1835 review.scope.app_name.clone(),
1836 review.scope.user_id.clone(),
1837 review.scope.session_id.clone(),
1838 )
1839 .with_invocation_id(review.invocation_id.clone());
1840 request.acting = review.request.acting.as_deref().cloned();
1841 let evaluated = self
1843 .policy
1844 .evaluate_full(
1845 &request,
1846 review.request.origin.as_ref(),
1847 review.request.function_call_id.as_deref(),
1848 false,
1849 )
1850 .await;
1851 evaluated.mode == HarnessMode::Auto
1852 && matches!(evaluated.decision, PolicyDecision::RequireApproval { .. })
1853 && !evaluated.base.is_non_waivable()
1854 && self.inner.covers(review).await
1855 }
1856
1857 async fn review(
1858 &self,
1859 review: &adk_core::ToolReview,
1860 ) -> adk_core::Result<adk_core::ReviewVerdict> {
1861 self.inner.review(review).await
1862 }
1863}
1864
1865#[cfg(all(test, feature = "sandbox"))]
1866mod tests {
1867 use std::sync::Arc;
1868
1869 use adk_core::ToolPolicyRequest;
1870 use adk_model::{ScriptedLlm, ScriptedResponse};
1871 use serde_json::json;
1872
1873 use crate::{HarnessAgent, InstructionsConfig, Preset, ShellIsolation};
1874
1875 #[tokio::test]
1879 async fn the_personal_preset_turns_the_unsandboxed_retry_off() {
1880 let dir = tempfile::tempdir().unwrap();
1881 let agent = HarnessAgent::builder("assistant")
1882 .preset(Preset::Personal)
1883 .shell(ShellIsolation::OsSandbox(Default::default()))
1884 .allow_unsandboxed_retry(true)
1885 .model(Arc::new(ScriptedLlm::new("scripted", vec![ScriptedResponse::text("ok")])))
1886 .workspace(adk_devtools::Workspace::new(dir.path()).allow_bash(true))
1887 .project_instructions(InstructionsConfig {
1888 user_file: None,
1889 ..InstructionsConfig::default()
1890 })
1891 .build()
1892 .unwrap();
1893 let retry = ToolPolicyRequest::new(
1894 "bash",
1895 json!({ "command": "ls", "unsandboxed": true, "retry_of": "1", "reason": "denied" }),
1896 );
1897 assert_eq!(
1898 agent.runtime().policy.retry_refusal(&retry).await.as_deref(),
1899 Some("unsandboxed retries are turned off for this harness")
1900 );
1901 }
1902}