Skip to main content

adk_harness/
agent.rs

1//! `HarnessAgent`, its runtime, and the run-config layer (spec 3.1 §7.3).
2
3use 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
28/// Error code of a harness run without the harness policy in its run config (spec 3.1 §7.3).
29///
30/// # Example
31///
32/// ```rust
33/// assert_eq!(adk_harness::HARNESS_UNGOVERNED_CODE, "harness.ungoverned");
34/// ```
35pub const HARNESS_UNGOVERNED_CODE: &str = "harness.ungoverned";
36
37/// What a built harness is (spec 3.1 §7.3).
38///
39/// # Example
40///
41/// ```rust,ignore
42/// let info = harness.info();
43/// println!("{} in {} mode, shell: {}", info.name, info.default_mode, info.isolation);
44/// ```
45#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
46#[serde(rename_all = "camelCase")]
47pub struct HarnessInfo {
48    /// The agent name.
49    pub name: String,
50    /// The mode of sessions with no mode record.
51    pub default_mode: HarnessMode,
52    /// Where `bash` runs.
53    pub isolation: IsolationStatus,
54    /// Why a requested sandbox is unavailable.
55    pub degraded_reason: Option<String>,
56    /// Team members.
57    pub members: Vec<String>,
58    /// Active packs.
59    pub packs: Vec<String>,
60    /// The harness tools.
61    pub tools: Vec<String>,
62    /// The reasoning effort of each mode and role (spec 3.1 §7.23).
63    pub effort: crate::posture::EffortPolicy,
64    /// Whether a `cache_capable` model gets the runner's explicit context cache.
65    pub context_caching: bool,
66    /// Which path `web_search` takes (spec 3.1 §7.20).
67    pub web_search: crate::web::WebSearchPath,
68}
69
70impl HarnessInfo {
71    /// Where `bash` runs, or `None` when the harness offers no shell — as the personal
72    /// preset's does outside the OS sandbox or a container (spec 3.3 §10 H1). Surfaces show
73    /// this rather than [`isolation`](Self::isolation), which names the isolation the
74    /// harness was configured with whether or not it offers `bash`.
75    ///
76    /// # Example
77    ///
78    /// ```rust
79    /// use adk_harness::{HarnessAgent, InstructionsConfig, Preset};
80    /// use adk_model::{ScriptedLlm, ScriptedResponse};
81    /// use std::sync::Arc;
82    ///
83    /// let dir = tempfile::tempdir().unwrap();
84    /// let harness = HarnessAgent::builder("assistant")
85    ///     .preset(Preset::Personal)
86    ///     .model(Arc::new(ScriptedLlm::new("scripted", vec![ScriptedResponse::text("ok")])))
87    ///     .workspace(adk_devtools::Workspace::new(dir.path()).allow_bash(true))
88    ///     .project_instructions(InstructionsConfig { user_file: None, ..InstructionsConfig::default() })
89    ///     .build()?;
90    /// assert_eq!(harness.info().shell(), None, "no host shell");
91    /// # Ok::<(), adk_core::AdkError>(())
92    /// ```
93    pub fn shell(&self) -> Option<&IsolationStatus> {
94        self.tools.iter().any(|tool| tool == "bash").then_some(&self.isolation)
95    }
96}
97
98/// Project instructions with the trust they load under.
99#[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/// The governed services a harness applies to every run (spec 3.1 §7.3).
123///
124/// # Example
125///
126/// ```rust,ignore
127/// let rules = harness.runtime().standing_rules().list("adk-rust", "alice").await?;
128/// ```
129#[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    /// The reviewer of calls Auto mode holds, when auto review is on.
139    pub(crate) auto_review: Option<Arc<dyn adk_core::ToolReviewer>>,
140    /// Checks requested calls against their approval seals, when set.
141    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    /// When the harness's runs compact their history before a model call; `None` keeps the
150    /// runner's default, which is on.
151    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    /// Prefixes of tool names no run-wide approval answers: the coordinator's crossing tools
156    /// listed at request time, `<to>__` for each partition it crosses into (spec 3.2 K-I15).
157    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    /// Snapshots and rewind (spec 3.1 §7.27).
171    pub(crate) snapshots: Option<Arc<crate::snapshot::Snapshots>>,
172    pub(crate) goals: crate::goal::GoalRuntime,
173    /// Reports approval outcomes to the kernel built by `Harness::kernel` (spec 3.2 §7.4).
174    #[cfg(feature = "kernel")]
175    pub(crate) kernel_approvals: Arc<crate::kernel::LateApprovalNotifier>,
176    /// The agenda of the kernel built by `Harness::kernel`, for `propose_followup` (spec 3.2
177    /// §7.5).
178    #[cfg(feature = "kernel")]
179    pub(crate) kernel_agenda: adk_kernel::AgendaHandle,
180    /// The kernel's ledger, bound when a kernel built by `Harness::kernel` starts (spec 3.2
181    /// §7.10).
182    #[cfg(feature = "kernel")]
183    pub(crate) kernel_ledger: adk_kernel::proc::LateLedgerSink,
184    /// The partition the harness was built for and its policy (spec 3.2 §7.8).
185    #[cfg(feature = "kernel")]
186    pub(crate) partition: Option<crate::partition::PartitionWiring>,
187    /// The kernel target the harness stamps its sessions with (spec 3.3 §5.7 "Threads").
188    #[cfg(feature = "kernel")]
189    pub(crate) session_stamp: Option<String>,
190    /// Provider-executed search and URL tools, when the operator enabled any (spec 3.1 §7.20).
191    #[cfg(feature = "web")]
192    pub(crate) provider_web: Option<Arc<crate::web::provider::ProviderWebToolset>>,
193    /// MCP servers and the bridges answering them (spec 3.1 §7.21).
194    #[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    /// The model whose context the runner caches explicitly, when caching is on.
200    // Read by `configure_runner`, which exists with feature `runner` only.
201    #[cfg_attr(not(feature = "runner"), allow(dead_code))]
202    pub(crate) cache_capable: Option<Arc<dyn adk_core::CacheCapable>>,
203    /// The payments pack's per-request reminder (spec 3.1 §7.16).
204    #[cfg(feature = "payments")]
205    pub(crate) payments: Option<Arc<crate::packs::payments::PaymentsReminder>>,
206    /// The computer-use pack's screen plans, decided from a surface's card when a held step
207    /// parks (spec 3.7 Q8).
208    #[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    /// Take over, when the harness was built with it (spec 3.3 §10 H2).
212    pub(crate) take_over: Option<crate::take_over::TakeOver>,
213    /// The tools and toolsets the model is given besides `toolset`, for a realtime session
214    /// of the harness (spec 3.3 §5.6).
215    #[cfg_attr(not(feature = "voice"), allow(dead_code))]
216    pub(crate) agent_tools: AgentTools,
217}
218
219/// The tools and toolsets the model is given besides the harness toolset.
220pub(crate) type AgentTools = (Vec<Arc<dyn adk_core::Tool>>, Vec<Arc<dyn adk_core::Toolset>>);
221
222/// The harness's audit trail, in Block mode: `recorder`, or with feature `auth` an
223/// [`EphemeralAuditLog`](crate::EphemeralAuditLog) (spec 3.1 §9.2 I39).
224pub(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    /// The layer `configure_run` applies.
248    pub fn layer(&self) -> HarnessLayer<'_> {
249        HarnessLayer { runtime: self }
250    }
251
252    /// The harness policy.
253    pub fn policy(&self) -> &HarnessPolicy {
254        &self.policy
255    }
256
257    /// Where session modes are kept.
258    pub fn mode_store(&self) -> &Arc<dyn ModeStore> {
259        &self.mode_store
260    }
261
262    /// Where standing rules are kept.
263    pub fn standing_rules(&self) -> &Arc<dyn StandingRuleStore> {
264        &self.standing_rules
265    }
266
267    /// The per-session shell ledger.
268    pub fn shell_ledger(&self) -> &Arc<dyn ShellLedger> {
269        &self.ledger
270    }
271
272    /// Where held calls and their decisions are kept.
273    pub fn approval_store(&self) -> &Arc<dyn ApprovalStore> {
274        &self.approval_store
275    }
276
277    /// The approval inbox, if configured.
278    pub fn approval_service(&self) -> Option<&Arc<dyn ApprovalService>> {
279        self.approval_service.as_ref()
280    }
281
282    /// The reviewer of calls Auto mode holds, when auto review is on
283    /// ([`HarnessAgentBuilder::auto_review`](crate::HarnessAgentBuilder::auto_review)).
284    pub fn auto_review(&self) -> Option<&Arc<dyn adk_core::ToolReviewer>> {
285        self.auto_review.as_ref()
286    }
287
288    /// Take over (spec 3.3 §8.2, §10 H2), when the harness was built with it: surfaces answer
289    /// a take-over entry through it.
290    pub fn take_over(&self) -> Option<&crate::take_over::TakeOver> {
291        self.take_over.as_ref()
292    }
293
294    /// Where non-idempotent calls are recorded when a run carries no ledger of its own
295    /// (spec 3.1 §7.12).
296    pub fn action_ledger(&self) -> &Arc<dyn adk_core::ActionLedger> {
297        self.ledgers.store()
298    }
299
300    /// The live confirmation handler: the configured one, or the prompting handler over
301    /// the configured prompter.
302    pub fn confirmation_handler(&self) -> Option<&Arc<dyn ToolConfirmationHandler>> {
303        self.handler.as_ref()
304    }
305
306    /// The harness toolset.
307    pub fn toolset(&self) -> &Arc<HarnessToolset> {
308        &self.toolset
309    }
310
311    /// The workspace's instruction files.
312    pub fn instructions(&self) -> &ProjectInstructions {
313        &self.instructions.instructions
314    }
315
316    /// Where workspace trust decisions are kept.
317    pub fn trust_store(&self) -> &Arc<dyn WorkspaceTrustStore> {
318        &self.instructions.trust_store
319    }
320
321    /// Whether the workspace's project instruction files load.
322    pub fn workspace_trusted(&self) -> bool {
323        self.instructions.trusted()
324    }
325
326    /// The workspace the harness works in.
327    pub fn workspace(&self) -> &Workspace {
328        &self.workspace
329    }
330
331    /// The events compaction the harness asks its runner for.
332    pub fn compaction(&self) -> Option<&EventsCompactionConfig> {
333        self.compaction.as_ref()
334    }
335
336    /// When the harness's runs compact their history before a model call, when set on the
337    /// builder; `None` keeps the runner's auto-compaction, which is on.
338    pub fn intra_compaction(&self) -> Option<&adk_core::IntraCompactionConfig> {
339        self.intra_compaction.as_ref()
340    }
341
342    /// The spend of `subject`, or of every subject, since the harness was built: per
343    /// acting agent, subject and vendor (spec 3.1 §7.13).
344    #[cfg(feature = "observe")]
345    pub fn spend(&self, subject: Option<&str>) -> crate::observe::SpendReport {
346        self.spend.report(subject)
347    }
348
349    /// The audit trail a run gets when it carries none (spec 3.1 §7.14, §9.2 I39).
350    pub fn audit_trail(&self) -> Option<&adk_core::audit_log::AuditTrail> {
351        self.audit.as_ref()
352    }
353
354    /// Reads MCP resource `uri` of `server` for an explicit `@server:resource` mention by
355    /// `user` in `session` of `app`: the delimited untrusted block, recorded as
356    /// `harness.mcp.resource.read` with `via: mention` (spec 3.1 §7.21, I52).
357    ///
358    /// # Errors
359    ///
360    /// `harness.mcp.unknown_server`, the server's error, or the audit error.
361    #[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    /// The MCP servers and bridges, when the harness has any (spec 3.1 §7.21).
389    #[cfg(feature = "mcp")]
390    pub fn mcp(&self) -> Option<&Arc<crate::mcp::McpInteractionRuntime>> {
391        self.mcp.as_ref()
392    }
393
394    /// The compiled team, when the harness has members (spec 3.1 §7.10).
395    #[cfg(feature = "team")]
396    pub fn team(&self) -> Option<&crate::team::HarnessTeam> {
397        self.team.as_deref()
398    }
399
400    /// Where session goals are kept (spec 3.1 §7.11).
401    pub fn goal_store(&self) -> &Arc<dyn crate::goal::GoalStore> {
402        &self.goals.store
403    }
404
405    /// The plan graphs, when `plan_graph` is on (spec 3.1 §7.11).
406    #[cfg(feature = "graph")]
407    pub fn plan_graph(&self) -> Option<&Arc<crate::plan_graph::PlanGraphs>> {
408        self.plan_graph.as_ref()
409    }
410
411    /// The workspace's snapshots, when the harness takes them (spec 3.1 §7.27):
412    /// [`Snapshots::take`](crate::snapshot::Snapshots::take) is "snapshot now" for a governed
413    /// path that is about to do something a file restore must be able to undo (§7.30).
414    pub fn snapshots(&self) -> Option<&Arc<crate::snapshot::Snapshots>> {
415        self.snapshots.as_ref()
416    }
417
418    /// The hooks the harness runs, when any are configured (spec 3.1 §7.22).
419    #[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/// What `HarnessAgent::configure_run` applies to a run's config (spec 3.1 §7.3).
426///
427/// | Rule | Effect |
428/// |---|---|
429/// | Compose, never replace | the run's policy and the operator policy are kept; the strictest decision wins |
430/// | Idempotent | a config that already carries this harness's layer is left as it is; a policy that only names itself `adk-harness` is composed with it |
431/// | Approvals | the approval service and store are filled only when empty or identical; otherwise the run's own are kept with a warning |
432/// | Action ledger | the harness's ledger when the run carries none; a run's own keeps the records, with resumed held calls keyed alike (spec 3.1 §7.12) |
433/// | Non-waivable | `tool_approvals` entries naming non-waivable calls are removed |
434/// | Auto review | the harness's reviewer, limited to what Auto mode holds, when the run carries none |
435/// | Run-owned fields | `durable_run_id`, the confirmation handler and call-ID decisions are never touched |
436///
437/// # Example
438///
439/// ```rust,ignore
440/// let mut config = adk_core::RunConfig::default();
441/// harness.runtime().layer().apply(&mut config);
442/// assert!(adk_harness::has_harness_layer(config.tool_policy.as_deref().unwrap()));
443/// ```
444#[derive(Clone, Copy)]
445pub struct HarnessLayer<'a> {
446    runtime: &'a HarnessRuntime,
447}
448
449/// Whether the `tool_approvals` key `fingerprint` names a call no fingerprint approval may
450/// authorize (spec 3.1 §7.3, §9.2 I7). Anything that does not parse is removed too. An
451/// edit's path is judged at the target it resolves to under `root` (I11, I29).
452pub(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        // A protected path anywhere in a patch makes the whole call non-waivable (I67).
474        "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    /// Applies the layer to `config`.
485    pub fn apply(&self, config: &mut RunConfig) {
486        self.apply_with(config, true);
487    }
488
489    /// Applies the layer; `compose_policy` false leaves the policy to `configure_run`,
490    /// which binds it to the run's audit trail.
491    fn apply_with(&self, config: &mut RunConfig, compose_policy: bool) {
492        let runtime = self.runtime;
493        // Before the policy is composed, which binds it to the run's trail. The runner path
494        // installs the trail through `RunnerConfigBuilder::audit_log` instead, so a
495        // runner's own log takes precedence.
496        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            // A runner's own audit log also feeds a bound kernel ledger (spec 3.2 §7.10);
504            // the harness's trail was tapped when it was built. Before the policy binds it.
505            #[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        // Auto review: the reviewer sees only what Auto mode holds and a rule could answer.
543        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        // Non-idempotent harness calls run at most once across crashes, retries and resumes
580        // (§7.12, I37); a ledger the run carries keeps the records. Per run only, like the
581        // policy: a runner installs its own ledger on a run config that carries none.
582        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        // A tracker counts one run (spec 3.1 §7.13): the run's own config gets one here; a
611        // runner's base config carries the budget only, and the runner creates a tracker
612        // per run from it.
613        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
635/// The harness agent: a governed `LlmAgent` with the harness policy, approvals and tools
636/// (spec 3.1 §7.3).
637///
638/// `configure_run` carries the policy and approvals into every runtime that runs it — a
639/// `Runner`, a transfer, a delegate behind an agent tool — without changing them. `run`
640/// refuses unless its policy is in the run's config, because the runner calls
641/// `configure_run` on the root agent only (spec 3.1 §9.2 I17).
642///
643/// # Example
644///
645/// ```rust,ignore
646/// use adk_harness::HarnessAgent;
647///
648/// let harness = HarnessAgent::builder("harness")
649///     .model(model)
650///     .workspace(adk_devtools::Workspace::new(".").allow_bash(true))
651///     .build()?;
652/// let harness = harness.into_harness("adk-rust", sessions)?;
653/// ```
654pub 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    /// Starts building a harness named `name`.
669    ///
670    /// # Example
671    ///
672    /// ```rust
673    /// let builder = adk_harness::HarnessAgent::builder("harness");
674    /// # let _ = builder;
675    /// ```
676    pub fn builder(name: impl Into<String>) -> crate::HarnessAgentBuilder {
677        crate::HarnessAgentBuilder::new(name)
678    }
679
680    /// The harness as an `Arc<dyn Agent>`, to hand to any runtime: it applies the harness
681    /// layer in `configure_run` and refuses to run without it.
682    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    /// The governed services.
692    pub fn runtime(&self) -> &HarnessRuntime {
693        &self.runtime
694    }
695
696    /// What the harness is.
697    pub fn info(&self) -> &HarnessInfo {
698        &self.info
699    }
700
701    /// What the harness can do, as the model is told it (spec 3.1 §7.25): generated when
702    /// the harness was built from its classes in each mode, its tools, packs, memory, the
703    /// surface's commands and what its safety mechanisms cover.
704    ///
705    /// # Example
706    ///
707    /// ```rust
708    /// use adk_harness::{HarnessAgent, InstructionsConfig, ModeDecision};
709    /// use adk_model::{ScriptedLlm, ScriptedResponse};
710    /// use std::sync::Arc;
711    ///
712    /// let dir = tempfile::tempdir().unwrap();
713    /// let harness = HarnessAgent::builder("assistant")
714    ///     .model(Arc::new(ScriptedLlm::new("scripted", vec![ScriptedResponse::text("ok")])))
715    ///     .workspace(adk_devtools::Workspace::new(dir.path()))
716    ///     .project_instructions(InstructionsConfig { user_file: None, ..InstructionsConfig::default() })
717    ///     .build()?;
718    /// let edit = harness.manifest().classes.iter().find(|class| class.class == "edit").unwrap();
719    /// assert_eq!(edit.decisions[2], ModeDecision::Ask, "ask mode asks before an edit");
720    /// # Ok::<(), adk_core::AdkError>(())
721    /// ```
722    pub fn manifest(&self) -> &crate::manifest::HarnessManifest {
723        &self.manifest
724    }
725
726    /// The partition the harness was built for (spec 3.2 §7.8,
727    /// [`HarnessAgentBuilder::partition`](crate::HarnessAgentBuilder::partition)).
728    #[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    /// The partition's policy, when the harness was built for one: what decides its
734    /// crossings (spec 3.2 §7.8, K-I15).
735    #[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    /// A run config carrying the harness layer and the confirmation handler, for callers
746    /// wiring their own `Runner`. Its policy records no `harness.*` audit records; with the
747    /// harness at the root of the runner, `configure_run` binds the run's audit trail.
748    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    /// `root` as the root agent of a `Runner` under this harness's layer (spec 3.1 §7.10):
758    /// a review round from [`HarnessTeam::review_round_with`](crate::HarnessTeam::review_round_with),
759    /// or any agent built from the harness's members.
760    ///
761    /// Its `configure_run` applies `root`'s own configuration and then
762    /// [`HarnessRuntime::layer`], so every tool call `root`'s agents make goes through
763    /// `authorize_tool_call` under the harness policy and mode, with the run's audit trail,
764    /// approvals and budget, and the members record `harness.member.*` in that trail. It
765    /// refuses to run without that layer, as the harness does (spec 3.1 §9.2 I17), and with
766    /// feature `observe` meters the run into [`HarnessRuntime::spend`] and records
767    /// `harness.spend`. It never transfers: the runner always starts at `root`. Its name,
768    /// description and sub-agents are `root`'s.
769    ///
770    /// # Example
771    ///
772    /// ```rust,ignore
773    /// use adk_runner::Runner;
774    ///
775    /// let team = harness.runtime().team().expect("the harness has members");
776    /// let round = team.review_round("review", &["review_correctness", "review_style"], 1)?;
777    /// let runner = harness
778    ///     .configure_runner(
779    ///         Runner::builder().app_name("app").agent(harness.governed_root(round)).session_service(sessions),
780    ///     )
781    ///     .build()?;
782    /// ```
783    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    /// Applies the harness run config, approval store and compaction to a runner builder.
793    /// Call it before setting a run config of your own on the builder.
794    ///
795    /// A budget set with [`HarnessAgentBuilder::budget`](crate::HarnessAgentBuilder::budget)
796    /// bounds each run on its own: the runner's base config carries the budget and the
797    /// runner counts every run against fresh counters (spec 3.1 §7.13).
798    #[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        // The policy is composed per run by `configure_run`, which binds it to the run's
804        // audit trail; a policy composed here would carry none.
805        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        // Explicit context caching for a model that supports it (spec 3.1 §7.23).
819        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    /// The reasoning effort of each mode and model role (spec 3.1 §7.23).
828    pub fn effort(&self) -> &crate::posture::EffortPolicy {
829        &self.runtime.effort
830    }
831
832    /// The todo list of `session` (spec 3.1 §7.6).
833    pub fn todos(&self, session: &dyn Session) -> TodoList {
834        TodoList::from_state(session.state())
835    }
836
837    /// Wraps the harness in a [`Harness`](crate::Harness) that owns a `Runner` over
838    /// `sessions` (spec 3.1 §7.3).
839    ///
840    /// # Errors
841    ///
842    /// Returns the runner's error when `app_name` is invalid.
843    #[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    // The builder name, with or without members: the acting principal, fingerprints and
856    // standing rules stay the same when a team is added (spec 3.1 §7.10).
857    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    // The root consumes the run's runtime toolsets under the harness's policy, so a
874    // `TeamSpec` whose coordinator is a harness compiles its delegate edges (spec 3.5
875    // §7.19); handoff follows the harness's own transfer support.
876    fn capabilities(&self) -> AgentCapabilities {
877        AgentCapabilities { handoff: self.supports_agent_transfer(), ..self.root.capabilities() }
878    }
879
880    // With members, every turn starts at the harness, never at a member the runner found
881    // in history: members run only as isolated delegations (spec 3.1 §7.10).
882    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    /// Starts the MCP servers the first run would start, under the same trust rule, then
900    /// prewarms the root's model.
901    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        // A partition's harness runs only its own partition's sessions (spec 3.2 K-I15).
911        #[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        // A thread belongs to one agent: the agent's harness stamps it on its first run and
917        // every other agent refuses it (spec 3.3 §5.7 "Threads").
918        #[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        // A run that starts in Ask or Auto with a provider-executed web tool declared
924        // records that an ungoverned fetch path was live (spec 3.1 §7.20, I49).
925        #[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        // Operator-declared MCP servers start with the first run; workspace-declared ones
930        // only under workspace trust (spec 3.1 §7.21, I3).
931        #[cfg(feature = "mcp")]
932        if let Some(mcp) = &self.runtime.mcp {
933            mcp.ensure_started(self.runtime.workspace_trusted()).await;
934        }
935        // The workspace as it was before this turn, so /rewind can restore it (spec 3.1 §7.27).
936        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        // What a provider-executed search ran is recorded after each response
952        // (spec 3.1 §7.20).
953        #[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    /// Keeps the `harness:mode` display mirror equal to the mode store (spec 3.1 §6 D-3):
981    /// re-asserts it when the run starts and replaces any value an event of the run writes,
982    /// so neither a client `stateDelta` nor a tool's `state_delta` misreports the mode.
983    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        // A session that never had a mirror needs none; one that disagrees with the store
1002        // was written by something other than the harness.
1003        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        // Bound to this harness's own layer, not to a policy that names itself the harness.
1040        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        // Long-term memory reads the run's audit trail and budget, and counts user turns
1073        // for distillation (spec 3.1 §7.15.2).
1074        #[cfg(feature = "memory")]
1075        if let Some(facts) = self.runtime.toolset.facts() {
1076            facts.observe_invocation(ctx.as_ref());
1077        }
1078        // The payments reminder names the run's remaining budget (spec 3.1 §7.16).
1079        #[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            // A trust decision made on other files than these no longer applies (spec 3.4 P2).
1089            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        // OnSessionStart hooks run once per session; their notes join the <environment> block
1122        // of every run of the session (spec 3.1 §7.22).
1123        #[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        // OnHold and OnStop hooks observe the turn; their notes reach the user as events
1166        // without content, never the model (spec 3.1 §7.22).
1167        #[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
1183/// An agent run as a runner root under a harness's layer (spec 3.1 §7.10); built by
1184/// [`HarnessAgent::governed_root`].
1185struct 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    /// One turn: the session's running goal, then its running plan, step by step, else the
1280    /// harness agent (spec 3.1 §7.11).
1281    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
1302/// The error of a standing rule that cannot be created for a call.
1303fn rule_refused(message: &str) -> AdkError {
1304    AdkError::new(
1305        ErrorComponent::Agent,
1306        ErrorCategory::InvalidInput,
1307        "harness.decision.invalid",
1308        message,
1309    )
1310}
1311
1312/// Standing rules created and revoked by a person outside a prompt: `Harness::decide`, a
1313/// served harness's authenticated REST routes (spec 3.1 §7.5, §8.2).
1314impl HarnessAgent {
1315    /// The rule `suggestion` becomes for the held call `request`, owned by `owner`
1316    /// (spec 3.1 §7.5, §9.2 I2, I8).
1317    ///
1318    /// The suggestion must pin the call's tool and exact declaration; an allow rule must be
1319    /// one [`StandingRule::suggestions`](crate::StandingRule::suggestions) offers for the
1320    /// call; a call no rule covers — plan exit, a payment, a memory write, a desktop action,
1321    /// a protected or other non-waivable edit — gets none.
1322    ///
1323    /// # Example
1324    ///
1325    /// ```rust,ignore
1326    /// let suggestion = StandingRule::suggestions(&held.request).remove(0);
1327    /// let rule = harness.rule_for_held_call(&held.request, suggestion, StandingDecision::Allow, &owner)?;
1328    /// harness.grant_rule(rule, "rest", Some(&held.request)).await?;
1329    /// ```
1330    ///
1331    /// # Errors
1332    ///
1333    /// Returns `harness.decision.invalid` when the call records no tool origin or no rule
1334    /// may be created from `suggestion` for it.
1335    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        // "Always allow for this folder": the harness's file-writing tools, each pinned to
1365        // its declaration (spec 3.3 §8.2).
1366        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    /// The rule "Always allow for this folder" makes for the held call `request`
1386    /// (spec 3.3 §8.2): every call of this harness's file-writing tools — `write_file`,
1387    /// `edit_file`, and an `apply_patch` that adds files or updates them in place — whose
1388    /// paths all lie within the folder `request` writes in, each tool pinned to its exact
1389    /// declaration, for the session. Paths outside the folder, `..` and symlink escapes,
1390    /// protected paths, deletes, moves, the shell and every other tool still ask.
1391    ///
1392    /// `None` when `request` is not a file write of this harness's own tools: another tool,
1393    /// another declaration, a delete or a move, a protected path or a path with `..`.
1394    /// [`rule_for_held_call`](Self::rule_for_held_call) makes the rule from it.
1395    ///
1396    /// # Example
1397    ///
1398    /// ```rust,ignore
1399    /// let folder = harness.folder_suggestion(&held.request).expect("a file write");
1400    /// assert_eq!(folder.label, "file writes: within notes/");
1401    /// let rule = harness.rule_for_held_call(&held.request, folder, StandingDecision::Allow, &owner)?;
1402    /// harness.grant_rule(rule, "web", Some(&held.request)).await?;
1403    /// ```
1404    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    /// Stores `rule`, recording `harness.rule.created` with `surface` (such as `rest`) in
1412    /// the harness's audit trail before the store write (spec 3.1 §7.5, §9.3, I39).
1413    /// `from` is the held call the rule was created from, if any.
1414    ///
1415    /// The caller authenticates the person the rule's scope and `created_by` name; a rule
1416    /// is never created for a model-callable tool's request (spec 3.1 §9.2 I2, I5).
1417    ///
1418    /// # Example
1419    ///
1420    /// ```rust,ignore
1421    /// let granted = harness.grant_rule(rule, "rest", None).await?;
1422    /// ```
1423    ///
1424    /// # Errors
1425    ///
1426    /// Returns the audit log's error, and then stores nothing, or the store's error.
1427    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    /// Revokes the rule `id` of `user` in `app`, recording `harness.rule.revoked` with
1451    /// `surface` before the store write (spec 3.1 §7.5, §9.2 I4, §9.3). Returns the revoked
1452    /// rule, or `None` when `user` has no rule `id`, so a person revokes only their own.
1453    ///
1454    /// # Example
1455    ///
1456    /// ```rust,ignore
1457    /// let revoked = harness.revoke_rule("adk-rust", "ana", &rule.id, "rest").await?;
1458    /// ```
1459    ///
1460    /// # Errors
1461    ///
1462    /// Returns the audit log's error, and then revokes nothing, or the store's error.
1463    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    /// Moves the end of the rule `id` of `user` in `app` to `until`, recording
1491    /// `harness.rule.extended` with `surface`, the old end and the new one before the store
1492    /// write (spec 3.3 §8.1 "Allowed without asking — Extend", spec 3.1 §9.3). Returns the
1493    /// rule after it, or `None` when `user` has no rule `id` or it was revoked meanwhile: an
1494    /// extension never brings a revoked rule back.
1495    ///
1496    /// # Example
1497    ///
1498    /// ```rust,ignore
1499    /// let until = chrono::Utc::now() + chrono::Duration::days(30);
1500    /// let extended = harness.extend_rule("adk-rust", "ana", &rule.id, until, "rest").await?;
1501    /// ```
1502    ///
1503    /// # Errors
1504    ///
1505    /// Returns `harness.rule.invalid` when the rule has no end date, or `until` is not later
1506    /// than both its end and now; the audit log's error, and then changes nothing; or the
1507    /// store's error.
1508    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}