1use std::collections::BTreeSet;
4use std::sync::Arc;
5use std::time::Duration;
6
7use adk_core::audit_log::AuditActor;
8use adk_core::{
9 AdkError, Agent, AgentCapabilities, AgentTopology, ApprovalService, ApprovalStore,
10 DEFAULT_TOOL_CONFIRMATION_TIMEOUT, ErrorCategory, ErrorComponent, EventStream,
11 EventsCompactionConfig, InvocationContext, Result, RunBudget, RunConfig, Session, SpendLedger,
12 ToolConfirmationHandler, ToolPolicy, async_trait,
13};
14use adk_devtools::Workspace;
15use serde::Serialize;
16use serde_json::{Value, json};
17
18use crate::approvals::StandingRuleStore;
19use crate::approvals::matcher::is_protected_target;
20use crate::audit::HarnessAudit;
21use crate::instructions::{ProjectInstructions, WorkspaceTrustStore};
22use crate::mode::{HarnessMode, ModeStore};
23use crate::policy::{HarnessPolicy, composed_layer_owner, register_composed_layer};
24use crate::shell::{IsolationStatus, ShellLedger};
25use crate::tools::TodoList;
26use crate::toolset::HarnessToolset;
27
28pub const HARNESS_UNGOVERNED_CODE: &str = "harness.ungoverned";
36
37#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
46#[serde(rename_all = "camelCase")]
47pub struct HarnessInfo {
48 pub name: String,
50 pub default_mode: HarnessMode,
52 pub isolation: IsolationStatus,
54 pub degraded_reason: Option<String>,
56 pub members: Vec<String>,
58 pub packs: Vec<String>,
60 pub tools: Vec<String>,
62 pub effort: crate::posture::EffortPolicy,
64 pub context_caching: bool,
66 pub web_search: crate::web::WebSearchPath,
68}
69
70impl HarnessInfo {
71 pub fn shell(&self) -> Option<&IsolationStatus> {
94 self.tools.iter().any(|tool| tool == "bash").then_some(&self.isolation)
95 }
96}
97
98#[derive(Debug)]
100pub(crate) struct InstructionState {
101 pub(crate) instructions: ProjectInstructions,
102 pub(crate) trust_store: Arc<dyn WorkspaceTrustStore>,
103 pub(crate) require_trust: bool,
104}
105
106impl InstructionState {
107 pub(crate) fn trusted(&self) -> bool {
108 if !self.require_trust {
109 return true;
110 }
111 match self.trust_store.get(self.instructions.root_digest()) {
112 Ok(Some(trust)) => trust.covers(&self.instructions.instructions_digest()),
113 Ok(None) => false,
114 Err(error) => {
115 tracing::warn!(error = %error, "workspace trust store unavailable; treating the workspace as untrusted");
116 false
117 }
118 }
119 }
120}
121
122#[derive(Clone)]
130pub struct HarnessRuntime {
131 pub(crate) policy: HarnessPolicy,
132 pub(crate) operator_policy: Option<Arc<dyn ToolPolicy>>,
133 pub(crate) mode_store: Arc<dyn ModeStore>,
134 pub(crate) standing_rules: Arc<dyn StandingRuleStore>,
135 pub(crate) ledger: Arc<dyn ShellLedger>,
136 pub(crate) approval_store: Arc<dyn ApprovalStore>,
137 pub(crate) approval_service: Option<Arc<dyn ApprovalService>>,
138 pub(crate) auto_review: Option<Arc<dyn adk_core::ToolReviewer>>,
140 pub(crate) requested_call_seal: Option<Arc<dyn adk_core::RequestedCallSeal>>,
142 pub(crate) ledgers: crate::ledger::HarnessLedgers,
143 pub(crate) handler: Option<Arc<dyn ToolConfirmationHandler>>,
144 pub(crate) confirmation_timeout: Duration,
145 pub(crate) budget: Option<RunBudget>,
146 pub(crate) spend_ledger: Option<Arc<dyn SpendLedger>>,
147 pub(crate) history_max_events: Option<usize>,
148 pub(crate) compaction: Option<EventsCompactionConfig>,
149 pub(crate) intra_compaction: Option<adk_core::IntraCompactionConfig>,
152 pub(crate) toolset: Arc<HarnessToolset>,
153 pub(crate) instructions: Arc<InstructionState>,
154 pub(crate) non_waivable_tools: BTreeSet<String>,
155 pub(crate) non_waivable_prefixes: Vec<String>,
158 pub(crate) workspace: Workspace,
159 pub(crate) audit: Option<adk_core::audit_log::AuditTrail>,
160 #[cfg(feature = "auth")]
161 pub(crate) identity: Arc<crate::identity::IdentityGate>,
162 #[cfg(feature = "observe")]
163 pub(crate) spend: Arc<crate::observe::SpendAccounts>,
164 #[cfg(feature = "observe")]
165 pub(crate) run_trails: Arc<crate::observe::RunTrails>,
166 #[cfg(feature = "team")]
167 pub(crate) team: Option<Arc<crate::team::HarnessTeam>>,
168 #[cfg(feature = "graph")]
169 pub(crate) plan_graph: Option<Arc<crate::plan_graph::PlanGraphs>>,
170 pub(crate) snapshots: Option<Arc<crate::snapshot::Snapshots>>,
172 pub(crate) goals: crate::goal::GoalRuntime,
173 #[cfg(feature = "kernel")]
175 pub(crate) kernel_approvals: Arc<crate::kernel::LateApprovalNotifier>,
176 #[cfg(feature = "kernel")]
179 pub(crate) kernel_agenda: adk_kernel::AgendaHandle,
180 #[cfg(feature = "kernel")]
183 pub(crate) kernel_ledger: adk_kernel::proc::LateLedgerSink,
184 #[cfg(feature = "kernel")]
186 pub(crate) partition: Option<crate::partition::PartitionWiring>,
187 #[cfg(feature = "kernel")]
189 pub(crate) session_stamp: Option<String>,
190 #[cfg(feature = "web")]
192 pub(crate) provider_web: Option<Arc<crate::web::provider::ProviderWebToolset>>,
193 #[cfg(feature = "mcp")]
195 pub(crate) mcp: Option<Arc<crate::mcp::McpInteractionRuntime>>,
196 #[cfg(feature = "hooks")]
197 pub(crate) hooks: Option<Arc<crate::hooks::HookRunner>>,
198 pub(crate) effort: crate::posture::EffortPolicy,
199 #[cfg_attr(not(feature = "runner"), allow(dead_code))]
202 pub(crate) cache_capable: Option<Arc<dyn adk_core::CacheCapable>>,
203 #[cfg(feature = "payments")]
205 pub(crate) payments: Option<Arc<crate::packs::payments::PaymentsReminder>>,
206 #[cfg(feature = "computer-use")]
209 #[cfg_attr(not(feature = "runner"), allow(dead_code))]
210 pub(crate) screen_plans: Option<Arc<crate::packs::computer_use::ScreenPlans>>,
211 pub(crate) take_over: Option<crate::take_over::TakeOver>,
213 #[cfg_attr(not(feature = "voice"), allow(dead_code))]
216 pub(crate) agent_tools: AgentTools,
217}
218
219pub(crate) type AgentTools = (Vec<Arc<dyn adk_core::Tool>>, Vec<Arc<dyn adk_core::Toolset>>);
221
222pub(crate) fn harness_audit_trail(
225 recorder: Option<Arc<dyn adk_core::audit_log::AuditRecorder>>,
226) -> Result<Option<adk_core::audit_log::AuditTrail>> {
227 #[cfg(feature = "auth")]
228 let recorder = match recorder {
229 Some(recorder) => Some(recorder),
230 None => Some(Arc::new(crate::identity::EphemeralAuditLog::new()?)
231 as Arc<dyn adk_core::audit_log::AuditRecorder>),
232 };
233 Ok(recorder.map(adk_core::audit_log::AuditTrail::new))
234}
235
236impl std::fmt::Debug for HarnessRuntime {
237 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
238 f.debug_struct("HarnessRuntime")
239 .field("policy", &self.policy)
240 .field("confirmation_timeout", &self.confirmation_timeout)
241 .field("handler", &self.handler.is_some())
242 .finish_non_exhaustive()
243 }
244}
245
246impl HarnessRuntime {
247 pub fn layer(&self) -> HarnessLayer<'_> {
249 HarnessLayer { runtime: self }
250 }
251
252 pub fn policy(&self) -> &HarnessPolicy {
254 &self.policy
255 }
256
257 pub fn mode_store(&self) -> &Arc<dyn ModeStore> {
259 &self.mode_store
260 }
261
262 pub fn standing_rules(&self) -> &Arc<dyn StandingRuleStore> {
264 &self.standing_rules
265 }
266
267 pub fn shell_ledger(&self) -> &Arc<dyn ShellLedger> {
269 &self.ledger
270 }
271
272 pub fn approval_store(&self) -> &Arc<dyn ApprovalStore> {
274 &self.approval_store
275 }
276
277 pub fn approval_service(&self) -> Option<&Arc<dyn ApprovalService>> {
279 self.approval_service.as_ref()
280 }
281
282 pub fn auto_review(&self) -> Option<&Arc<dyn adk_core::ToolReviewer>> {
285 self.auto_review.as_ref()
286 }
287
288 pub fn take_over(&self) -> Option<&crate::take_over::TakeOver> {
291 self.take_over.as_ref()
292 }
293
294 pub fn action_ledger(&self) -> &Arc<dyn adk_core::ActionLedger> {
297 self.ledgers.store()
298 }
299
300 pub fn confirmation_handler(&self) -> Option<&Arc<dyn ToolConfirmationHandler>> {
303 self.handler.as_ref()
304 }
305
306 pub fn toolset(&self) -> &Arc<HarnessToolset> {
308 &self.toolset
309 }
310
311 pub fn instructions(&self) -> &ProjectInstructions {
313 &self.instructions.instructions
314 }
315
316 pub fn trust_store(&self) -> &Arc<dyn WorkspaceTrustStore> {
318 &self.instructions.trust_store
319 }
320
321 pub fn workspace_trusted(&self) -> bool {
323 self.instructions.trusted()
324 }
325
326 pub fn workspace(&self) -> &Workspace {
328 &self.workspace
329 }
330
331 pub fn compaction(&self) -> Option<&EventsCompactionConfig> {
333 self.compaction.as_ref()
334 }
335
336 pub fn intra_compaction(&self) -> Option<&adk_core::IntraCompactionConfig> {
339 self.intra_compaction.as_ref()
340 }
341
342 #[cfg(feature = "observe")]
345 pub fn spend(&self, subject: Option<&str>) -> crate::observe::SpendReport {
346 self.spend.report(subject)
347 }
348
349 pub fn audit_trail(&self) -> Option<&adk_core::audit_log::AuditTrail> {
351 self.audit.as_ref()
352 }
353
354 #[cfg(feature = "mcp")]
362 pub async fn mcp_resource_mention(
363 &self,
364 app: &str,
365 user: &str,
366 session: &str,
367 server: &str,
368 uri: &str,
369 ) -> Result<serde_json::Value> {
370 let Some(mcp) = &self.mcp else {
371 return Err(AdkError::new(
372 ErrorComponent::Tool,
373 ErrorCategory::NotFound,
374 "harness.mcp.unknown_server",
375 "this harness has no MCP servers",
376 ));
377 };
378 let audit = self.audit.clone().map(|trail| {
379 crate::audit::HarnessAudit::new(
380 trail,
381 adk_core::audit_log::AuditActor::for_invocation(app, "harness", user, "mention"),
382 session,
383 )
384 });
385 mcp.read_resource(server, uri, "mention", audit.as_ref()).await
386 }
387
388 #[cfg(feature = "mcp")]
390 pub fn mcp(&self) -> Option<&Arc<crate::mcp::McpInteractionRuntime>> {
391 self.mcp.as_ref()
392 }
393
394 #[cfg(feature = "team")]
396 pub fn team(&self) -> Option<&crate::team::HarnessTeam> {
397 self.team.as_deref()
398 }
399
400 pub fn goal_store(&self) -> &Arc<dyn crate::goal::GoalStore> {
402 &self.goals.store
403 }
404
405 #[cfg(feature = "graph")]
407 pub fn plan_graph(&self) -> Option<&Arc<crate::plan_graph::PlanGraphs>> {
408 self.plan_graph.as_ref()
409 }
410
411 pub fn snapshots(&self) -> Option<&Arc<crate::snapshot::Snapshots>> {
415 self.snapshots.as_ref()
416 }
417
418 #[cfg(feature = "hooks")]
420 pub fn hooks(&self) -> Option<&crate::hooks::HookSet> {
421 self.hooks.as_deref().map(crate::hooks::HookRunner::set)
422 }
423}
424
425#[derive(Clone, Copy)]
445pub struct HarnessLayer<'a> {
446 runtime: &'a HarnessRuntime,
447}
448
449pub(crate) fn names_non_waivable(
453 fingerprint: &str,
454 non_waivable: &BTreeSet<String>,
455 prefixes: &[String],
456 root: &std::path::Path,
457) -> bool {
458 let parts: Vec<&str> = fingerprint.splitn(5, '\u{1f}').collect();
459 if parts.iter().any(|part| non_waivable.contains(*part)) {
460 return true;
461 }
462 if parts.get(3).is_some_and(|tool| prefixes.iter().any(|prefix| tool.starts_with(prefix))) {
463 return true;
464 }
465 let [_, _, _, tool, args] = parts.as_slice() else {
466 return true;
467 };
468 let Ok(args) = serde_json::from_str::<Value>(args) else {
469 return true;
470 };
471 match *tool {
472 "bash" => args.get("unsandboxed").is_some_and(|value| *value != Value::Bool(false)),
473 "write_file" | "edit_file" | crate::edits::APPLY_PATCH => {
475 crate::edits::edit_paths(tool, &args).is_none_or(|paths| {
476 paths.is_empty() || paths.iter().any(|path| is_protected_target(root, path))
477 })
478 }
479 _ => false,
480 }
481}
482
483impl HarnessLayer<'_> {
484 pub fn apply(&self, config: &mut RunConfig) {
486 self.apply_with(config, true);
487 }
488
489 fn apply_with(&self, config: &mut RunConfig, compose_policy: bool) {
492 let runtime = self.runtime;
493 if compose_policy && config.audit.is_none() {
497 config.audit = runtime.audit.clone();
498 }
499 let owner = runtime.policy.owner_id();
500 if compose_policy
501 && config.tool_policy.as_deref().and_then(composed_layer_owner) != Some(owner)
502 {
503 #[cfg(feature = "kernel")]
506 if runtime.kernel_ledger.is_bound()
507 && let Some(trail) = config.audit.take()
508 {
509 let address = |trail: &adk_core::audit_log::AuditTrail| {
510 Arc::as_ptr(trail.recorder()).cast::<()>() as usize
511 };
512 let ours =
513 runtime.audit.as_ref().is_some_and(|own| address(own) == address(&trail));
514 config.audit = Some(if ours {
515 trail
516 } else {
517 crate::kernel::tap_audit(trail, &runtime.kernel_ledger)
518 });
519 }
520 let mut layers: Vec<Arc<dyn ToolPolicy>> = Vec::new();
521 if let Some(existing) = config.tool_policy.take() {
522 layers.push(existing);
523 }
524 if let Some(operator) = &runtime.operator_policy {
525 layers.push(operator.clone());
526 }
527 let peers = (!layers.is_empty()).then(|| {
528 Arc::new(adk_core::StrictestPolicy::new(layers.clone())) as Arc<dyn ToolPolicy>
529 });
530 layers.push(Arc::new(
531 runtime
532 .policy
533 .with_audit(config.audit.clone())
534 .with_peers(peers)
535 .with_governance(config.governance.clone()),
536 ));
537 let composed: Arc<dyn ToolPolicy> = Arc::new(adk_core::StrictestPolicy::new(layers));
538 register_composed_layer(owner, &composed);
539 config.tool_policy = Some(composed);
540 }
541
542 if config.tool_reviewer.is_none()
544 && let Some(reviewer) = &runtime.auto_review
545 {
546 config.tool_reviewer = Some(Arc::new(crate::policy::AutoReview::new(
547 reviewer.clone(),
548 runtime.policy.clone(),
549 runtime.non_waivable_tools.clone(),
550 runtime.non_waivable_prefixes.clone(),
551 runtime.workspace.root().to_path_buf(),
552 )));
553 }
554 if config.requested_call_seal.is_none() {
555 config.requested_call_seal = runtime.requested_call_seal.clone();
556 }
557 match (&config.approval_service, &runtime.approval_service) {
558 (None, Some(service)) => config.approval_service = Some(service.clone()),
559 (Some(own), Some(service)) if !Arc::ptr_eq(own, service) => tracing::warn!(
560 "the run carries its own approval service; keeping it instead of the harness's"
561 ),
562 _ => {}
563 }
564 match &config.approval_store {
565 None => {
566 let store = runtime
567 .approval_service
568 .as_ref()
569 .and_then(|service| service.approval_store())
570 .unwrap_or_else(|| runtime.approval_store.clone());
571 config.approval_store = Some(store);
572 }
573 Some(own) if !Arc::ptr_eq(own, &runtime.approval_store) => {
574 tracing::debug!("the run carries its own approval store; keeping it");
575 }
576 Some(_) => {}
577 }
578
579 if compose_policy {
583 config.action_ledger = Some(runtime.ledgers.for_run(config.action_ledger.as_ref()));
584 }
585
586 let before = config.tool_approvals.len();
587 config.tool_approvals.retain(|fingerprint, _| {
588 !names_non_waivable(
589 fingerprint,
590 &runtime.non_waivable_tools,
591 &runtime.non_waivable_prefixes,
592 runtime.workspace.root(),
593 )
594 });
595 if config.tool_approvals.len() != before {
596 tracing::warn!(
597 removed = before - config.tool_approvals.len(),
598 "removed run-wide approvals of non-waivable tool calls"
599 );
600 }
601
602 if config.tool_confirmation_timeout == DEFAULT_TOOL_CONFIRMATION_TIMEOUT {
603 config.tool_confirmation_timeout = runtime.confirmation_timeout;
604 }
605 if config.budget.is_none()
606 && let Some(budget) = &runtime.budget
607 {
608 config.budget = Some(budget.clone());
609 }
610 if compose_policy
614 && config.budget_tracker.is_none()
615 && let Some(budget) = &config.budget
616 {
617 config.budget_tracker = Some(Arc::new(adk_core::BudgetTracker::new(budget.clone())));
618 }
619 if config.spend_ledger.is_none() {
620 config.spend_ledger = runtime.spend_ledger.clone();
621 }
622 #[cfg(feature = "observe")]
623 if compose_policy {
624 crate::observe::meter_run(&runtime.spend, config);
625 }
626 if config.history_max_events.is_none() {
627 config.history_max_events = runtime.history_max_events;
628 }
629 if config.intra_compaction.is_none() {
630 config.intra_compaction = runtime.intra_compaction.clone();
631 }
632 }
633}
634
635pub struct HarnessAgent {
655 pub(crate) root: Arc<dyn Agent>,
656 pub(crate) runtime: HarnessRuntime,
657 pub(crate) info: HarnessInfo,
658 pub(crate) manifest: crate::manifest::HarnessManifest,
659}
660
661impl std::fmt::Debug for HarnessAgent {
662 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
663 f.debug_struct("HarnessAgent").field("info", &self.info).finish_non_exhaustive()
664 }
665}
666
667impl HarnessAgent {
668 pub fn builder(name: impl Into<String>) -> crate::HarnessAgentBuilder {
677 crate::HarnessAgentBuilder::new(name)
678 }
679
680 pub fn agent(&self) -> Arc<dyn Agent> {
683 Arc::new(Self {
684 root: self.root.clone(),
685 runtime: self.runtime.clone(),
686 info: self.info.clone(),
687 manifest: self.manifest.clone(),
688 })
689 }
690
691 pub fn runtime(&self) -> &HarnessRuntime {
693 &self.runtime
694 }
695
696 pub fn info(&self) -> &HarnessInfo {
698 &self.info
699 }
700
701 pub fn manifest(&self) -> &crate::manifest::HarnessManifest {
723 &self.manifest
724 }
725
726 #[cfg(feature = "kernel")]
729 pub fn partition(&self) -> Option<&adk_kernel::Partition> {
730 self.runtime.partition.as_ref().map(|wiring| &wiring.partition)
731 }
732
733 #[cfg(feature = "kernel")]
736 pub fn partition_policy(&self) -> Option<&adk_kernel::PartitionPolicy> {
737 self.runtime.partition.as_ref().map(|wiring| &wiring.policy)
738 }
739
740 #[cfg(feature = "kernel")]
741 pub(crate) fn partition_wiring(&self) -> Option<&crate::partition::PartitionWiring> {
742 self.runtime.partition.as_ref()
743 }
744
745 pub fn run_config(&self) -> RunConfig {
749 let mut config = RunConfig::default();
750 if let Some(handler) = &self.runtime.handler {
751 config.tool_confirmation_handler = Some(handler.clone());
752 }
753 self.runtime.layer().apply(&mut config);
754 config
755 }
756
757 pub fn governed_root(&self, root: Arc<dyn Agent>) -> Arc<dyn Agent> {
784 Arc::new(GovernedRoot {
785 runtime: self.runtime.clone(),
786 root,
787 default_mode: self.info.default_mode,
788 isolation: self.info.isolation.clone(),
789 })
790 }
791
792 #[cfg(feature = "runner")]
799 pub fn configure_runner<A, G, S>(
800 &self,
801 builder: adk_runner::RunnerConfigBuilder<A, G, S>,
802 ) -> adk_runner::RunnerConfigBuilder<A, G, S> {
803 let mut config = RunConfig::default();
806 if let Some(handler) = &self.runtime.handler {
807 config.tool_confirmation_handler = Some(handler.clone());
808 }
809 self.runtime.layer().apply_with(&mut config, false);
810 let mut builder =
811 builder.run_config(config).approval_store(self.runtime.approval_store.clone());
812 if let Some(trail) = &self.runtime.audit {
813 builder = builder.audit_log(trail.recorder().clone());
814 }
815 if let Some(compaction) = &self.runtime.compaction {
816 builder = builder.compaction_config(compaction.clone());
817 }
818 if let Some(model) = &self.runtime.cache_capable {
820 builder = builder
821 .cache_capable(model.clone())
822 .context_cache_config(adk_core::ContextCacheConfig::default());
823 }
824 builder
825 }
826
827 pub fn effort(&self) -> &crate::posture::EffortPolicy {
829 &self.runtime.effort
830 }
831
832 pub fn todos(&self, session: &dyn Session) -> TodoList {
834 TodoList::from_state(session.state())
835 }
836
837 #[cfg(feature = "runner")]
844 pub fn into_harness(
845 self,
846 app_name: impl Into<String>,
847 sessions: Arc<dyn adk_session::SessionService>,
848 ) -> Result<crate::Harness> {
849 crate::Harness::new(Arc::new(self), app_name.into(), sessions)
850 }
851}
852
853#[async_trait]
854impl Agent for HarnessAgent {
855 fn name(&self) -> &str {
858 &self.info.name
859 }
860
861 fn description(&self) -> &str {
862 self.root.description()
863 }
864
865 fn sub_agents(&self) -> &[Arc<dyn Agent>] {
866 self.root.sub_agents()
867 }
868
869 fn topology(&self) -> Option<AgentTopology> {
870 self.root.topology()
871 }
872
873 fn capabilities(&self) -> AgentCapabilities {
877 AgentCapabilities { handoff: self.supports_agent_transfer(), ..self.root.capabilities() }
878 }
879
880 fn supports_agent_transfer(&self) -> bool {
883 self.info.members.is_empty() && self.root.supports_agent_transfer()
884 }
885
886 fn transfer_targets_for(&self, agent_name: &str) -> Option<Vec<String>> {
887 self.root.transfer_targets_for(agent_name)
888 }
889
890 fn configure_run(&self, agent_name: &str, config: &mut RunConfig) {
891 self.root.configure_run(agent_name, config);
892 self.runtime.layer().apply(config);
893 }
894
895 async fn close(&self) {
896 self.root.close().await;
897 }
898
899 async fn prewarm(&self) -> Result<()> {
902 #[cfg(feature = "mcp")]
903 if let Some(mcp) = &self.runtime.mcp {
904 mcp.ensure_started(self.runtime.workspace_trusted()).await;
905 }
906 self.root.prewarm().await
907 }
908
909 async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
910 #[cfg(feature = "kernel")]
912 let mark = match self.partition_wiring() {
913 Some(wiring) => wiring.session_mark(ctx.as_ref(), self.name())?,
914 None => None,
915 };
916 #[cfg(feature = "kernel")]
919 let stamp = match &self.runtime.session_stamp {
920 Some(stamp) => crate::agents::stamp_event(ctx.as_ref(), stamp, self.name())?,
921 None => None,
922 };
923 #[cfg(feature = "web")]
926 if let Some(provider_web) = &self.runtime.provider_web {
927 provider_web.record_run_start(ctx.as_ref()).await?;
928 }
929 #[cfg(feature = "mcp")]
932 if let Some(mcp) = &self.runtime.mcp {
933 mcp.ensure_started(self.runtime.workspace_trusted()).await;
934 }
935 if let Some(snapshots) = &self.runtime.snapshots {
937 #[cfg(feature = "graph")]
938 let plan = match &self.runtime.plan_graph {
939 Some(graphs) => graphs
940 .mark(ctx.app_name(), ctx.user_id(), ctx.session_id())
941 .await
942 .ok()
943 .flatten(),
944 None => None,
945 };
946 #[cfg(not(feature = "graph"))]
947 let plan = None;
948 crate::snapshot::before_turn(snapshots, ctx.as_ref(), plan).await;
949 }
950 let events = self.run_governed(ctx.clone()).await?;
951 #[cfg(feature = "web")]
954 let events = match &self.runtime.provider_web {
955 Some(provider_web) => provider_web.record_searches(ctx.clone(), events),
956 None => events,
957 };
958 let events = self.with_mode_mirror(&ctx, events).await;
959 #[cfg(feature = "kernel")]
960 let events = match mark {
961 Some(mark) => {
962 use futures::StreamExt as _;
963 Box::pin(futures::stream::iter([Ok(mark)]).chain(events)) as EventStream
964 }
965 None => events,
966 };
967 #[cfg(feature = "kernel")]
968 let events = match stamp {
969 Some(stamp) => {
970 use futures::StreamExt as _;
971 Box::pin(futures::stream::iter([Ok(stamp)]).chain(events)) as EventStream
972 }
973 None => events,
974 };
975 Ok(events)
976 }
977}
978
979impl HarnessAgent {
980 async fn with_mode_mirror(
984 &self,
985 ctx: &Arc<dyn InvocationContext>,
986 events: EventStream,
987 ) -> EventStream {
988 use futures::StreamExt as _;
989 let store = self.runtime.mode_store.clone();
990 let default_mode = self.info.default_mode;
991 let identity =
992 (ctx.app_name().to_string(), ctx.user_id().to_string(), ctx.session_id().to_string());
993 let mirror = move || {
994 let store = store.clone();
995 let (app, user, session) = identity.clone();
996 async move {
997 crate::mode::mode_mirror(store.as_ref(), default_mode, (&app, &user, &session))
998 .await
999 }
1000 };
1001 let shown = ctx.session().state().get(crate::mode::MODE_STATE_KEY);
1004 let prelude = match (shown, mirror().await) {
1005 (Some(shown), Some(value)) if shown != value => {
1006 let mut event = adk_core::Event::new(ctx.invocation_id());
1007 event.author = self.name().to_string();
1008 event.branch = ctx.branch().to_string();
1009 event.actions.state_delta.insert(crate::mode::MODE_STATE_KEY.to_string(), value);
1010 Some(Ok(event))
1011 }
1012 _ => None,
1013 };
1014 let events = events.then(move |event| {
1015 let mirror = mirror();
1016 async move {
1017 let mut event = event?;
1018 if event.actions.state_delta.contains_key(crate::mode::MODE_STATE_KEY) {
1019 match mirror.await {
1020 Some(value) => {
1021 event
1022 .actions
1023 .state_delta
1024 .insert(crate::mode::MODE_STATE_KEY.to_string(), value);
1025 }
1026 None => {
1027 event.actions.state_delta.remove(crate::mode::MODE_STATE_KEY);
1028 }
1029 }
1030 }
1031 Ok(event)
1032 }
1033 });
1034 Box::pin(futures::stream::iter(prelude).chain(events))
1035 }
1036
1037 async fn run_governed(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
1038 let config = ctx.run_config();
1039 if config.tool_policy.as_deref().and_then(composed_layer_owner)
1041 != Some(self.runtime.policy.owner_id())
1042 {
1043 return Err(AdkError::new(
1044 ErrorComponent::Agent,
1045 ErrorCategory::Forbidden,
1046 HARNESS_UNGOVERNED_CODE,
1047 format!(
1048 "harness '{}' refuses to run without its policy in the run config; run it as \
1049 the root agent of a Runner, or apply HarnessAgent::run_config()",
1050 self.name()
1051 ),
1052 ));
1053 }
1054 #[cfg(feature = "auth")]
1055 {
1056 let blocking = config.audit.as_ref().is_some_and(|trail| {
1057 trail.failure_mode() == adk_core::audit_log::AuditFailureMode::Block
1058 });
1059 if !blocking {
1060 return Err(crate::identity::audit_required(self.name()));
1061 }
1062 self.runtime.identity.observe(ctx.as_ref());
1063 }
1064 if ctx.user_id() != ctx.session().user_id() {
1065 return Err(AdkError::new(
1066 ErrorComponent::Agent,
1067 ErrorCategory::Forbidden,
1068 "harness.identity_mismatch",
1069 "the run's user is not the session's user",
1070 ));
1071 }
1072 #[cfg(feature = "memory")]
1075 if let Some(facts) = self.runtime.toolset.facts() {
1076 facts.observe_invocation(ctx.as_ref());
1077 }
1078 #[cfg(feature = "payments")]
1080 if let Some(payments) = &self.runtime.payments {
1081 payments.observe_invocation(ctx.as_ref());
1082 }
1083 if let Some(trail) = config.audit.clone() {
1084 let state = &self.runtime.instructions;
1085 let trusted = state.trusted();
1086 let audit =
1087 HarnessAudit::new(trail, AuditActor::for_context(ctx.as_ref()), ctx.session_id());
1088 if let Ok(Some(trust)) = state.trust_store.get(state.instructions.root_digest())
1090 && trust.is_trusted()
1091 && !trusted
1092 {
1093 tracing::warn!(
1094 "the workspace's instruction files changed since they were trusted; they are not loaded"
1095 );
1096 audit
1097 .record(
1098 "harness.instructions.changed",
1099 json!({
1100 "files": state.instructions.audit_files(false),
1101 "rootDigest": state.instructions.root_digest(),
1102 "trustedDigest": trust.instructions_digest,
1103 "currentDigest": state.instructions.instructions_digest(),
1104 "by": trust.by,
1105 }),
1106 )
1107 .await?;
1108 }
1109 audit
1110 .record(
1111 "harness.instructions.loaded",
1112 json!({
1113 "files": state.instructions.audit_files(trusted),
1114 "rootDigest": state.instructions.root_digest(),
1115 "trusted": trusted,
1116 "nested": state.instructions.nested().len(),
1117 }),
1118 )
1119 .await?;
1120 }
1121 #[cfg(feature = "hooks")]
1124 if let Some(hooks) = &self.runtime.hooks {
1125 let mode = self
1126 .runtime
1127 .policy
1128 .mode_for(ctx.app_name(), ctx.user_id(), ctx.session_id(), ctx.invocation_id())
1129 .await;
1130 let scope = crate::hooks::HookScope::from_invocation(ctx.as_ref());
1131 let audit = config.audit.clone().map(|trail| {
1132 HarnessAudit::new(trail, AuditActor::for_context(ctx.as_ref()), ctx.session_id())
1133 });
1134 hooks.on_session_start(mode, &scope, audit.as_ref()).await;
1135 }
1136 #[cfg(feature = "observe")]
1137 let events = {
1138 let mode = crate::observe::run_mode(
1139 self.runtime.mode_store.as_ref(),
1140 self.info.default_mode,
1141 ctx.as_ref(),
1142 )
1143 .await;
1144 let span = crate::observe::run_span(
1145 self.name(),
1146 ctx.invocation_id(),
1147 mode,
1148 &self.info.isolation,
1149 );
1150 let events = {
1151 use tracing::Instrument as _;
1152 self.turn(ctx.clone()).instrument(span.clone()).await?
1153 };
1154 crate::observe::observe_run(
1155 events,
1156 &ctx,
1157 span,
1158 self.runtime.spend.clone(),
1159 self.runtime.run_trails.clone(),
1160 self.runtime.effort.for_mode(mode),
1161 )
1162 };
1163 #[cfg(not(feature = "observe"))]
1164 let events = self.turn(ctx.clone()).await?;
1165 #[cfg(feature = "hooks")]
1168 let events = match &self.runtime.hooks {
1169 Some(hooks) => {
1170 let mode = self
1171 .runtime
1172 .policy
1173 .mode_for(ctx.app_name(), ctx.user_id(), ctx.session_id(), ctx.invocation_id())
1174 .await;
1175 hooks.observe(events, ctx.clone(), mode, self.name().to_string())
1176 }
1177 None => events,
1178 };
1179 Ok(events)
1180 }
1181}
1182
1183struct GovernedRoot {
1186 runtime: HarnessRuntime,
1187 root: Arc<dyn Agent>,
1188 default_mode: HarnessMode,
1189 isolation: crate::shell::IsolationStatus,
1190}
1191
1192#[async_trait]
1193impl Agent for GovernedRoot {
1194 fn name(&self) -> &str {
1195 self.root.name()
1196 }
1197
1198 fn description(&self) -> &str {
1199 self.root.description()
1200 }
1201
1202 fn sub_agents(&self) -> &[Arc<dyn Agent>] {
1203 self.root.sub_agents()
1204 }
1205
1206 fn supports_agent_transfer(&self) -> bool {
1207 false
1208 }
1209
1210 fn configure_run(&self, agent_name: &str, config: &mut RunConfig) {
1211 self.root.configure_run(agent_name, config);
1212 self.runtime.layer().apply(config);
1213 }
1214
1215 async fn close(&self) {
1216 self.root.close().await;
1217 }
1218
1219 async fn prewarm(&self) -> Result<()> {
1220 self.root.prewarm().await
1221 }
1222
1223 async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
1224 let config = ctx.run_config();
1225 if config.tool_policy.as_deref().and_then(composed_layer_owner)
1226 != Some(self.runtime.policy.owner_id())
1227 {
1228 return Err(AdkError::new(
1229 ErrorComponent::Agent,
1230 ErrorCategory::Forbidden,
1231 HARNESS_UNGOVERNED_CODE,
1232 format!(
1233 "'{}' runs only under its harness's policy; run it as the root agent of a \
1234 Runner, whose configure_run applies the harness layer",
1235 self.root.name()
1236 ),
1237 ));
1238 }
1239 #[cfg(feature = "auth")]
1240 if !config.audit.as_ref().is_some_and(|trail| {
1241 trail.failure_mode() == adk_core::audit_log::AuditFailureMode::Block
1242 }) {
1243 return Err(crate::identity::audit_required(self.root.name()));
1244 }
1245 #[cfg(feature = "observe")]
1246 {
1247 use tracing::Instrument as _;
1248 let mode = crate::observe::run_mode(
1249 self.runtime.mode_store.as_ref(),
1250 self.default_mode,
1251 ctx.as_ref(),
1252 )
1253 .await;
1254 let span = crate::observe::run_span(
1255 self.root.name(),
1256 ctx.invocation_id(),
1257 mode,
1258 &self.isolation,
1259 );
1260 let events = self.root.run(ctx.clone()).instrument(span.clone()).await?;
1261 Ok(crate::observe::observe_run(
1262 events,
1263 &ctx,
1264 span,
1265 self.runtime.spend.clone(),
1266 self.runtime.run_trails.clone(),
1267 self.runtime.effort.for_mode(mode),
1268 ))
1269 }
1270 #[cfg(not(feature = "observe"))]
1271 {
1272 let _ = (self.default_mode, &self.isolation);
1273 self.root.run(ctx).await
1274 }
1275 }
1276}
1277
1278impl HarnessAgent {
1279 async fn turn(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
1282 let mode = self
1283 .runtime
1284 .policy
1285 .mode_for(ctx.app_name(), ctx.user_id(), ctx.session_id(), ctx.invocation_id())
1286 .await;
1287 if let Some(stream) =
1288 self.runtime.goals.route(mode, &self.info.name, self.root.clone(), ctx.clone()).await?
1289 {
1290 return Ok(stream);
1291 }
1292 #[cfg(feature = "graph")]
1293 if let Some(graphs) = &self.runtime.plan_graph
1294 && let Some(stream) = graphs.route(mode, self.root.clone(), ctx.clone()).await?
1295 {
1296 return Ok(stream);
1297 }
1298 self.root.run(ctx).await
1299 }
1300}
1301
1302fn rule_refused(message: &str) -> AdkError {
1304 AdkError::new(
1305 ErrorComponent::Agent,
1306 ErrorCategory::InvalidInput,
1307 "harness.decision.invalid",
1308 message,
1309 )
1310}
1311
1312impl HarnessAgent {
1315 pub fn rule_for_held_call(
1336 &self,
1337 request: &adk_core::ToolConfirmationRequest,
1338 suggestion: crate::RuleSuggestion,
1339 decision: crate::StandingDecision,
1340 owner: &crate::RuleOwner,
1341 ) -> Result<crate::StandingRule> {
1342 let runtime = &self.runtime;
1343 let origin = request
1344 .origin
1345 .as_ref()
1346 .ok_or_else(|| rule_refused("the pending call records no tool origin"))?;
1347 let kind = runtime.policy.registry().classify(
1348 &self.info.name,
1349 &request.tool_name,
1350 Some(origin),
1351 &request.args,
1352 adk_core::ToolEffect::NonIdempotent,
1353 runtime.policy.isolation_status().isolation(),
1354 false,
1355 );
1356 let protected = kind == crate::ToolKind::Edit
1357 && crate::edits::edit_paths(&request.tool_name, &request.args).is_none_or(|paths| {
1358 paths.is_empty()
1359 || paths.iter().any(|path| is_protected_target(runtime.workspace.root(), path))
1360 });
1361 if !kind.rule_eligible() || crate::TableRow::of(&kind, protected).is_non_waivable() {
1362 return Err(rule_refused("no standing rule applies to this call; decide it once"));
1363 }
1364 if self.folder_suggestion(request).as_ref() == Some(&suggestion) {
1367 return Ok(suggestion.into_rule(owner, decision, Some(request.fingerprint())));
1368 }
1369 if !suggestion.origin.admits(origin)
1370 || !matches!(suggestion.origin, crate::OriginPin::Exact { .. })
1371 || suggestion.tool != request.tool_name
1372 {
1373 return Err(rule_refused(
1374 "a remembered rule must pin this call's tool and declaration",
1375 ));
1376 }
1377 if decision == crate::StandingDecision::Allow
1378 && !crate::StandingRule::suggestions(request).contains(&suggestion)
1379 {
1380 return Err(rule_refused("only a suggested rule can be remembered as an allow rule"));
1381 }
1382 Ok(suggestion.into_rule(owner, decision, Some(request.fingerprint())))
1383 }
1384
1385 pub fn folder_suggestion(
1405 &self,
1406 request: &adk_core::ToolConfirmationRequest,
1407 ) -> Option<crate::RuleSuggestion> {
1408 crate::StandingRule::folder_suggestion(request, |name| self.runtime.toolset.origin_of(name))
1409 }
1410
1411 pub async fn grant_rule(
1428 &self,
1429 rule: crate::StandingRule,
1430 surface: &str,
1431 from: Option<&adk_core::ToolConfirmationRequest>,
1432 ) -> Result<crate::StandingRule> {
1433 if let Some(trail) = self.runtime.audit_trail() {
1434 let mut fields = crate::approvals::rule_audit_fields(
1435 &rule,
1436 from.and_then(|request| request.function_call_id.as_deref()),
1437 );
1438 fields["surface"] = json!(surface);
1439 HarnessAudit::new(
1440 trail.clone(),
1441 AuditActor::subject(rule.created_by.clone()),
1442 rule.scope.session_id().unwrap_or_default(),
1443 )
1444 .record("harness.rule.created", fields)
1445 .await?;
1446 }
1447 self.runtime.standing_rules.grant(rule).await
1448 }
1449
1450 pub async fn revoke_rule(
1464 &self,
1465 app: &str,
1466 user: &str,
1467 id: &str,
1468 surface: &str,
1469 ) -> Result<Option<crate::StandingRule>> {
1470 let standing = &self.runtime.standing_rules;
1471 let Some(rule) = standing.list(app, user).await?.into_iter().find(|rule| rule.id == id)
1472 else {
1473 return Ok(None);
1474 };
1475 if let Some(trail) = self.runtime.audit_trail() {
1476 let mut fields = crate::approvals::rule_audit_fields(&rule, None);
1477 fields["by"] = json!(user);
1478 fields["surface"] = json!(surface);
1479 HarnessAudit::new(
1480 trail.clone(),
1481 AuditActor::subject(adk_core::principal::SubjectRef::human(user)),
1482 rule.scope.session_id().unwrap_or_default(),
1483 )
1484 .record("harness.rule.revoked", fields)
1485 .await?;
1486 }
1487 Ok(standing.revoke(app, id).await?.then_some(rule))
1488 }
1489
1490 pub async fn extend_rule(
1509 &self,
1510 app: &str,
1511 user: &str,
1512 id: &str,
1513 until: chrono::DateTime<chrono::Utc>,
1514 surface: &str,
1515 ) -> Result<Option<crate::StandingRule>> {
1516 let standing = &self.runtime.standing_rules;
1517 let Some(rule) = standing.list(app, user).await?.into_iter().find(|rule| rule.id == id)
1518 else {
1519 return Ok(None);
1520 };
1521 let invalid = |message: String| {
1522 AdkError::new(
1523 ErrorComponent::Agent,
1524 ErrorCategory::InvalidInput,
1525 "harness.rule.invalid",
1526 message,
1527 )
1528 };
1529 let Some(end) = rule.expires_at else {
1530 return Err(invalid(
1531 "this rule has no end date: it applies until it is stopped, so there is \
1532 nothing to extend"
1533 .into(),
1534 ));
1535 };
1536 let earliest = end.max(chrono::Utc::now());
1537 if until <= earliest {
1538 return Err(invalid(format!(
1539 "a rule is extended to a later end than {}; stop allowing it to end it sooner",
1540 earliest.to_rfc3339()
1541 )));
1542 }
1543 if let Some(trail) = self.runtime.audit_trail() {
1544 let mut fields = crate::approvals::rule_audit_fields(&rule, None);
1545 fields["by"] = json!(user);
1546 fields["surface"] = json!(surface);
1547 fields["from"] = json!(end);
1548 fields["to"] = json!(until);
1549 HarnessAudit::new(
1550 trail.clone(),
1551 AuditActor::subject(adk_core::principal::SubjectRef::human(user)),
1552 rule.scope.session_id().unwrap_or_default(),
1553 )
1554 .record("harness.rule.extended", fields)
1555 .await?;
1556 }
1557 let extended = crate::StandingRule { expires_at: Some(until), ..rule };
1558 Ok(standing.replace(extended.clone()).await?.then_some(extended))
1559 }
1560}
1561
1562#[cfg(test)]
1563mod tests {
1564 use super::*;
1565
1566 fn nw() -> BTreeSet<String> {
1567 ["exit_plan_mode".to_string()].into_iter().collect()
1568 }
1569
1570 #[test]
1571 fn non_waivable_fingerprints_are_recognized() {
1572 let key = |tool: &str, args: &str| {
1573 format!("agent\u{1f}static\u{1f}sha256:x\u{1f}{tool}\u{1f}{args}")
1574 };
1575 let dir = tempfile::tempdir().unwrap();
1576 let root = std::fs::canonicalize(dir.path()).unwrap();
1577 let strip = |fingerprint: &str| names_non_waivable(fingerprint, &nw(), &[], &root);
1578 assert!(strip(&key("exit_plan_mode", "{}")));
1579 assert!(strip(&key("bash", r#"{"command":"ls","unsandboxed":true}"#)));
1580 assert!(!strip(&key("bash", r#"{"command":"ls"}"#)));
1581 assert!(strip(&key("write_file", r#"{"path":"AGENTS.md"}"#)));
1582 assert!(!strip(&key("write_file", r#"{"path":"src/a.rs"}"#)));
1583 let patch = |paths: &[&str]| {
1584 let body: String =
1585 paths.iter().map(|path| format!("*** Add File: {path}\n+x\n")).collect();
1586 serde_json::json!({ "patch": format!("*** Begin Patch\n{body}*** End Patch") })
1587 .to_string()
1588 };
1589 assert!(!strip(&key("apply_patch", &patch(&["src/a.rs", "src/b.rs"]))));
1590 assert!(strip(&key("apply_patch", &patch(&["src/a.rs", "AGENTS.md"]))));
1591 assert!(strip(&key("apply_patch", r#"{"patch":"not a patch"}"#)));
1592 assert!(strip("garbage"));
1593 }
1594
1595 #[test]
1596 fn a_crossing_tool_listed_at_request_time_is_non_waivable_by_its_prefix() {
1597 let key =
1598 |tool: &str| format!("agent\u{1f}driver:notes\u{1f}sha256:x\u{1f}{tool}\u{1f}{{}}");
1599 let root = std::path::Path::new("/");
1600 let prefixes = ["work__".to_string()];
1601 assert!(names_non_waivable(&key("work__read_note"), &nw(), &prefixes, root));
1602 assert!(!names_non_waivable(&key("read_note"), &nw(), &prefixes, root));
1603 assert!(!names_non_waivable(&key("home__read_note"), &nw(), &prefixes, root));
1604 }
1605
1606 #[cfg(unix)]
1607 #[test]
1608 fn an_approval_of_a_write_through_a_symlink_to_a_protected_file_is_stripped() {
1609 let key =
1610 |args: &str| format!("agent\u{1f}static\u{1f}sha256:x\u{1f}write_file\u{1f}{args}");
1611 let dir = tempfile::tempdir().unwrap();
1612 let root = std::fs::canonicalize(dir.path()).unwrap();
1613 std::fs::write(root.join("AGENTS.md"), "rules").unwrap();
1614 std::fs::create_dir(root.join(".git")).unwrap();
1615 std::fs::create_dir(root.join("docs")).unwrap();
1616 std::os::unix::fs::symlink("../AGENTS.md", root.join("docs/notes.md")).unwrap();
1617 std::os::unix::fs::symlink(".git", root.join("cfg")).unwrap();
1618 assert!(names_non_waivable(&key(r#"{"path":"docs/notes.md"}"#), &nw(), &[], &root));
1619 assert!(names_non_waivable(&key(r#"{"path":"cfg/hooks/pre-commit"}"#), &nw(), &[], &root));
1620 assert!(!names_non_waivable(&key(r#"{"path":"docs/other.md"}"#), &nw(), &[], &root));
1621 }
1622}