1use std::sync::Arc;
17
18use adk_core::{
19 AdkError, ApprovalRisk, ErrorCategory, ErrorComponent, PolicyDecision, Result, SubjectRef,
20 ToolPolicy, ToolPolicyRequest,
21};
22use adk_kernel::agents::{
23 AgentAssessment, AgentCeiling, AgentRecord, AgentUses, FileAccess, MONEY_PACKS, ShellAccess,
24 WebAccess,
25};
26use adk_kernel::{PartitionId, PartitionMode};
27use async_trait::async_trait;
28
29use crate::IsolationStatus;
30use crate::approvals::{
31 RuleOwner, RuleSuggestion, StandingDecision, StandingRule, StandingRuleStore,
32};
33use crate::builder::HarnessAgentBuilder;
34use crate::harness::Harness;
35use crate::mode::HarnessMode;
36
37pub const AGENT_STATE_KEY: &str = "harness:agent";
47
48pub const AGENT_SESSION_CODE: &str = "harness.agent_session";
57
58pub const PROPOSE_AGENT: &str = "propose_agent";
66
67pub const PRIMARY_AGENT_STAMP: &str = "adk-rust";
75
76fn money_pack(pack: &str) -> bool {
78 MONEY_PACKS.contains(&pack)
79}
80
81#[cfg(feature = "web")]
83fn looseness(mode: PartitionMode) -> u8 {
84 match mode {
85 PartitionMode::ReadOnly => 0,
86 PartitionMode::Plan => 1,
87 PartitionMode::Ask => 2,
88 _ => 3,
89 }
90}
91
92pub(crate) fn partition_mode(mode: HarnessMode) -> PartitionMode {
94 match mode {
95 HarnessMode::ReadOnly => PartitionMode::ReadOnly,
96 HarnessMode::Plan => PartitionMode::Plan,
97 HarnessMode::Ask => PartitionMode::Ask,
98 HarnessMode::Auto => PartitionMode::Auto,
99 }
100}
101
102fn place(folder: Option<&str>) -> String {
104 folder.map_or_else(|| "the workspace".to_string(), str::to_string)
105}
106
107pub fn assess_agent(record: &AgentRecord) -> AgentAssessment {
139 let uses = &record.uses;
140 let mut risk = match record.mode {
141 PartitionMode::ReadOnly | PartitionMode::Plan => ApprovalRisk::Low,
142 PartitionMode::Ask => ApprovalRisk::Medium,
143 _ => ApprovalRisk::High,
144 };
145 let mut abilities = vec![
146 match record.mode {
147 PartitionMode::ReadOnly => "It only looks: it changes nothing.",
148 PartitionMode::Plan => "It suggests what to do and changes nothing until you say yes.",
149 PartitionMode::Ask => "It asks you first before it changes anything.",
150 _ => "It goes ahead without asking, except for what always asks first.",
151 }
152 .to_string(),
153 ];
154 let folder = place(uses.folder.as_deref());
155 match uses.files {
156 FileAccess::None => abilities.push("It can't use your files.".to_string()),
157 FileAccess::Read => abilities.push(format!("It can read files in {folder}.")),
158 FileAccess::ReadWrite => {
159 risk = risk.max(ApprovalRisk::Medium);
160 abilities.push(format!("It can read and change files in {folder}."));
161 }
162 }
163 match uses.shell {
164 ShellAccess::None => abilities.push("It has no shell.".to_string()),
165 ShellAccess::Sandboxed => {
166 risk = risk.max(ApprovalRisk::Medium);
167 abilities.push("It can run commands in the sandbox.".to_string());
168 }
169 ShellAccess::Host => {
170 risk = risk.max(ApprovalRisk::High);
171 abilities.push("It can run commands on this computer.".to_string());
172 }
173 }
174 match &uses.web {
175 WebAccess::None => abilities.push("It can't use the web.".to_string()),
176 WebAccess::Listed { hosts } => {
177 abilities.push(format!("It can use these sites only: {}.", hosts.join(", ")));
178 }
179 WebAccess::Any => {
180 risk = risk.max(ApprovalRisk::Medium);
181 abilities.push("It can use any site.".to_string());
182 }
183 }
184 let mut money = false;
185 for pack in &uses.packs {
186 if money_pack(pack) {
187 money = true;
188 }
189 abilities.push(match pack.as_str() {
190 "payments" => "It can spend money with the payments pack.".to_string(),
191 "computer-use" | "computer_use" => {
192 "It can use this computer's screen, keyboard and mouse.".to_string()
193 }
194 other => format!("It can use the {other} pack."),
195 });
196 }
197 for driver in &uses.drivers {
198 abilities.push(format!("It can use the {driver} driver."));
199 }
200 if let Some(limit) = record.daily_limit_micro_usd {
201 abilities.push(format!("It spends at most ${:.2} a day.", limit as f64 / 1_000_000.0));
202 }
203 if let adk_kernel::agents::AgentOrigin::Suggested { unattended: true, .. } = &record.origin {
204 risk = ApprovalRisk::High;
205 }
206 let mut assessment = AgentAssessment::new(risk);
207 if money {
208 assessment = assessment.with_money();
209 }
210 for ability in abilities {
211 assessment = assessment.with_ability(ability);
212 }
213 assessment
214}
215
216pub fn suggester_ceiling<'a>(
252 tools: impl IntoIterator<Item = &'a str>,
253 packs: &[String],
254 shell: Option<&IsolationStatus>,
255 mode: HarnessMode,
256 drivers: &[String],
257) -> AgentCeiling {
258 let tools: Vec<&str> = tools.into_iter().collect();
259 let has = |name: &str| tools.contains(&name);
260 let files = if has("write_file") || has("edit_file") {
261 FileAccess::ReadWrite
262 } else if has("read_file") {
263 FileAccess::Read
264 } else {
265 FileAccess::None
266 };
267 let shell = match shell {
268 None => ShellAccess::None,
269 Some(
270 IsolationStatus::OsSandbox { .. }
271 | IsolationStatus::Container { .. }
272 | IsolationStatus::Remote { off_host: true, .. },
273 ) => ShellAccess::Sandboxed,
274 Some(_) => ShellAccess::Host,
275 };
276 let web = if has("web_fetch") || has("web_search") { WebAccess::Any } else { WebAccess::None };
277 let mut uses = AgentUses::default().with_files(files).with_shell(shell).with_web(web);
278 for pack in packs {
279 uses = uses.with_pack(pack.clone());
280 }
281 for driver in drivers {
282 uses = uses.with_driver(driver.clone());
283 }
284 AgentCeiling::new(partition_mode(mode), uses.normalized())
285}
286
287impl Harness {
288 pub async fn agent_ceiling(&self, user: &str, session: &str) -> Result<AgentCeiling> {
303 let agent = self.agent();
304 let info = agent.info();
305 let mode = match agent.runtime().mode_store.get(self.app_name(), user, session).await? {
306 Some(record) => record.mode,
307 None => info.default_mode,
308 };
309 let drivers = agent.partition().map(|area| area.drivers.clone()).unwrap_or_default();
310 Ok(suggester_ceiling(
311 info.tools.iter().map(String::as_str),
312 &info.packs,
313 info.shell(),
314 mode,
315 &drivers,
316 ))
317 }
318
319 pub fn agent_area(&self) -> PartitionId {
321 self.agent().partition().map(|area| area.id.clone()).unwrap_or_default()
322 }
323
324 pub fn hosted_agent(&self) -> adk_kernel::agents::HostedAgent {
335 let (_, runner) = self.goal_target();
336 adk_kernel::agents::HostedAgent::new(runner).with_progress(self.kernel_progress())
337 }
338}
339
340#[async_trait]
344impl adk_kernel::agents::HostedClose for Harness {
345 async fn close(&self) {
346 Harness::close(self).await;
347 }
348}
349
350#[cfg(feature = "web")]
373pub async fn screen_agent_definition(
374 mut definition: adk_kernel::agents::AgentDefinition,
375) -> adk_kernel::agents::AgentDefinition {
376 let label = crate::web::INJECTION_LABEL;
377 let doubled = format!("{label} {label} ");
378 let once = format!("{label} ");
379 let screened = crate::web::screen(&definition.instructions).await.text;
380 definition.instructions = screened
381 .split('\n')
382 .map(|line| {
383 let mut line = line.to_string();
384 while line.starts_with(&doubled) {
385 line = line.replacen(&doubled, &once, 1);
386 }
387 line
388 })
389 .collect::<Vec<_>>()
390 .join("\n");
391 definition.description = crate::web::redact_secrets(&definition.description).0;
392 definition
393}
394
395impl HarnessAgentBuilder {
396 #[must_use]
412 pub fn hosted_beside(self, primary: &Harness) -> Self {
413 let runtime = primary.agent().runtime();
414 let builder = self.agenda_handle(runtime.kernel_agenda.clone());
415 match runtime.approval_service() {
416 Some(service) => builder.approval_service(service.clone()),
417 None => builder,
418 }
419 }
420}
421
422#[derive(Debug, Clone, PartialEq, Eq)]
453#[non_exhaustive]
454pub struct AddedAgent {
455 pub id: String,
457 pub description: String,
459 pub instructions: String,
461 pub mode: PartitionMode,
463 pub uses: AgentUses,
465}
466
467impl AddedAgent {
468 pub fn from_record(record: &AgentRecord) -> Self {
470 Self {
471 id: record.id.clone(),
472 description: record.description.clone(),
473 instructions: record.instructions.clone(),
474 mode: record.mode,
475 uses: record.uses.clone().normalized(),
476 }
477 }
478
479 pub fn mode_in(&self, area: HarnessMode) -> HarnessMode {
494 let own = HarnessMode::from(self.mode);
495 if own.strictness() > area.strictness() { own } else { area }
496 }
497
498 pub fn deny_layer(&self) -> Option<Arc<dyn ToolPolicy>> {
501 let layer = UsesPolicy::new(&self.id, &self.uses);
502 (!layer.is_empty()).then(|| Arc::new(layer) as Arc<dyn ToolPolicy>)
503 }
504}
505
506const READ_TOOLS: &[&str] = &["read_file", "list_dir", "glob", "grep", "file_info"];
508const WRITE_TOOLS: &[&str] =
510 &["write_file", "edit_file", "multi_edit", "apply_patch", "delete_file", "move_file"];
511
512#[derive(Debug, Clone, PartialEq, Eq)]
515struct UsesPolicy {
516 agent: String,
517 denied: Vec<&'static str>,
518 sites: Option<Vec<String>>,
519}
520
521impl UsesPolicy {
522 fn new(agent: &str, uses: &AgentUses) -> Self {
523 let mut denied: Vec<&'static str> = Vec::new();
524 match uses.files {
525 FileAccess::None => {
526 denied.extend(READ_TOOLS);
527 denied.extend(WRITE_TOOLS);
528 }
529 FileAccess::Read => denied.extend(WRITE_TOOLS),
530 FileAccess::ReadWrite => {}
531 }
532 if uses.shell == ShellAccess::None {
533 denied.push("bash");
534 }
535 let sites = match &uses.web {
536 WebAccess::None => {
537 denied.extend(["web_fetch", "web_search"]);
538 None
539 }
540 WebAccess::Listed { hosts } => {
541 denied.push("web_search");
542 Some(hosts.clone())
543 }
544 WebAccess::Any => None,
545 };
546 Self { agent: agent.to_string(), denied, sites }
547 }
548
549 fn is_empty(&self) -> bool {
550 self.denied.is_empty() && self.sites.is_none()
551 }
552}
553
554fn host_of(url: &str) -> Option<String> {
556 let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
557 let authority = rest.split(['/', '?', '#']).next()?;
558 let host = authority.rsplit_once('@').map_or(authority, |(_, host)| host);
559 let host = host.split(':').next()?.trim_end_matches('.').to_ascii_lowercase();
560 (!host.is_empty()).then_some(host)
561}
562
563#[async_trait]
564impl ToolPolicy for UsesPolicy {
565 async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
566 if self.denied.contains(&request.tool_name.as_str()) {
567 return PolicyDecision::deny(format!(
568 "{} may not use {}: a person set what it can use in its settings (spec 3.3 §5.7)",
569 self.agent, request.tool_name
570 ));
571 }
572 if let Some(sites) = &self.sites
573 && request.tool_name == "web_fetch"
574 {
575 let host =
576 request.args.get("url").and_then(serde_json::Value::as_str).and_then(host_of);
577 let listed = host.as_deref().is_some_and(|host| {
578 sites.iter().any(|site| {
579 let site = site.to_ascii_lowercase();
580 host == site || host.ends_with(&format!(".{site}"))
581 })
582 });
583 if !listed {
584 return PolicyDecision::deny(format!(
585 "{} may use only these sites: {} (spec 3.3 §5.7)",
586 self.agent,
587 sites.join(", ")
588 ));
589 }
590 }
591 PolicyDecision::Allow
592 }
593}
594
595impl HarnessAgentBuilder {
596 #[must_use]
612 pub fn added_agent(self, record: &AgentRecord) -> Self {
613 let added = AddedAgent::from_record(record);
614 let builder = match added.deny_layer() {
615 Some(layer) => self.add_operator_policy(layer),
616 None => self,
617 };
618 let builder = match added.uses.shell {
619 ShellAccess::None => builder.without_shell(),
620 _ => builder,
621 };
622 builder.lower_added(added)
623 }
624}
625
626pub(crate) fn check_stamp(
634 stamp: &str,
635 stamped: Option<&serde_json::Value>,
636 session: &str,
637) -> Result<bool> {
638 match stamped {
639 Some(owner) if owner.as_str() == Some(stamp) => Ok(false),
640 Some(owner) => Err(AdkError::new(
641 ErrorComponent::Agent,
642 ErrorCategory::Forbidden,
643 AGENT_SESSION_CODE,
644 format!(
645 "session '{session}' is {}'s thread; {stamp} cannot continue it (spec 3.3 §5.7); \
646 start a new thread with {stamp}",
647 owner.as_str().unwrap_or("another agent")
648 ),
649 )),
650 None => Ok(true),
651 }
652}
653
654pub(crate) fn stamp_event(
661 ctx: &dyn adk_core::InvocationContext,
662 stamp: &str,
663 author: &str,
664) -> Result<Option<adk_core::Event>> {
665 let stamped = ctx.session().state().get(AGENT_STATE_KEY);
666 if !check_stamp(stamp, stamped.as_ref(), ctx.session_id())? {
667 return Ok(None);
668 }
669 let mut event = adk_core::Event::new(ctx.invocation_id());
670 event.author = author.to_string();
671 event.branch = ctx.branch().to_string();
672 event.actions.state_delta.insert(AGENT_STATE_KEY.to_string(), serde_json::json!(stamp));
673 Ok(Some(event))
674}
675
676fn acting_id(app: &str, root: &str) -> String {
678 adk_core::AgentPrincipal::derived(app, root).id.as_str().to_string()
679}
680
681#[derive(Debug, Clone)]
698pub struct PinnedOnlyRules {
699 inner: Arc<dyn StandingRuleStore>,
700 root: String,
701}
702
703impl PinnedOnlyRules {
704 pub fn new(inner: Arc<dyn StandingRuleStore>, root: impl Into<String>) -> Self {
706 Self { inner, root: root.into() }
707 }
708
709 fn pinned(&self, app: &str, rule: &StandingRule) -> bool {
710 rule.agent.as_deref() == Some(acting_id(app, &self.root).as_str())
711 }
712}
713
714#[async_trait]
715impl StandingRuleStore for PinnedOnlyRules {
716 async fn rules_for(&self, app: &str, user: &str, session: &str) -> Result<Vec<StandingRule>> {
717 let rules = self.inner.rules_for(app, user, session).await?;
718 Ok(rules.into_iter().filter(|rule| self.pinned(app, rule)).collect())
719 }
720
721 async fn grant(&self, mut rule: StandingRule) -> Result<StandingRule> {
722 rule.agent = Some(acting_id(rule.scope.app_name(), &self.root));
723 self.inner.grant(rule).await
724 }
725
726 async fn revoke(&self, app: &str, id: &str) -> Result<bool> {
727 let pinned = self
728 .inner
729 .list(app, "")
730 .await
731 .map(|rules| rules.iter().any(|rule| rule.id == id && self.pinned(app, rule)))
732 .unwrap_or(true);
733 if !pinned {
734 return Ok(false);
735 }
736 self.inner.revoke(app, id).await
737 }
738
739 async fn list(&self, app: &str, user: &str) -> Result<Vec<StandingRule>> {
740 let rules = self.inner.list(app, user).await?;
741 Ok(rules.into_iter().filter(|rule| self.pinned(app, rule)).collect())
742 }
743
744 async fn replace(&self, mut rule: StandingRule) -> Result<bool> {
745 let app = rule.scope.app_name().to_string();
746 let held = self.list(&app, rule.scope.user_id()).await?;
747 if !held.iter().any(|existing| existing.id == rule.id) {
748 return Ok(false);
749 }
750 rule.agent = Some(acting_id(&app, &self.root));
751 self.inner.replace(rule).await
752 }
753}
754
755impl RuleSuggestion {
756 pub fn into_pinned_rule(
783 self,
784 owner: &RuleOwner,
785 decision: StandingDecision,
786 source_fingerprint: Option<String>,
787 agent: &str,
788 ) -> StandingRule {
789 let mut rule = self.into_rule(owner, decision, source_fingerprint);
790 rule.agent = Some(agent.to_string());
791 rule
792 }
793}
794
795pub fn copy_rule_to(rule: &StandingRule, agent: &str, by: SubjectRef) -> Result<StandingRule> {
830 if by.kind != adk_core::principal::SubjectKind::Human {
831 return Err(AdkError::new(
832 ErrorComponent::Agent,
833 ErrorCategory::Forbidden,
834 "harness.rule.not_a_person",
835 "only a person copies a rule to an agent (spec 3.1 I2)",
836 ));
837 }
838 let mut copy = rule.clone();
839 copy.id = uuid::Uuid::new_v4().to_string();
840 copy.agent = Some(agent.to_string());
841 copy.created_by = by;
842 copy.created_at = chrono::Utc::now();
843 Ok(copy)
844}
845
846#[cfg(feature = "web")]
849pub(crate) fn over_limits(
850 definition: &adk_kernel::agents::AgentDefinition,
851 ceiling: &AgentCeiling,
852 area: &PartitionId,
853) -> Vec<String> {
854 let mut over = adk_kernel::agents::over_ceiling(definition, ceiling);
855 if &definition.area != area {
856 over.push(format!("another area ({})", definition.area));
857 }
858 if looseness(definition.mode) > looseness(ceiling.mode) && over.is_empty() {
859 over.push("a looser mode".to_string());
860 }
861 over
862}
863
864#[cfg(feature = "web")]
865pub(crate) use propose::{ProposeAgentTool, SuggestAgent};
866
867#[cfg(feature = "web")]
868mod propose {
869 use std::sync::{Arc, OnceLock};
870
871 use adk_core::{
872 AdkError, AgentId, ErrorCategory, ErrorComponent, Result, Tool, ToolContext, ToolEffect,
873 };
874 use adk_kernel::agents::{AgentCeiling, AgentDefinition, AgentUses, AvatarColor, ModelChoice};
875 use adk_kernel::{PartitionId, PartitionMode};
876 use async_trait::async_trait;
877 use serde_json::{Value, json};
878
879 use super::{PROPOSE_AGENT, over_limits, partition_mode};
880 use crate::mode::{HarnessMode, ModeStore};
881 use crate::policy::has_harness_layer;
882
883 #[async_trait]
885 pub(crate) trait SuggestAgent: Send + Sync {
886 async fn propose(
889 &self,
890 definition: AgentDefinition,
891 proposer: AgentId,
892 ceiling: AgentCeiling,
893 user: &str,
894 session: &str,
895 run: Option<String>,
896 ) -> Result<Option<Value>>;
897 }
898
899 #[async_trait]
900 impl SuggestAgent for adk_kernel::agents::AgentsHandle {
901 async fn propose(
902 &self,
903 definition: AgentDefinition,
904 proposer: AgentId,
905 ceiling: AgentCeiling,
906 user: &str,
907 session: &str,
908 run: Option<String>,
909 ) -> Result<Option<Value>> {
910 let Some(agents) = self.get() else {
911 return Ok(None);
912 };
913 let mut who = adk_kernel::agents::AgentProposer::new(proposer, user, session)
916 .with_ceiling(ceiling);
917 if let Some(run) = run {
918 who = who.with_run(run);
919 }
920 match agents.propose(definition, &who).await {
921 Ok(proposal) => Ok(Some(json!({
922 "risk": proposal.risk,
923 "merged": proposal.merged,
924 }))),
925 Err(error) => Ok(Some(json!({ "refused": error.to_string() }))),
927 }
928 }
929 }
930
931 pub(crate) struct ProposeAgentTool {
937 proposer: Arc<dyn SuggestAgent>,
938 modes: (Arc<dyn ModeStore>, HarnessMode),
939 limits: Arc<OnceLock<AgentUses>>,
941 area: PartitionId,
942 }
943
944 impl ProposeAgentTool {
945 pub(crate) fn new(
946 proposer: Arc<dyn SuggestAgent>,
947 mode_store: Arc<dyn ModeStore>,
948 default_mode: HarnessMode,
949 limits: Arc<OnceLock<AgentUses>>,
950 area: PartitionId,
951 ) -> Self {
952 Self { proposer, modes: (mode_store, default_mode), limits, area }
953 }
954
955 async fn mode(&self, ctx: &dyn ToolContext) -> HarnessMode {
956 let (store, default_mode) = &self.modes;
957 match store.get(ctx.app_name(), ctx.user_id(), ctx.session_id()).await {
958 Ok(Some(record)) => record.mode_for_invocation(ctx.invocation_id()),
959 Ok(None) => *default_mode,
960 Err(error) => {
961 tracing::warn!(error = %error, "mode store unavailable; the suggestion is limited to Just look");
962 HarnessMode::ReadOnly
963 }
964 }
965 }
966 }
967
968 fn invalid(message: impl Into<String>) -> AdkError {
969 AdkError::new(
970 ErrorComponent::Tool,
971 ErrorCategory::InvalidInput,
972 "harness.agent.invalid",
973 message,
974 )
975 }
976
977 fn mode_of(value: &str) -> Option<PartitionMode> {
979 match value.trim().to_ascii_lowercase().replace(['-', '_', ' '], "").as_str() {
980 "justlook" | "readonly" => Some(PartitionMode::ReadOnly),
981 "suggest" | "plan" => Some(PartitionMode::Plan),
982 "askfirst" | "ask" => Some(PartitionMode::Ask),
983 "goahead" | "auto" => Some(PartitionMode::Auto),
984 _ => None,
985 }
986 }
987
988 #[async_trait]
989 impl Tool for ProposeAgentTool {
990 fn name(&self) -> &str {
991 PROPOSE_AGENT
992 }
993
994 fn description(&self) -> &str {
995 "Suggest a new agent for the person: a name, what it does in one line, and its \
996 instructions; optionally how much it asks first (justLook, suggest, askFirst, \
997 goAhead), what it can use, and the model it runs on. The suggestion waits in the \
998 person's Decisions; only the person adds it. It can do no more than you can, in \
999 your area: never a shell on this computer, payments, computer use or team \
1000 members. Suggesting does nothing else."
1001 }
1002
1003 fn parameters_schema(&self) -> Option<Value> {
1004 Some(json!({
1005 "type": "object",
1006 "properties": {
1007 "name": { "type": "string", "description": "Its name, such as Finance: at most 40 characters." },
1008 "whatItDoes": { "type": "string", "description": "What it does, in one line." },
1009 "instructions": { "type": "string", "description": "How it works: its instructions." },
1010 "mode": { "type": "string", "enum": ["justLook", "suggest", "askFirst", "goAhead"], "description": "How much it asks first; at most your own mode. Default: yours." },
1011 "uses": {
1012 "type": "object",
1013 "description": "What it can use; at most what you can. Default: nothing.",
1014 "properties": {
1015 "files": { "type": "string", "enum": ["none", "read", "readWrite"] },
1016 "folder": { "type": "string", "description": "One folder inside the workspace, relative to it." },
1017 "shell": { "type": "string", "enum": ["none", "sandboxed"] },
1018 "web": {
1019 "type": "object",
1020 "description": "{\"access\": \"none\"}, {\"access\": \"listed\", \"hosts\": [\"example.com\"]} or {\"access\": \"any\"}."
1021 },
1022 "packs": { "type": "array", "items": { "type": "string" } },
1023 "drivers": { "type": "array", "items": { "type": "string" } }
1024 }
1025 },
1026 "model": {
1027 "type": "object",
1028 "description": "The model it runs on; default: yours.",
1029 "properties": { "provider": { "type": "string" }, "model": { "type": "string" } },
1030 "required": ["provider", "model"]
1031 }
1032 },
1033 "required": ["name", "whatItDoes", "instructions"]
1034 }))
1035 }
1036
1037 fn effect(&self) -> ToolEffect {
1038 ToolEffect::NonIdempotent
1041 }
1042
1043 async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
1044 let config = ctx
1045 .run_config()
1046 .ok_or_else(|| AdkError::tool("propose_agent runs only inside a harness run"))?;
1047 if !config.tool_policy.as_deref().is_some_and(has_harness_layer) {
1048 return Err(AdkError::tool(
1049 "propose_agent refuses to run without the harness policy in the run config",
1050 ));
1051 }
1052 let text = |field: &str| -> Result<String> {
1053 args.get(field)
1054 .and_then(Value::as_str)
1055 .map(str::trim)
1056 .filter(|value| !value.is_empty())
1057 .map(str::to_string)
1058 .ok_or_else(|| invalid(format!("propose_agent needs a non-empty '{field}'")))
1059 };
1060 let name = text("name")?;
1061 let does = text("whatItDoes")?;
1062 let instructions = text("instructions")?;
1063 let own_mode = self.mode(ctx.as_ref()).await;
1064 let mode = match args.get("mode") {
1065 None | Some(Value::Null) => partition_mode(own_mode),
1066 Some(value) => value.as_str().and_then(mode_of).ok_or_else(|| {
1067 invalid("'mode' is one of justLook, suggest, askFirst or goAhead")
1068 })?,
1069 };
1070 let uses: AgentUses = match args.get("uses") {
1071 None | Some(Value::Null) => AgentUses::default(),
1072 Some(value) => serde_json::from_value(value.clone()).map_err(|error| {
1073 invalid(format!("'uses' is not what an agent can use: {error}"))
1074 })?,
1075 };
1076 let model: Option<ModelChoice> = match args.get("model") {
1077 None | Some(Value::Null) => None,
1078 Some(value) => Some(
1079 serde_json::from_value(value.clone())
1080 .map_err(|error| invalid(format!("'model' is not a model: {error}")))?,
1081 ),
1082 };
1083 let mut definition = AgentDefinition::new(name.clone(), self.area.clone())
1086 .with_color(AvatarColor::for_name(&name))
1087 .with_description(does)
1088 .with_instructions(instructions)
1089 .with_mode(mode)
1090 .with_uses(uses);
1091 if let Some(model) = model {
1092 definition = definition.with_model(model);
1093 }
1094 let definition = super::screen_agent_definition(definition.normalized()).await;
1095 let uses = self.limits.get().cloned().unwrap_or_default();
1096 let ceiling = AgentCeiling::new(partition_mode(own_mode), uses);
1097 let over = over_limits(&definition, &ceiling, &self.area);
1098 let proposer = ctx.acting_context().agent.id;
1099 let run = config.durable_run_id.clone();
1100 match self
1105 .proposer
1106 .propose(definition, proposer, ceiling, ctx.user_id(), ctx.session_id(), run)
1107 .await?
1108 {
1109 None => Ok(json!({
1110 "error": "no agent kernel hosts this harness, so no agent can be suggested; \
1111 the person can start one with `adk-rust up`"
1112 })),
1113 Some(outcome) if outcome.get("refused").is_some() && !over.is_empty() => {
1114 Ok(json!({
1115 "error": format!(
1116 "Not suggested: {name} would have {}, which is more than you can \
1117 give it. Suggest it without those, or the person can set it up \
1118 themselves.",
1119 join(&over)
1120 ),
1121 }))
1122 }
1123 Some(outcome) if outcome.get("refused").is_some() => Ok(json!({
1124 "error": format!(
1125 "Not suggested: {}",
1126 outcome["refused"].as_str().unwrap_or_default()
1127 ),
1128 })),
1129 Some(outcome) => Ok(json!({
1130 "state": "suggested",
1131 "note": "Suggested; waiting for the person. Nothing is added until they say yes.",
1132 "outcome": outcome,
1133 })),
1134 }
1135 }
1136 }
1137
1138 fn join(items: &[String]) -> String {
1139 match items {
1140 [] => String::new(),
1141 [one] => one.clone(),
1142 [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
1143 }
1144 }
1145}
1146
1147#[cfg(test)]
1148mod tests {
1149 use adk_core::principal::SubjectKind;
1150 use adk_core::{AgentId, ToolOrigin};
1151 use adk_kernel::agents::{AgentDefinition, AgentOrigin, AgentRecordState};
1152 use serde_json::json;
1153
1154 use super::*;
1155 use crate::approvals::{InMemoryStandingRuleStore, OriginPin, RuleScope};
1156
1157 fn record(mode: PartitionMode, uses: AgentUses) -> AgentRecord {
1158 AgentRecord::new(
1159 "finance",
1160 AgentDefinition::new("Finance", "default").with_mode(mode).with_uses(uses),
1161 AgentRecordState::Active,
1162 AgentOrigin::ByHand,
1163 SubjectRef::human("ana"),
1164 chrono::Utc::now(),
1165 )
1166 }
1167
1168 fn risk(mode: PartitionMode, uses: AgentUses) -> (ApprovalRisk, bool) {
1169 let assessment = assess_agent(&record(mode, uses));
1170 (assessment.risk, assessment.money)
1171 }
1172
1173 #[test]
1174 fn every_row_of_the_risk_table() {
1175 use ApprovalRisk::{High, Low, Medium};
1176 let none = AgentUses::default;
1177 assert_eq!(risk(PartitionMode::ReadOnly, none()), (Low, false));
1179 assert_eq!(
1180 risk(
1181 PartitionMode::Plan,
1182 none().with_files(FileAccess::Read).with_web(WebAccess::listed(["a.io"]))
1183 ),
1184 (Low, false)
1185 );
1186 assert_eq!(risk(PartitionMode::Ask, none()), (Medium, false));
1188 assert_eq!(
1189 risk(PartitionMode::Plan, none().with_files(FileAccess::ReadWrite)),
1190 (Medium, false)
1191 );
1192 assert_eq!(
1193 risk(PartitionMode::Plan, none().with_shell(ShellAccess::Sandboxed)),
1194 (Medium, false)
1195 );
1196 assert_eq!(risk(PartitionMode::Plan, none().with_web(WebAccess::Any)), (Medium, false));
1197 assert_eq!(risk(PartitionMode::Auto, none()), (High, false));
1199 assert_eq!(
1200 risk(PartitionMode::ReadOnly, none().with_shell(ShellAccess::Host)),
1201 (High, false)
1202 );
1203 assert_eq!(risk(PartitionMode::ReadOnly, none().with_pack("payments")), (High, true));
1205 assert_eq!(risk(PartitionMode::ReadOnly, none().with_pack("computer-use")), (High, true));
1206 assert_eq!(risk(PartitionMode::ReadOnly, none().with_pack("browser")), (Low, false));
1208 }
1209
1210 #[test]
1211 fn a_suggestion_from_unattended_work_is_high_risk() {
1212 let mut unattended = record(PartitionMode::ReadOnly, AgentUses::default());
1213 unattended.origin = AgentOrigin::Suggested {
1214 agent: AgentId::new("urn:adk:agent:adk-rust/adk-rust").unwrap(),
1215 session: "s1".into(),
1216 run: None,
1217 unattended: true,
1218 };
1219 assert_eq!(assess_agent(&unattended).risk, ApprovalRisk::High);
1220 }
1221
1222 #[test]
1223 fn abilities_are_plain_sentences_in_definition_order() {
1224 let assessment = assess_agent(&record(
1225 PartitionMode::Ask,
1226 AgentUses::default()
1227 .with_files(FileAccess::Read)
1228 .with_folder("Invoices")
1229 .with_web(WebAccess::listed(["bank.example"])),
1230 ));
1231 assert_eq!(
1232 assessment.abilities,
1233 [
1234 "It asks you first before it changes anything.",
1235 "It can read files in Invoices.",
1236 "It has no shell.",
1237 "It can use these sites only: bank.example.",
1238 ]
1239 );
1240 }
1241
1242 #[test]
1243 fn the_ceiling_follows_the_suggesters_tools_shell_and_mode() {
1244 let host = suggester_ceiling(
1245 ["read_file", "bash", "web_fetch"],
1246 &["payments".to_string()],
1247 Some(&IsolationStatus::Host),
1248 HarnessMode::Plan,
1249 &["calendar".to_string()],
1250 );
1251 assert_eq!(host.mode, PartitionMode::Plan);
1252 assert_eq!(host.uses.files, FileAccess::Read);
1253 assert_eq!(host.uses.shell, ShellAccess::Host);
1254 assert_eq!(host.uses.web, WebAccess::Any);
1255 assert_eq!(host.uses.packs, ["payments"]);
1256 assert_eq!(host.uses.drivers, ["calendar"]);
1257 let bare = suggester_ceiling([] as [&str; 0], &[], None, HarnessMode::ReadOnly, &[]);
1258 assert_eq!(bare.uses, AgentUses::default());
1259 }
1260
1261 #[cfg(feature = "web")]
1262 fn ceiling() -> AgentCeiling {
1263 suggester_ceiling(
1264 ["read_file", "write_file", "bash", "web_fetch"],
1265 &["payments".to_string(), "browser".to_string()],
1266 Some(&IsolationStatus::Host),
1267 HarnessMode::Ask,
1268 &["calendar".to_string()],
1269 )
1270 }
1271
1272 #[cfg(feature = "web")]
1273 fn over(definition: AgentDefinition) -> Vec<String> {
1274 over_limits(&definition, &ceiling(), &PartitionId::default())
1275 }
1276
1277 #[cfg(feature = "web")]
1278 #[test]
1279 fn a_suggestion_over_the_ceiling_names_each_dimension() {
1280 let base = || AgentDefinition::new("Finance", "default").with_mode(PartitionMode::Ask);
1281 assert!(over(base()).is_empty());
1282 assert!(!over(base().with_mode(PartitionMode::Auto)).is_empty(), "a looser mode");
1283 assert!(
1284 over(base().with_uses(AgentUses::default().with_shell(ShellAccess::Host)))
1285 .contains(&"a shell on this computer".to_string())
1286 );
1287 assert!(
1288 over(base().with_uses(AgentUses::default().with_pack("payments")))
1289 .contains(&"the payments pack".to_string())
1290 );
1291 assert!(
1292 over(base().with_uses(AgentUses::default().with_pack("computer-use")))
1293 .contains(&"the computer-use pack".to_string())
1294 );
1295 assert!(
1296 over(base().with_uses(AgentUses::default().with_pack("voice")))
1297 .contains(&"the voice pack".to_string())
1298 );
1299 assert!(
1300 over(base().with_uses(AgentUses::default().with_driver("mail")))
1301 .contains(&"the mail driver".to_string())
1302 );
1303 assert!(
1304 over(AgentDefinition::new("Finance", "work").with_mode(PartitionMode::Ask))
1305 .contains(&"another area (work)".to_string())
1306 );
1307 let narrowed = AgentCeiling::new(
1309 PartitionMode::Ask,
1310 AgentUses::default().with_files(FileAccess::Read).with_folder("Docs"),
1311 );
1312 let wider =
1313 base().with_uses(AgentUses::default().with_files(FileAccess::Read).with_folder("Mail"));
1314 assert_eq!(over_limits(&wider, &narrowed, &PartitionId::default()), ["the folder Mail"]);
1315 let listed = AgentCeiling::new(
1317 PartitionMode::Ask,
1318 AgentUses::default().with_web(WebAccess::listed(["docs.rs"])),
1319 );
1320 let other =
1321 base().with_uses(AgentUses::default().with_web(WebAccess::listed(["evil.example"])));
1322 assert_eq!(
1323 over_limits(&other, &listed, &PartitionId::default()),
1324 ["the sites evil.example"]
1325 );
1326 }
1327
1328 #[test]
1329 fn an_added_agent_runs_in_the_stricter_mode() {
1330 let added = AddedAgent::from_record(&record(PartitionMode::Plan, AgentUses::default()));
1331 assert_eq!(added.mode_in(HarnessMode::Auto), HarnessMode::Plan);
1332 assert_eq!(added.mode_in(HarnessMode::ReadOnly), HarnessMode::ReadOnly);
1333 }
1334
1335 async fn decide(policy: &Arc<dyn ToolPolicy>, tool: &str, args: serde_json::Value) -> bool {
1336 matches!(policy.evaluate(&ToolPolicyRequest::new(tool, args)).await, PolicyDecision::Allow)
1337 }
1338
1339 #[tokio::test]
1340 async fn the_deny_layer_takes_away_what_the_record_does_not_give() {
1341 let reader = AddedAgent::from_record(&record(
1342 PartitionMode::Ask,
1343 AgentUses::default()
1344 .with_files(FileAccess::Read)
1345 .with_web(WebAccess::listed(["bank.example"])),
1346 ));
1347 let policy = reader.deny_layer().unwrap();
1348 assert!(decide(&policy, "read_file", json!({})).await);
1349 assert!(!decide(&policy, "write_file", json!({})).await);
1350 assert!(!decide(&policy, "edit_file", json!({})).await);
1351 assert!(!decide(&policy, "bash", json!({})).await);
1352 assert!(!decide(&policy, "web_search", json!({})).await);
1353 assert!(decide(&policy, "web_fetch", json!({ "url": "https://bank.example/x" })).await);
1354 assert!(decide(&policy, "web_fetch", json!({ "url": "https://www.bank.example" })).await);
1355 assert!(!decide(&policy, "web_fetch", json!({ "url": "https://evil.example" })).await);
1356 assert!(
1357 !decide(&policy, "web_fetch", json!({ "url": "https://bank.example.evil.io" })).await
1358 );
1359 let nothing = AddedAgent::from_record(&record(PartitionMode::Ask, AgentUses::default()));
1360 let policy = nothing.deny_layer().unwrap();
1361 assert!(!decide(&policy, "read_file", json!({})).await);
1362 assert!(!decide(&policy, "web_fetch", json!({ "url": "https://a.io" })).await);
1363 assert!(decide(&policy, "write_todos", json!({})).await);
1364 let everything = AddedAgent::from_record(&record(
1365 PartitionMode::Ask,
1366 AgentUses::default()
1367 .with_files(FileAccess::ReadWrite)
1368 .with_shell(ShellAccess::Sandboxed)
1369 .with_web(WebAccess::Any),
1370 ));
1371 assert!(everything.deny_layer().is_none());
1372 }
1373
1374 #[test]
1375 fn the_stamp_refuses_another_agents_session() {
1376 assert!(check_stamp("finance", None, "s1").unwrap());
1377 assert!(!check_stamp("finance", Some(&json!("finance")), "s1").unwrap());
1378 let error = check_stamp("adk-rust", Some(&json!("finance")), "s1").unwrap_err();
1379 assert_eq!(error.code, AGENT_SESSION_CODE);
1380 assert!(check_stamp("finance", Some(&json!("adk-rust")), "s1").is_err());
1381 }
1382
1383 fn rule(id: &str, agent: Option<&str>) -> StandingRule {
1384 StandingRule {
1385 id: id.into(),
1386 scope: RuleScope::User {
1387 app_name: "adk-rust".into(),
1388 user_id: "ana".into(),
1389 subject_kind: SubjectKind::Human,
1390 },
1391 tool: "read_file".into(),
1392 origin: OriginPin::exact(&ToolOrigin::new(
1393 "static",
1394 &json!({ "name": "read_file" }),
1395 None,
1396 )),
1397 agent: agent.map(str::to_string),
1398 predicates: vec![],
1399 decision: StandingDecision::Allow,
1400 created_by: SubjectRef::human("ana"),
1401 created_at: chrono::Utc::now(),
1402 expires_at: None,
1403 label: "Reading files".into(),
1404 source_fingerprint: None,
1405 }
1406 }
1407
1408 #[tokio::test]
1409 async fn pinned_only_rules_ignore_none_globs_and_other_agents() {
1410 let shared: Arc<dyn StandingRuleStore> = Arc::new(InMemoryStandingRuleStore::new());
1411 for (id, agent) in [
1412 ("any", None),
1413 ("star", Some("*")),
1414 ("glob", Some("urn:adk:agent:adk-rust/*")),
1415 ("primary", Some("urn:adk:agent:adk-rust/adk-rust")),
1416 ("mine", Some("urn:adk:agent:adk-rust/finance")),
1417 ] {
1418 shared.grant(rule(id, agent)).await.unwrap();
1419 }
1420 let finance = PinnedOnlyRules::new(shared.clone(), "finance");
1421 let ids =
1422 |rules: Vec<StandingRule>| rules.into_iter().map(|rule| rule.id).collect::<Vec<_>>();
1423 assert_eq!(ids(finance.rules_for("adk-rust", "ana", "s1").await.unwrap()), ["mine"]);
1424 assert_eq!(ids(finance.list("adk-rust", "ana").await.unwrap()), ["mine"]);
1425 let granted = finance.grant(rule("new", None)).await.unwrap();
1427 assert_eq!(granted.agent.as_deref(), Some("urn:adk:agent:adk-rust/finance"));
1428 assert!(!finance.revoke("adk-rust", "primary").await.unwrap());
1430 assert_eq!(shared.list("adk-rust", "ana").await.unwrap().len(), 6);
1431 }
1432
1433 #[test]
1434 fn a_copy_is_pinned_and_made_by_a_person() {
1435 let original = rule("r1", None);
1436 let copy =
1437 copy_rule_to(&original, "urn:adk:agent:adk-rust/finance", SubjectRef::human("ana"))
1438 .unwrap();
1439 assert_ne!(copy.id, original.id);
1440 assert_eq!(copy.agent.as_deref(), Some("urn:adk:agent:adk-rust/finance"));
1441 assert_eq!(copy.tool, original.tool);
1442 let agent = SubjectRef::agent(&AgentId::new("urn:adk:agent:adk-rust/adk-rust").unwrap());
1443 assert!(copy_rule_to(&original, "urn:adk:agent:adk-rust/finance", agent).is_err());
1444 }
1445}