Skip to main content

adk_harness/approvals/
prompt.rs

1//! Interactive approval prompts (spec 3.1 §7.5).
2
3use std::fmt;
4use std::sync::Arc;
5use std::sync::atomic::{AtomicBool, Ordering};
6
7use adk_core::principal::{SubjectKind, SubjectRef};
8use adk_core::{
9    PolicyCall, PolicyDecision, Result, ToolApproval, ToolConfirmationDecision,
10    ToolConfirmationHandler, ToolConfirmationRequest, async_trait,
11};
12use serde_json::{Value, json};
13use tokio::sync::Mutex;
14
15use super::changeset::{ChangeSetAnswer, ChangeSetPrompt};
16use super::matcher::glob_matches;
17use super::rule::{
18    OriginPin, RuleOwner, RulePredicate, RuleSuggestion, StandingDecision, StandingRule,
19};
20use super::store::StandingRuleStore;
21use crate::mode::HarnessMode;
22use crate::policy::{HarnessPolicy, PromptContext, ToolKind};
23use crate::shell::IsolationStatus;
24
25/// A standing rule that allowed a call without asking (spec 3.1 §7.33 fix 3).
26///
27/// # Example
28///
29/// ```rust
30/// let hit = adk_harness::RuleHit::new("r1", Some(3), "bash", "bash: cargo test …");
31/// assert_eq!(hit.to_string(), "[allowed by rule 3] bash: cargo test …");
32/// ```
33#[derive(Clone, Debug, PartialEq, Eq)]
34#[non_exhaustive]
35pub struct RuleHit {
36    /// The rule's id.
37    pub rule_id: String,
38    /// The rule's number as `/rules` lists it: every rule of the user, oldest first.
39    pub number: Option<usize>,
40    /// The tool the call was made to.
41    pub tool: String,
42    /// What the rule matches.
43    pub label: String,
44    /// The function call id of the call the rule allowed, so a surface can show the hit
45    /// after the call's own line.
46    pub function_call_id: Option<String>,
47}
48
49impl RuleHit {
50    /// A rule hit.
51    pub fn new(
52        rule_id: impl Into<String>,
53        number: Option<usize>,
54        tool: impl Into<String>,
55        label: impl Into<String>,
56    ) -> Self {
57        Self {
58            rule_id: rule_id.into(),
59            number,
60            tool: tool.into(),
61            label: label.into(),
62            function_call_id: None,
63        }
64    }
65
66    /// The hit for the call with function call id `id`.
67    ///
68    /// # Example
69    ///
70    /// ```rust
71    /// let hit = adk_harness::RuleHit::new("r1", Some(3), "bash", "bash: cargo test …")
72    ///     .with_function_call_id("call-1");
73    /// assert_eq!(hit.function_call_id.as_deref(), Some("call-1"));
74    /// ```
75    pub fn with_function_call_id(mut self, id: impl Into<String>) -> Self {
76        self.function_call_id = Some(id.into());
77        self
78    }
79}
80
81/// `[allowed by rule N] <tool>: <label>`, the label alone when it already names the tool.
82impl fmt::Display for RuleHit {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        match self.number {
85            Some(number) => write!(f, "[allowed by rule {number}] ")?,
86            None => write!(f, "[allowed by a standing rule] ")?,
87        }
88        if self.label.starts_with(&format!("{}:", self.tool)) {
89            write!(f, "{}", self.label)
90        } else {
91            write!(f, "{}: {}", self.tool, self.label)
92        }
93    }
94}
95
96/// Asks a person to decide one held call (spec 3.1 §7.5).
97///
98/// Implemented by interactive surfaces: a terminal, an editor, a chat channel.
99///
100/// # Example
101///
102/// ```rust
103/// use adk_harness::{ApprovalPrompt, ApprovalPrompter, PromptAnswer};
104///
105/// /// Approves everything once; for tests.
106/// #[derive(Debug)]
107/// struct Yes;
108///
109/// #[async_trait::async_trait]
110/// impl ApprovalPrompter for Yes {
111///     async fn prompt(&self, _prompt: ApprovalPrompt) -> adk_core::Result<PromptAnswer> {
112///         Ok(PromptAnswer::ApproveOnce)
113///     }
114/// }
115/// ```
116#[async_trait]
117pub trait ApprovalPrompter: fmt::Debug + Send + Sync {
118    /// Shows `prompt` and returns the person's answer.
119    async fn prompt(&self, prompt: ApprovalPrompt) -> Result<PromptAnswer>;
120
121    /// Tells the person a standing rule allowed a call the mode would have asked about, so
122    /// the call does not run unannounced (spec 3.1 §7.33 fix 3). The policy calls it for a
123    /// call a rule allows when it is evaluated, and the handler when a rule granted for an
124    /// earlier call of the batch answers a held one. The default shows nothing.
125    fn rule_applied(&self, hit: &RuleHit) {
126        let _ = hit;
127    }
128
129    /// Shows a change set — two or more held edits of one model turn as one diff — and
130    /// returns the person's one answer (spec 3.1 §7.26). `None`, the default, has the
131    /// handler ask about each call on its own, as a prompter that shows one call at a time
132    /// needs.
133    ///
134    /// # Errors
135    ///
136    /// Returns the prompter's error.
137    async fn prompt_change_set(&self, prompt: ChangeSetPrompt) -> Result<Option<ChangeSetAnswer>> {
138        let _ = prompt;
139        Ok(None)
140    }
141
142    /// Shows a screen plan — up to N previewed desktop actions in one window — and returns
143    /// the person's one answer for all its steps (spec 3.7 Q8). `None`, the default, has the
144    /// handler ask about each `computer_use_execute` on its own, as a prompter that shows
145    /// one call at a time needs.
146    ///
147    /// # Errors
148    ///
149    /// Returns the prompter's error.
150    #[cfg(feature = "computer-use")]
151    async fn prompt_screen_plan(
152        &self,
153        prompt: super::ScreenPlanPrompt,
154    ) -> Result<Option<super::ScreenPlanAnswer>> {
155        let _ = prompt;
156        Ok(None)
157    }
158
159    /// Shows a partition crossing (spec 3.2 §7.8) and returns the person's answer: "allow
160    /// this read of *X* for this run" (once, for a change), "deny", or "deny and block
161    /// crossings to *X* from this partition".
162    ///
163    /// The default shows the call through [`prompt`](Self::prompt) with a title naming the
164    /// crossing and maps the answer with
165    /// [`CrossingAnswer::from_prompt_answer`](crate::CrossingAnswer::from_prompt_answer).
166    ///
167    /// # Errors
168    ///
169    /// Returns the prompter's error.
170    #[cfg(feature = "kernel")]
171    async fn prompt_crossing(
172        &self,
173        prompt: crate::partition::CrossingPrompt,
174    ) -> Result<crate::partition::CrossingAnswer> {
175        let mut call = prompt.call;
176        call.rendered.title =
177            format!("Partition crossing into {}: {}", prompt.crossing.label(), call.rendered.title);
178        Ok(crate::partition::CrossingAnswer::from_prompt_answer(self.prompt(call).await?))
179    }
180}
181
182/// What a prompt shows (spec 3.1 §7.5, §9.2 I21).
183///
184/// # Example
185///
186/// ```rust,ignore
187/// println!("{}\n{}", prompt.rendered.title, prompt.rendered.body);
188/// ```
189#[derive(Clone, Debug)]
190pub struct ApprovalPrompt {
191    /// The held call, with its final arguments, acting agent and origin.
192    pub request: ToolConfirmationRequest,
193    /// The call's class.
194    pub kind: ToolKind,
195    /// The session's mode.
196    pub mode: HarnessMode,
197    /// Where `bash` runs.
198    pub isolation: IsolationStatus,
199    /// Rules the person may choose to remember.
200    pub suggestions: Vec<RuleSuggestion>,
201    /// The call rendered for display.
202    pub rendered: RenderedCall,
203}
204
205/// A person's answer to an [`ApprovalPrompt`] (spec 3.1 §7.5).
206///
207/// # Example
208///
209/// ```rust
210/// use adk_harness::PromptAnswer;
211///
212/// let answer = PromptAnswer::Deny { message: Some("use the staging database".into()) };
213/// assert!(matches!(answer, PromptAnswer::Deny { .. }));
214/// ```
215#[derive(Clone, Debug, PartialEq)]
216pub enum PromptAnswer {
217    /// Run this call once.
218    ApproveOnce,
219    /// Run this call once with these arguments; the policy checks them again.
220    ApproveWithArgs(Value),
221    /// Run this call and remember the rule.
222    ApproveAndRemember(RuleSuggestion),
223    /// Do not run this call.
224    Deny {
225        /// Reported to the model.
226        message: Option<String>,
227    },
228    /// Do not run this call and remember a Deny rule.
229    DenyAndRemember(RuleSuggestion),
230    /// Do not run this call or any other call of this turn.
231    DenyAllRemaining,
232}
233
234/// Default byte budget of [`RenderedCall::body`] (spec 3.1 §7.5).
235///
236/// # Example
237///
238/// ```rust
239/// assert_eq!(adk_harness::RENDERED_CALL_MAX_BYTES, 4096);
240/// ```
241pub const RENDERED_CALL_MAX_BYTES: usize = 4096;
242/// Most characters of a model-supplied retry reason a prompt shows.
243const REASON_MAX_CHARS: usize = 300;
244
245/// Escapes control characters, including ANSI escapes, carriage returns and bidi
246/// overrides, so a prompt shows exactly what runs (spec 3.1 §9.1 "Approval UX").
247///
248/// # Example
249///
250/// ```rust
251/// use adk_harness::escape_control;
252///
253/// assert_eq!(escape_control("ls\r; curl evil\x1b[2K"), "ls\\r; curl evil\\x1b[2K");
254/// assert_eq!(escape_control("a\u{202e}b"), "a\\u{202e}b");
255/// ```
256pub fn escape_control(text: &str) -> String {
257    let mut out = String::with_capacity(text.len());
258    for c in text.chars() {
259        match c {
260            '\n' => out.push_str("\\n"),
261            '\r' => out.push_str("\\r"),
262            '\t' => out.push_str("\\t"),
263            '\\' => out.push_str("\\\\"),
264            c if (c as u32) < 0x20 || (0x7f..0xa0).contains(&(c as u32)) => {
265                out.push_str(&format!("\\x{:02x}", c as u32));
266            }
267            '\u{200b}'..='\u{200f}'
268            | '\u{202a}'..='\u{202e}'
269            | '\u{2066}'..='\u{2069}'
270            | '\u{feff}' => {
271                out.push_str(&format!("\\u{{{:04x}}}", c as u32));
272            }
273            c => out.push(c),
274        }
275    }
276    out
277}
278
279fn cut(text: &str, max_bytes: usize) -> (String, bool) {
280    if text.len() <= max_bytes {
281        return (text.to_string(), false);
282    }
283    let end = text.floor_char_boundary(max_bytes);
284    (format!("{}… [truncated: {} of {} bytes shown]", &text[..end], end, text.len()), true)
285}
286
287/// A held call rendered for a person (spec 3.1 §7.5, §9.2 I21).
288///
289/// Control characters are escaped, the origin, acting agent and isolation are shown, and a
290/// body longer than the budget is truncated with a marker. A truncated call cannot be
291/// approved until [`expand`](Self::expand) has shown the whole body.
292///
293/// # Example
294///
295/// ```rust
296/// use adk_core::ToolConfirmationRequest;
297/// use adk_harness::{IsolationStatus, RenderedCall};
298/// use serde_json::json;
299///
300/// let long = "x".repeat(10_000);
301/// let request = ToolConfirmationRequest::new("bash", json!({ "command": long }));
302/// let rendered = RenderedCall::render(&request, &IsolationStatus::Host, 100);
303/// assert!(rendered.truncated);
304/// assert!(!rendered.can_approve());
305/// assert_eq!(rendered.expand().len(), "$ ".len() + 10_000);
306/// assert!(rendered.can_approve());
307/// ```
308#[derive(Clone, Debug)]
309pub struct RenderedCall {
310    /// One line naming the tool and the isolation; never contains model-written text.
311    pub title: String,
312    /// Who publishes the tool: source and declaration digest.
313    pub origin: String,
314    /// The acting agent and the subject it acts for.
315    pub agent: String,
316    /// The isolation the call runs under.
317    pub isolation: String,
318    /// The escaped arguments, cut to the budget.
319    pub body: String,
320    /// Whether [`body`](Self::body) was cut.
321    pub truncated: bool,
322    full_body: String,
323    expanded: Arc<AtomicBool>,
324}
325
326impl RenderedCall {
327    /// Renders `request` with a body of at most `max_bytes` bytes.
328    pub fn render(
329        request: &ToolConfirmationRequest,
330        isolation: &IsolationStatus,
331        max_bytes: usize,
332    ) -> Self {
333        let tool = escape_control(&request.tool_name);
334        let shell = request.tool_name == "bash";
335        let title = if shell {
336            if request.args.get("unsandboxed").and_then(Value::as_bool) == Some(true) {
337                format!("{tool}: unsandboxed retry on the host (full user permissions, network)")
338            } else if request.args.get("run_in_background").and_then(Value::as_bool) == Some(true) {
339                format!("{tool} on {isolation}, in the background")
340            } else {
341                format!("{tool} on {isolation}")
342            }
343        } else {
344            tool.to_string()
345        };
346        let web_url = match request.tool_name.as_str() {
347            // The browser pack's navigation is a web call too (spec 3.1 §7.24).
348            "web_fetch" | "browser_navigate" | "browser_new_tab" | "browser_new_window" => {
349                request.args.get("url").and_then(Value::as_str)
350            }
351            "web_search" => request.args.get("site").and_then(Value::as_str),
352            _ => None,
353        };
354        let mut full_body = if shell {
355            let command = request.args.get("command").and_then(Value::as_str).unwrap_or_default();
356            format!("$ {}", escape_control(command))
357        } else if let Some(url) = web_url {
358            // Host, path and query shown separately, so a credential or a look-alike host
359            // in the URL is visible as such (spec 3.1 §7.20 "Prompt").
360            let parsed = crate::web::ParsedUrl::parse(url)
361                .or_else(|_| crate::web::ParsedUrl::parse(&format!("https://{url}/")));
362            let mut body = match parsed {
363                Ok(parsed) => format!(
364                    "host: {}\npath: {}\nquery: {}",
365                    escape_control(&parsed.host),
366                    escape_control(&parsed.path),
367                    parsed.query.as_deref().map_or_else(|| "(none)".to_string(), escape_control),
368                ),
369                Err(refusal) => format!("url: {} (refused: {refusal})", escape_control(url)),
370            };
371            if let Some(query) = request.args.get("query").and_then(Value::as_str) {
372                body.push_str(&format!("\nsearch: {}", escape_control(query)));
373            }
374            body
375        } else {
376            escape_control(&request.args.to_string())
377        };
378        if shell && let Some(reason) = request.args.get("reason").and_then(Value::as_str) {
379            let reason: String = reason.chars().take(REASON_MAX_CHARS).collect();
380            full_body.push_str(&format!("\nmodel's reason: \"{}\"", escape_control(&reason)));
381        }
382        let (body, truncated) = cut(&full_body, max_bytes);
383        let origin = request.origin.as_ref().map_or_else(
384            || "unknown origin".to_string(),
385            |origin| format!("{} ({})", escape_control(&origin.source), origin.declaration_digest),
386        );
387        let agent = request.acting.as_deref().map_or_else(
388            || "unknown agent".to_string(),
389            |acting| match &acting.on_behalf_of {
390                Some(subject) => format!("{} for {}", acting.agent.id, escape_control(&subject.id)),
391                None => acting.agent.id.to_string(),
392            },
393        );
394        Self {
395            title,
396            origin,
397            agent,
398            isolation: isolation.to_string(),
399            body,
400            truncated,
401            full_body,
402            expanded: Arc::new(AtomicBool::new(false)),
403        }
404    }
405
406    /// The whole escaped body. Showing it lets a truncated call be approved.
407    pub fn expand(&self) -> &str {
408        self.expanded.store(true, Ordering::SeqCst);
409        &self.full_body
410    }
411
412    /// Whether [`expand`](Self::expand) was called on this rendering or a clone of it.
413    pub fn was_expanded(&self) -> bool {
414        self.expanded.load(Ordering::SeqCst)
415    }
416
417    /// Whether an approval of this rendering may stand: the body was shown in full.
418    pub fn can_approve(&self) -> bool {
419        !self.truncated || self.was_expanded()
420    }
421}
422
423/// Most prompts one turn may show before the remaining calls are denied (spec 3.1 §7.5).
424///
425/// # Example
426///
427/// ```rust
428/// assert_eq!(adk_harness::DEFAULT_PROMPTS_PER_TURN, 20);
429/// ```
430pub const DEFAULT_PROMPTS_PER_TURN: usize = 20;
431
432#[derive(Debug, Default)]
433struct TurnState {
434    invocation_id: String,
435    prompts: usize,
436    deny_all: bool,
437}
438
439/// Most sessions whose turn state is kept; the oldest is dropped first.
440const TURN_STATES_CAP: usize = 1024;
441
442/// Turn state per session, so one session's "deny all remaining" and prompt cap never
443/// reset or spend another's (threat I-3).
444#[derive(Debug, Default)]
445struct Turns {
446    states: std::collections::HashMap<String, TurnState>,
447    order: std::collections::VecDeque<String>,
448}
449
450impl Turns {
451    fn of(&mut self, key: String) -> &mut TurnState {
452        if !self.states.contains_key(&key) {
453            self.order.push_back(key.clone());
454            while self.order.len() > TURN_STATES_CAP {
455                if let Some(oldest) = self.order.pop_front() {
456                    self.states.remove(&oldest);
457                }
458            }
459        }
460        self.states.entry(key).or_default()
461    }
462}
463
464/// A [`ToolConfirmationHandler`] that asks an [`ApprovalPrompter`] (spec 3.1 §7.5).
465///
466/// Prompts are serialized, because calls in a batch are decided concurrently, and capped
467/// per turn of each session. Before prompting, the call is decided again by the run's whole policy — the
468/// harness layer with the call's origin, made stricter by the run's and the operator's
469/// layers — so a rule granted for an earlier call in the same batch applies without a
470/// prompt when only the harness asked. A call another layer requires approval for, or the
471/// agent's confirmation policy holds, is always put to the person. An approval with edited arguments returns them through `decide_approval`, and
472/// the governed path checks them against the policy again. After a person denies a call,
473/// the rest of the turn's calls are denied (I19).
474///
475/// # Example
476///
477/// ```rust,ignore
478/// let harness = HarnessAgent::builder("harness")
479///     .model(model)
480///     .workspace(workspace)
481///     .prompter(Arc::new(ConsolePrompter::new()))
482///     .build()?;
483/// ```
484pub struct PromptingConfirmationHandler {
485    pub(super) prompter: Arc<dyn ApprovalPrompter>,
486    standing: Arc<dyn StandingRuleStore>,
487    policy: HarnessPolicy,
488    serial: Mutex<Turns>,
489    pub(super) per_turn_cap: usize,
490    /// The batches of recent model turns, for change sets (spec 3.1 §7.26).
491    pub(super) batches: std::sync::Mutex<super::batch::BatchBook>,
492    /// The computer-use pack's screen plans, shown as one card each (spec 3.7 Q8).
493    #[cfg(feature = "computer-use")]
494    pub(super) screen_plans: Option<Arc<crate::packs::computer_use::ScreenPlans>>,
495    /// The partition whose crossings are put to the person with their three answers.
496    #[cfg(feature = "kernel")]
497    partition: Option<crate::partition::PartitionWiring>,
498}
499
500impl fmt::Debug for PromptingConfirmationHandler {
501    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
502        f.debug_struct("PromptingConfirmationHandler")
503            .field("prompter", &self.prompter)
504            .field("per_turn_cap", &self.per_turn_cap)
505            .finish()
506    }
507}
508
509pub(super) fn refuse(message: impl Into<String>) -> ToolApproval {
510    ToolApproval::deny().with_message(message)
511}
512
513impl PromptingConfirmationHandler {
514    /// A handler asking `prompter`, granting remembered rules in `standing`, and
515    /// re-checking each call against `policy`.
516    pub fn new(
517        prompter: Arc<dyn ApprovalPrompter>,
518        standing: Arc<dyn StandingRuleStore>,
519        policy: HarnessPolicy,
520    ) -> Self {
521        Self {
522            prompter,
523            standing,
524            policy,
525            serial: Mutex::new(Turns::default()),
526            per_turn_cap: DEFAULT_PROMPTS_PER_TURN,
527            batches: std::sync::Mutex::default(),
528            #[cfg(feature = "computer-use")]
529            screen_plans: None,
530            #[cfg(feature = "kernel")]
531            partition: None,
532        }
533    }
534
535    /// Puts `wiring`'s crossings to the person with their three answers (spec 3.2 §7.8).
536    #[cfg(feature = "kernel")]
537    pub(crate) fn with_partition(mut self, wiring: crate::partition::PartitionWiring) -> Self {
538        self.partition = Some(wiring);
539        self
540    }
541
542    /// Shows `prompt` under this handler's serial mutex and per-turn cap, for a request
543    /// that is not a held tool call: an MCP server's elicitation (spec 3.1 §7.21).
544    ///
545    /// `turn` is the (app, user, session, invocation) the request belongs to. Returns
546    /// `Ok(None)` when the turn reached its prompt cap or a person denied its remaining
547    /// calls, so the caller declines.
548    ///
549    /// # Errors
550    ///
551    /// Returns the prompter's error.
552    pub async fn prompt_elicitation(
553        &self,
554        turn: (&str, &str, &str, &str),
555        prompt: ApprovalPrompt,
556    ) -> Result<Option<PromptAnswer>> {
557        let (app, user, session, invocation) = turn;
558        let mut turns = self.serial.lock().await;
559        let state = turns.of(format!("{app}\u{1f}{user}\u{1f}{session}"));
560        if state.invocation_id != invocation {
561            *state = TurnState { invocation_id: invocation.to_string(), ..TurnState::default() };
562        }
563        if state.deny_all || state.prompts >= self.per_turn_cap {
564            return Ok(None);
565        }
566        state.prompts += 1;
567        let answer = self.prompter.prompt(prompt).await?;
568        if matches!(answer, PromptAnswer::DenyAllRemaining) {
569            state.deny_all = true;
570        }
571        Ok(Some(answer))
572    }
573
574    /// Sets the most prompts one turn may show (default [`DEFAULT_PROMPTS_PER_TURN`]).
575    #[must_use]
576    pub fn with_per_turn_cap(mut self, cap: usize) -> Self {
577        self.per_turn_cap = cap;
578        self
579    }
580
581    /// Decides `request`, with the arguments a person substituted and their message
582    /// (spec 3.1 §7.5, §10 C3).
583    ///
584    /// # Errors
585    ///
586    /// Returns the prompter's error, or the rule store's when a remembered rule cannot be
587    /// stored.
588    async fn approval_for(&self, request: &ToolConfirmationRequest) -> Result<ToolApproval> {
589        let mut turns = self.serial.lock().await;
590        let Some(context) = self.policy.prompts().take(request) else {
591            tracing::warn!(tool.name = %request.tool_name, "held call was not evaluated by the harness policy; not run");
592            return Ok(refuse("the harness policy did not evaluate this call, so it is not run"));
593        };
594        let turn = turns.of(format!(
595            "{}\u{1f}{}\u{1f}{}",
596            context.app_name, context.user_id, context.session_id
597        ));
598        if turn.invocation_id != context.invocation_id {
599            *turn =
600                TurnState { invocation_id: context.invocation_id.clone(), ..TurnState::default() };
601        }
602        // A call a change set decided is answered from that decision (spec 3.1 §7.26).
603        if let Some(approval) =
604            self.batches.lock().unwrap_or_else(|e| e.into_inner()).decided(request)
605        {
606            return Ok(approval);
607        }
608        if turn.deny_all {
609            return Ok(refuse("the person denied the remaining calls of this turn"));
610        }
611
612        let policy = self.policy.with_audit(context.audit.clone());
613        let policy_request = context.policy_request(&request.tool_name, &request.args);
614        let evaluated = policy
615            .evaluate_full(
616                &policy_request,
617                request.origin.as_ref(),
618                request.function_call_id.as_deref(),
619                false,
620            )
621            .await;
622        // The re-check covers the run's whole policy: a rule granted for an earlier call
623        // in the batch answers the harness's own approval, never another layer's.
624        let peer_decision = match &context.peers {
625            Some(peers) => {
626                let mut call = PolicyCall::new();
627                if let Some(origin) = request.origin.as_ref() {
628                    call = call.with_origin(origin);
629                }
630                if let Some(call_id) = request.function_call_id.as_deref() {
631                    call = call.with_function_call_id(call_id);
632                }
633                Some(peers.evaluate_call(&policy_request, &call).await)
634            }
635            None => None,
636        };
637        let composed = match peer_decision.clone() {
638            Some(peers) => evaluated.decision.clone().stricter(peers),
639            None => evaluated.decision.clone(),
640        };
641        match &composed {
642            // Held by the harness alone, and the harness now allows it: a rule granted for an
643            // earlier call of the batch answers it, and the person is told so.
644            PolicyDecision::Allow if context.harness_held => {
645                if let Some(hit) = &evaluated.rule {
646                    self.prompter.rule_applied(hit);
647                }
648                return Ok(ToolApproval::approve());
649            }
650            // Held by another layer or the agent's confirmation policy: the person decides.
651            PolicyDecision::Allow => {}
652            PolicyDecision::Deny { reason } => return Ok(refuse(reason.clone())),
653            PolicyDecision::RequireApproval { .. } => {}
654        }
655        // The steps of a previewed screen plan are approved with one answer (spec 3.7 Q8).
656        #[cfg(feature = "computer-use")]
657        if let Some(approval) = self
658            .screen_plan(
659                &context,
660                request,
661                &policy,
662                evaluated.mode,
663                (&mut turn.prompts, &mut turn.deny_all),
664            )
665            .await?
666        {
667            return Ok(approval);
668        }
669        // Two or more held edits of the turn are reviewed as one change set (spec 3.1 §7.26).
670        if evaluated.kind == ToolKind::Edit
671            && super::rule::EDIT_TOOLS.contains(&request.tool_name.as_str())
672            && let Some(approval) = self
673                .change_set(&context, request, &policy, &mut turn.prompts, &mut turn.deny_all)
674                .await?
675        {
676            return Ok(approval);
677        }
678        if turn.deny_all {
679            return Ok(refuse("the person denied the remaining calls of this turn"));
680        }
681        if turn.prompts >= self.per_turn_cap {
682            return Ok(refuse(format!(
683                "this turn reached its limit of {} approval prompts",
684                self.per_turn_cap
685            )));
686        }
687        turn.prompts += 1;
688
689        let isolation = policy.isolation_status().clone();
690        // A remembered rule answers only the harness's own approval, so one is offered only
691        // when no other layer asks too.
692        let only_the_harness_asks =
693            matches!(evaluated.decision, PolicyDecision::RequireApproval { .. })
694                && peer_decision.as_ref().is_none_or(|peers| *peers == PolicyDecision::Allow);
695        let suggestions = if only_the_harness_asks
696            && evaluated.kind.rule_eligible()
697            && !evaluated.base.is_non_waivable()
698        {
699            StandingRule::suggestions(request)
700        } else {
701            Vec::new()
702        };
703        let rendered = RenderedCall::render(request, &isolation, RENDERED_CALL_MAX_BYTES);
704        let prompt = ApprovalPrompt {
705            request: request.clone(),
706            kind: evaluated.kind,
707            mode: evaluated.mode,
708            isolation,
709            suggestions: suggestions.clone(),
710            rendered: rendered.clone(),
711        };
712        // A freeze resolves an open prompt: the call is not run and the turn ends with the
713        // freeze, as the governed path ends it when a freeze lands after an approval (I20).
714        let frozen = async {
715            if context.governance.is_empty() {
716                return std::future::pending::<adk_core::AdkError>().await;
717            }
718            loop {
719                if let Some(error) =
720                    context.governance.iter().find_map(|control| control.check().err())
721                {
722                    return error;
723                }
724                tokio::time::sleep(crate::tools::GOVERNANCE_POLL_INTERVAL).await;
725            }
726        };
727        // A crossing: allow (for the run, when it reads), deny, or deny and block the
728        // partition; never a remembered rule (spec 3.2 §7.8, K-I15).
729        #[cfg(feature = "kernel")]
730        if let Some((wiring, crossing)) = self
731            .partition
732            .as_ref()
733            .and_then(|wiring| wiring.crossing_of(request).map(|crossing| (wiring, crossing)))
734        {
735            let crossing_prompt = crate::partition::CrossingPrompt::new(prompt, crossing.clone());
736            let answer = tokio::select! {
737                answer = self.prompter.prompt_crossing(crossing_prompt) => answer?,
738                error = frozen => {
739                    tracing::warn!(tool.name = %request.tool_name, "execution was frozen while a person was deciding; the crossing does not run");
740                    return Err(error);
741                }
742            };
743            return Ok(match answer {
744                crate::partition::CrossingAnswer::Allow if !rendered.can_approve() => {
745                    refuse("the call was approved without showing its full arguments")
746                }
747                crate::partition::CrossingAnswer::Allow => ToolApproval::approve(),
748                crate::partition::CrossingAnswer::Deny { message } => {
749                    turn.deny_all = true;
750                    match message {
751                        Some(message) => refuse(message),
752                        None => ToolApproval::deny(),
753                    }
754                }
755                crate::partition::CrossingAnswer::DenyAndBlock => {
756                    turn.deny_all = true;
757                    let by = match &context.acting {
758                        Some(acting) => adk_core::audit_log::AuditActor::new(
759                            acting,
760                            context.invocation_id.clone(),
761                        ),
762                        None => adk_core::audit_log::AuditActor::default(),
763                    };
764                    wiring
765                        .policy
766                        .partitions()
767                        .block(crossing.from.clone(), crossing.to.clone(), by)
768                        .await
769                        .map_err(adk_core::AdkError::from)?;
770                    refuse(format!(
771                        "denied, and crossings to `{}` from partition `{}` are blocked",
772                        crossing.to, crossing.from
773                    ))
774                }
775            });
776        }
777        let answer = tokio::select! {
778            answer = self.prompter.prompt(prompt) => answer?,
779            error = frozen => {
780                tracing::warn!(tool.name = %request.tool_name, "execution was frozen while a person was deciding; the call is not run");
781                return Err(error);
782            }
783        };
784        let unexpanded = || refuse("the call was approved without showing its full arguments");
785        Ok(match answer {
786            PromptAnswer::ApproveOnce => {
787                if !rendered.can_approve() {
788                    unexpanded()
789                } else {
790                    ToolApproval::approve()
791                }
792            }
793            PromptAnswer::ApproveWithArgs(args) => {
794                if !rendered.can_approve() {
795                    unexpanded()
796                } else {
797                    ToolApproval::approve().with_edited_args(args)
798                }
799            }
800            PromptAnswer::ApproveAndRemember(suggestion) => {
801                if !rendered.can_approve() {
802                    unexpanded()
803                } else {
804                    self.remember(
805                        &context,
806                        request,
807                        &suggestions,
808                        suggestion,
809                        StandingDecision::Allow,
810                    )
811                    .await?;
812                    ToolApproval::approve()
813                }
814            }
815            PromptAnswer::Deny { message } => {
816                turn.deny_all = true;
817                match message {
818                    Some(message) => refuse(message),
819                    None => ToolApproval::deny(),
820                }
821            }
822            PromptAnswer::DenyAndRemember(suggestion) => {
823                turn.deny_all = true;
824                let reason = format!("denied by {}", context.user_id);
825                self.remember(
826                    &context,
827                    request,
828                    &suggestions,
829                    suggestion,
830                    StandingDecision::Deny { reason: reason.clone() },
831                )
832                .await?;
833                refuse(reason)
834            }
835            PromptAnswer::DenyAllRemaining => {
836                turn.deny_all = true;
837                refuse("the person denied the remaining calls of this turn")
838            }
839        })
840    }
841
842    /// Stores the rule a person chose at a prompt and records `harness.rule.created`.
843    async fn remember(
844        &self,
845        context: &PromptContext,
846        request: &ToolConfirmationRequest,
847        offered: &[RuleSuggestion],
848        chosen: RuleSuggestion,
849        decision: StandingDecision,
850    ) -> Result<()> {
851        // Only a rule the prompt offered, or one at least as narrow, is accepted: same tool,
852        // exact pin to this call's declaration.
853        let pinned = match (&chosen.origin, request.origin.as_ref()) {
854            (OriginPin::Exact { .. }, Some(origin)) => chosen.origin.admits(origin),
855            _ => false,
856        };
857        if !pinned || !glob_matches(&chosen.tool, &request.tool_name) || chosen.tool.contains('*') {
858            tracing::warn!(tool.name = %request.tool_name, "ignoring a remembered rule that does not pin this call's tool");
859            return Ok(());
860        }
861        if decision == StandingDecision::Allow && !offered.contains(&chosen) {
862            tracing::warn!(tool.name = %request.tool_name, "ignoring an allow rule the prompt did not offer");
863            return Ok(());
864        }
865        let subject = context
866            .acting
867            .as_ref()
868            .and_then(|acting| acting.on_behalf_of.clone())
869            .unwrap_or_else(|| SubjectRef::new(SubjectKind::Human, context.user_id.clone()));
870        let owner = RuleOwner {
871            app_name: context.app_name.clone(),
872            user_id: context.user_id.clone(),
873            subject_kind: subject.kind,
874            session_id: context.session_id.clone(),
875            created_by: subject,
876        };
877        let rule = chosen.into_rule(&owner, decision, Some(request.fingerprint()));
878        if let Some(audit) = context.audit() {
879            let fields = rule_audit_fields(&rule, request.function_call_id.as_deref());
880            audit.record("harness.rule.created", fields).await?;
881        }
882        self.standing.grant(rule).await?;
883        Ok(())
884    }
885}
886
887/// The `ext` fields of a `harness.rule.*` record (spec 3.1 §9.3); `created_from_call_id`
888/// names the held call the rule was created from.
889pub(crate) fn rule_audit_fields(rule: &StandingRule, created_from_call_id: Option<&str>) -> Value {
890    let digest = |value: &Value| crate::fsutil::hex_digest(value.to_string().as_bytes());
891    let (source, declaration_digest) = match &rule.origin {
892        OriginPin::Exact { source, declaration_digest } => {
893            (source.clone(), Some(declaration_digest.clone()))
894        }
895        OriginPin::AnyDeclaration { source } => (source.clone(), None),
896        OriginPin::ExactEach { source, .. } => (source.clone(), None),
897    };
898    let mut fields = json!({
899        "ruleId": rule.id,
900        "ruleDigest": digest(&serde_json::to_value(rule).unwrap_or(Value::Null)),
901        "subject": rule.scope.user_id(),
902        "app": rule.scope.app_name(),
903        "tool": rule.tool,
904        "source": source,
905        "declarationDigest": declaration_digest,
906        "predicatesDigest": digest(&serde_json::to_value(&rule.predicates).unwrap_or(Value::Null)),
907        "decision": serde_json::to_value(&rule.decision).unwrap_or(Value::Null),
908        "expiresAt": rule.expires_at,
909        "createdFromCallId": created_from_call_id,
910        "by": rule.created_by.id,
911    });
912    // A folder rule's tool pattern matches any name, so its record keeps each tool and the
913    // declaration it is pinned to as data, and says what it covers in the words a person
914    // reads (spec 3.3 §8.2).
915    if let OriginPin::ExactEach { declarations, .. } = &rule.origin {
916        fields["tools"] = json!(declarations.keys().collect::<Vec<_>>());
917        fields["declarationDigests"] = json!(declarations);
918    }
919    let folder = rule.predicates.iter().find_map(|predicate| {
920        if let RulePredicate::WritesWithin { dir } = predicate { Some(dir) } else { None }
921    });
922    if let Some(dir) = folder {
923        fields["covers"] = json!(if dir == "." {
924            "file writes anywhere in the workspace".to_string()
925        } else {
926            format!("file writes in {dir}/")
927        });
928    }
929    fields
930}
931
932#[async_trait]
933impl ToolConfirmationHandler for PromptingConfirmationHandler {
934    async fn decide(&self, request: &ToolConfirmationRequest) -> Result<ToolConfirmationDecision> {
935        let approval = self.approval_for(request).await?;
936        // `decide` cannot carry edited arguments; the governed path asks
937        // `decide_approval`, and a direct caller of `decide` gets the safe direction.
938        if approval.edited_args.is_some() {
939            return Ok(ToolConfirmationDecision::Deny);
940        }
941        Ok(approval.decision)
942    }
943
944    async fn decide_approval(&self, request: &ToolConfirmationRequest) -> Result<ToolApproval> {
945        self.approval_for(request).await
946    }
947
948    /// Keeps the turn's batch, so its held edits are reviewed as one change set
949    /// (spec 3.1 §7.26, §10 C6).
950    async fn batch_started(&self, calls: &[adk_core::BatchCall<'_>]) {
951        self.batches.lock().unwrap_or_else(|e| e.into_inner()).started(calls);
952    }
953}