Skip to main content

agent86_core/
approval.rs

1//! The human-in-the-loop approval gate, ported from Python's
2//! `guardrails/policy.py`, and the terminal prompt from `ui/repl.py`.
3//!
4//! Read-only tools always pass. Side-effecting tools pass under `auto`, are
5//! blocked under `deny`, and are put to the user under `ask`. With no prompt
6//! (piped stdin, CI, cron), `ask` declines: running unattended requires an
7//! explicit `--yes` or `approval = "auto"`.
8
9use crate::pyjson::python_json_dumps;
10use crate::tools::{Tool, ToolContext};
11use crate::types::{ApprovalMode, ToolCall};
12use serde_json::Value;
13use std::io::{BufRead, IsTerminal, Write};
14use std::sync::{Mutex, PoisonError};
15
16/// The one-line argument summary is capped at this many characters.
17pub const SUMMARY_LIMIT: usize = 300;
18/// The prompt shows at most this many lines of a tool's preview.
19pub const APPROVAL_DETAIL_LINES: usize = 40;
20
21/// What the user is asked to approve.
22#[derive(Debug, Clone, PartialEq)]
23pub struct ApprovalPreview {
24    /// The arguments as `json.dumps`, capped at [`SUMMARY_LIMIT`].
25    pub summary: String,
26    /// The tool's own description of the effect, such as a unified diff.
27    pub detail: Option<String>,
28    /// What `detail` is written in (`diff`, `bash`, `python`), as Python's `lexer`.
29    pub lexer: Option<&'static str>,
30    /// Beyond Python: a caution shown above the detail, for a write into agent86's
31    /// own configuration or skills ([`guarded_warning`]).
32    pub warning: Option<String>,
33    /// Beyond Python: show the whole detail, never capped, because what is approved
34    /// is all of it (a project specialty's file, whose every line becomes prompt text).
35    pub full: bool,
36    /// Beyond Python: the specialist sub-agent asking (or, for a project specialty's
37    /// own approval, its name), so a surface can say who asks.
38    pub agent: Option<String>,
39    /// Beyond Python: the file text the call would change, before and after, for
40    /// a surface that shows a reviewable diff (an editor over ACP). Built from the
41    /// expanded call, then redacted, as `detail` is.
42    pub change: Option<crate::tools::FileChange>,
43    /// Beyond Python: the sub-agent the call comes from, with its card, worktree, and
44    /// spend so far, for a surface that shows who asks (an editor's approval inbox).
45    /// `None` for the main agent's calls.
46    pub asker: Option<Box<Asker>>,
47}
48
49/// The sub-agent a question comes from (beyond Python), as it stood when the
50/// question was built: an editor shows it beside the question, so the user knows
51/// which of several sub-agents running at once asks, where it works, and what it
52/// has cost.
53#[derive(Debug, Clone, PartialEq)]
54pub struct Asker {
55    /// The provider id of the card it reports on (its top-level delegation's call,
56    /// or `/agent`'s synthetic one), when the surface observes sub-agents.
57    pub card: Option<String>,
58    /// Its per-spawn number, as sub-agent events and the trace carry it.
59    pub run: u64,
60    /// The specialty or role it runs as.
61    pub agent: String,
62    pub depth: u32,
63    /// The git worktree it is jailed to: the worktree's directory and its branch.
64    pub worktree: Option<(String, String)>,
65    /// Model calls it has made so far.
66    pub steps: u32,
67    /// What it and anything it delegated have spent so far.
68    pub cost_usd: f64,
69}
70
71impl Asker {
72    /// The sub-agent `ctx` belongs to, or `None` for the main agent's context.
73    pub fn of(ctx: &ToolContext) -> Option<Self> {
74        let run = ctx.subagent.as_ref()?;
75        let (steps, cost_usd) = run.progress();
76        Some(Self {
77            card: ctx.card.as_ref().map(|card| card.id.clone()),
78            run: run.run,
79            agent: run.name.clone(),
80            depth: run.depth,
81            worktree: ctx.worktree.as_ref().map(|worktree| {
82                (
83                    crate::tools::display_path(&worktree.path),
84                    worktree.branch.clone(),
85                )
86            }),
87            steps,
88            cost_usd,
89        })
90    }
91}
92
93/// What a queued question is (beyond Python).
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum QuestionKind {
96    /// May a tool call run?
97    Approval,
98    /// May a project specialty run?
99    Specialty,
100    /// Raise a spent limit?
101    Limit,
102    /// Enter a secret.
103    Secret,
104}
105
106impl QuestionKind {
107    pub fn as_str(self) -> &'static str {
108        match self {
109            Self::Approval => "approval",
110            Self::Specialty => "specialty",
111            Self::Limit => "limit",
112            Self::Secret => "secret",
113        }
114    }
115}
116
117/// A question in the [`PromptQueue`], described for a surface that lists the
118/// questions waiting (beyond Python). It names who asks and about what, never the
119/// arguments or a secret's name.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct Question {
122    pub kind: QuestionKind,
123    /// The tool an approval is for.
124    pub tool: Option<String>,
125    /// The call it belongs to, by the id the gate sees (`<card>/<n>` for a
126    /// sub-agent's call).
127    pub call: Option<String>,
128    /// The sub-agent asking, when one is.
129    pub agent: Option<String>,
130    /// The provider id of the asking sub-agent's card.
131    pub card: Option<String>,
132    /// What is asked about beyond the tool: the project specialty to run, or the
133    /// limit to raise.
134    pub subject: Option<String>,
135}
136
137impl Question {
138    pub fn new(kind: QuestionKind) -> Self {
139        Self {
140            kind,
141            tool: None,
142            call: None,
143            agent: None,
144            card: None,
145            subject: None,
146        }
147    }
148
149    /// The question about `call`, whose prompt shows `preview`.
150    pub fn about(
151        kind: QuestionKind,
152        tool: &str,
153        call: &ToolCall,
154        preview: &ApprovalPreview,
155    ) -> Self {
156        let asker = preview.asker.as_ref();
157        Self {
158            tool: Some(tool.to_owned()),
159            call: Some(call.id.clone()),
160            agent: asker.map(|asker| asker.agent.clone()),
161            card: asker.and_then(|asker| asker.card.clone()),
162            ..Self::new(kind)
163        }
164    }
165}
166
167/// Told the question being asked, if any, and those waiting behind it in the order
168/// they will be asked, whenever either changes. Called with the queue locked, so it
169/// must not block or ask anything itself.
170pub type QueueWatcher = std::sync::Arc<dyn Fn(Option<&Question>, &[Question]) + Send + Sync>;
171
172/// The caution for a write into agent86's own configuration or skills.
173pub fn guarded_warning(path: &str) -> String {
174    format!(
175        "This writes agent86's own configuration or skills ({}), which changes what \
176         agent86 runs or is told from now on. Asked even in auto mode.",
177        crate::escape::show_controls(path)
178    )
179}
180
181/// Asks whether one side-effecting call may run: `(tool name, preview) -> approved`.
182pub type ApprovalPrompt = Box<dyn Fn(&str, &ApprovalPreview) -> bool + Send + Sync>;
183
184/// [`ApprovalPrompt`] for a surface that has to say which call it asks about
185/// (beyond Python): the ACP server names the call's id in its permission request, so
186/// the editor can match the question to the tool call it already showed.
187pub type CallApprovalPrompt = Box<dyn Fn(&ToolCall, &ApprovalPreview) -> bool + Send + Sync>;
188
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
190pub struct ApprovalDecision {
191    pub approved: bool,
192    pub reason: &'static str,
193}
194
195/// One question at a time (beyond Python): approval, limit, and secret prompts all
196/// pass through one queue, because sub-agents running in parallel can each reach a
197/// prompt, and a terminal or an editor answers one at a time. Questions are asked
198/// in the order they arrived, and a watcher can be told which are waiting
199/// ([`PromptQueue::set_watcher`]), so an editor can list them. A waiter that gets
200/// its turn after the turn was cancelled declines without asking, so a cancel is
201/// not followed by each queued question in turn. Clones share the queue.
202#[derive(Clone, Default)]
203pub struct PromptQueue {
204    inner: std::sync::Arc<QueueInner>,
205}
206
207#[derive(Default)]
208struct QueueInner {
209    state: Mutex<QueueState>,
210    /// Signalled whenever the question being asked ends or a waiter gives up its
211    /// turn, so the next in line can go.
212    turn_over: std::sync::Condvar,
213    cancel: Mutex<Option<crate::agent::CancelToken>>,
214    watcher: Mutex<Option<QueueWatcher>>,
215}
216
217#[derive(Default)]
218struct QueueState {
219    next: u64,
220    asking: Option<Question>,
221    /// By ticket, in arrival order.
222    waiting: std::collections::VecDeque<(u64, Question)>,
223}
224
225/// Ends the question being asked, even if its prompt panics.
226struct Asked<'a>(&'a PromptQueue);
227
228impl Drop for Asked<'_> {
229    fn drop(&mut self) {
230        let mut state = self.0.lock();
231        state.asking = None;
232        // With a question waiting, its turn reports next (asked, or given up), so
233        // a watcher never sees the gap between the two.
234        if state.waiting.is_empty() {
235            self.0.report(&state);
236        }
237        self.0.inner.turn_over.notify_all();
238    }
239}
240
241impl std::fmt::Debug for PromptQueue {
242    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
243        formatter.write_str("PromptQueue")
244    }
245}
246
247impl PromptQueue {
248    /// Decline queued questions once `token` (the turn's) is cancelled.
249    pub fn watch(&self, token: crate::agent::CancelToken) {
250        *self
251            .inner
252            .cancel
253            .lock()
254            .unwrap_or_else(PoisonError::into_inner) = Some(token);
255    }
256
257    /// Tell `watcher` (or, with `None`, nobody) what is asked and waiting from now on.
258    pub fn set_watcher(&self, watcher: Option<QueueWatcher>) {
259        *self
260            .inner
261            .watcher
262            .lock()
263            .unwrap_or_else(PoisonError::into_inner) = watcher;
264    }
265
266    /// Ask `question` with `ask` once every question that arrived before it has
267    /// been asked, or `None` when the turn was cancelled while it waited.
268    pub fn ask<T>(&self, question: Question, ask: impl FnOnce() -> T) -> Option<T> {
269        let mut state = self.lock();
270        let waited = state.asking.is_some() || !state.waiting.is_empty();
271        let question = if waited {
272            let ticket = state.next;
273            state.next += 1;
274            state.waiting.push_back((ticket, question));
275            self.report(&state);
276            while state.asking.is_some()
277                || state.waiting.front().map(|(first, _)| *first) != Some(ticket)
278            {
279                state = self
280                    .inner
281                    .turn_over
282                    .wait(state)
283                    .unwrap_or_else(PoisonError::into_inner);
284            }
285            state
286                .waiting
287                .pop_front()
288                .map_or_else(|| unreachable!("first in line"), |(_, question)| question)
289        } else {
290            question
291        };
292        if self.cancelled() {
293            if waited {
294                self.report(&state);
295                self.inner.turn_over.notify_all();
296            }
297            return None;
298        }
299        state.asking = Some(question);
300        self.report(&state);
301        drop(state);
302        let _asked = Asked(self);
303        Some(ask())
304    }
305
306    fn lock(&self) -> std::sync::MutexGuard<'_, QueueState> {
307        self.inner
308            .state
309            .lock()
310            .unwrap_or_else(PoisonError::into_inner)
311    }
312
313    fn cancelled(&self) -> bool {
314        self.inner
315            .cancel
316            .lock()
317            .unwrap_or_else(PoisonError::into_inner)
318            .as_ref()
319            .is_some_and(crate::agent::CancelToken::is_cancelled)
320    }
321
322    /// Tell the watcher, if there is one, about `state`.
323    fn report(&self, state: &QueueState) {
324        let watcher = self
325            .inner
326            .watcher
327            .lock()
328            .unwrap_or_else(PoisonError::into_inner)
329            .clone();
330        if let Some(watcher) = watcher {
331            let waiting: Vec<Question> = state
332                .waiting
333                .iter()
334                .map(|(_, question)| question.clone())
335                .collect();
336            watcher(state.asking.as_ref(), &waiting);
337        }
338    }
339}
340
341/// Decides whether a call may run, asking a human when the mode says so.
342pub struct ApprovalGate {
343    /// Behind a lock, so the interactive interface can switch it (Shift+Tab) while a
344    /// turn holds the harness; the next call is decided under the new mode, as in Python.
345    mode: Mutex<ApprovalMode>,
346    pub prompt: Option<ApprovalPrompt>,
347    /// Asked in place of `prompt` when set.
348    pub call_prompt: Option<CallApprovalPrompt>,
349    /// Every question goes through it, one at a time (beyond Python).
350    pub queue: PromptQueue,
351    /// Asked in place of the others about a project specialty's file (beyond
352    /// Python): an editor offers one remembering option for it, which a call's
353    /// prompt cannot.
354    pub specialty_prompt: Option<CallApprovalPrompt>,
355}
356
357impl ApprovalGate {
358    pub fn new(mode: ApprovalMode, prompt: Option<ApprovalPrompt>) -> Self {
359        Self {
360            mode: Mutex::new(mode),
361            prompt,
362            call_prompt: None,
363            queue: PromptQueue::default(),
364            specialty_prompt: None,
365        }
366    }
367
368    /// Ask `preview` of whichever prompt is installed, or `None` when nobody can be
369    /// asked.
370    fn ask(&self, tool: &dyn Tool, call: &ToolCall, preview: &ApprovalPreview) -> Option<bool> {
371        self.ask_about(tool.name(), call, preview)
372    }
373
374    pub fn mode(&self) -> ApprovalMode {
375        *self.mode.lock().unwrap_or_else(PoisonError::into_inner)
376    }
377
378    pub fn set_mode(&self, mode: ApprovalMode) {
379        *self.mode.lock().unwrap_or_else(PoisonError::into_inner) = mode;
380    }
381
382    pub fn decide(&self, tool: &dyn Tool, call: &ToolCall, ctx: &ToolContext) -> ApprovalDecision {
383        let decision = |approved, reason| ApprovalDecision { approved, reason };
384        let scope = ctx.scope.as_deref();
385        // Beyond Python: a specialist sub-agent's list comes before anything else,
386        // so nobody is asked about a call that would then be refused.
387        if !ctx.scope_allows(tool.name()) {
388            return decision(false, "not permitted for this sub-agent");
389        }
390        // Its approval mode applies only when stricter than the session's, read
391        // for each call so a switch mid-turn still counts.
392        let mode = crate::tools::stricter(Some(self.mode()), scope.and_then(|s| s.approval))
393            .unwrap_or(ApprovalMode::Ask);
394        // Beyond Python: a specialty's `confirm` tools are asked about in every mode
395        // but `deny`, read-only ones included.
396        if let Some(scope) = scope.filter(|s| s.confirm.iter().any(|t| t == tool.name())) {
397            if mode == ApprovalMode::Deny {
398                return decision(false, "blocked by approval policy (deny)");
399            }
400            if !self.can_ask() {
401                return decision(
402                    false,
403                    "this sub-agent's calls to this tool need approval, and no prompt is available",
404                );
405            }
406            let mut preview = build_preview(tool, call, ctx);
407            preview.warning = Some(format!(
408                "The '{}' sub-agent always asks before running {}.",
409                scope.label,
410                tool.name()
411            ));
412            preview.agent = Some(scope.label.clone());
413            return if self.ask(tool, call, &preview) == Some(true) {
414                decision(true, "approved by user")
415            } else {
416                decision(false, "declined by user")
417            };
418        }
419        if !tool.side_effecting() {
420            return decision(true, "read-only");
421        }
422        // Beyond Python: agent86's own files are asked about whatever the mode,
423        // except that `deny` still denies.
424        if let Some(path) = tool.guarded_target(&call.arguments, ctx) {
425            if mode == ApprovalMode::Deny {
426                return decision(false, "blocked by approval policy (deny)");
427            }
428            if !self.can_ask() {
429                return decision(
430                    false,
431                    "writing agent86's own configuration or skills needs approval, and no \
432                     prompt is available",
433                );
434            }
435            let mut preview = build_preview(tool, call, ctx);
436            preview.warning = Some(guarded_warning(&path));
437            preview.agent = scope.map(|scope| scope.label.clone());
438            return if self.ask(tool, call, &preview) == Some(true) {
439                decision(true, "approved by user")
440            } else {
441                decision(false, "declined by user")
442            };
443        }
444        match mode {
445            ApprovalMode::Auto => decision(true, "auto-approved"),
446            ApprovalMode::Deny => decision(false, "blocked by approval policy (deny)"),
447            ApprovalMode::Ask => {
448                if !self.can_ask() {
449                    return decision(false, "approval required but no prompt available");
450                }
451                let mut preview = build_preview(tool, call, ctx);
452                // Beyond Python: the user is told which sub-agent asks.
453                if let Some(scope) = scope {
454                    preview.warning = Some(format!("Asked by the '{}' sub-agent.", scope.label));
455                    preview.agent = Some(scope.label.clone());
456                }
457                if self.ask(tool, call, &preview) == Some(true) {
458                    decision(true, "approved by user")
459                } else {
460                    decision(false, "declined by user")
461                }
462            }
463        }
464    }
465
466    /// Ask about a project specialty's file: the specialty hook when one is
467    /// installed, else the call prompts. `None` when nobody can be asked.
468    pub fn ask_specialty(&self, call: &ToolCall, preview: &ApprovalPreview) -> Option<bool> {
469        match &self.specialty_prompt {
470            Some(prompt) => {
471                let mut question =
472                    Question::about(QuestionKind::Specialty, "delegate", call, preview);
473                question.subject = preview.agent.clone();
474                Some(
475                    self.queue
476                        .ask(question, || prompt(call, preview))
477                        .unwrap_or(false),
478                )
479            }
480            None => self.ask_about("delegate", call, preview),
481        }
482    }
483
484    /// Whether anybody can be asked.
485    pub fn can_ask(&self) -> bool {
486        self.prompt.is_some() || self.call_prompt.is_some()
487    }
488
489    /// Put a question that is not a tool's own to whichever prompt is installed (a
490    /// project specialty's approval). `call` is the call it belongs to, for a surface
491    /// that has to say which; `name` is what the plain prompt shows. `None` when
492    /// nobody can be asked.
493    pub fn ask_about(
494        &self,
495        name: &str,
496        call: &ToolCall,
497        preview: &ApprovalPreview,
498    ) -> Option<bool> {
499        if !self.can_ask() {
500            return None;
501        }
502        // A question that waited past a cancel is declined without being put.
503        Some(
504            self.queue
505                .ask(
506                    Question::about(QuestionKind::Approval, name, call, preview),
507                    || match &self.call_prompt {
508                        Some(prompt) => prompt(call, preview),
509                        None => self
510                            .prompt
511                            .as_ref()
512                            .is_some_and(|prompt| prompt(name, preview)),
513                    },
514                )
515                .unwrap_or(false),
516        )
517    }
518}
519
520/// The approval payload: a one-line argument summary plus the tool's own detail.
521///
522/// A tool that expands `${secret:NAME}` previews what it will really do (so a file
523/// that already holds the value shows no change on that line), and the detail is
524/// then redacted, so the user approves the placeholder, never reads the value.
525pub fn build_preview(tool: &dyn Tool, call: &ToolCall, ctx: &ToolContext) -> ApprovalPreview {
526    let text = python_json_dumps(&Value::Object(call.arguments.clone()), false);
527    let summary = if text.chars().count() <= SUMMARY_LIMIT {
528        text
529    } else {
530        format!(
531            "{} ...",
532            text.chars().take(SUMMARY_LIMIT).collect::<String>()
533        )
534    };
535    let expanded = crate::tools::with_secrets(tool, call, ctx)
536        .map_or_else(|_| call.arguments.clone(), |call| call.arguments.clone());
537    ApprovalPreview {
538        summary,
539        detail: tool
540            .preview(&expanded, ctx)
541            .map(|detail| ctx.secrets.redact(&detail))
542            .filter(|detail| !detail.is_empty()),
543        lexer: tool.preview_lexer(),
544        warning: None,
545        full: false,
546        agent: None,
547        change: tool
548            .change(&expanded, ctx)
549            .map(|change| change.redacted(&ctx.secrets)),
550        asker: Asker::of(ctx).map(Box::new),
551    }
552}
553
554/// The prompt to install for `agent86 run`: one that asks at the terminal when
555/// stdin is a terminal, and none otherwise (so `ask` declines).
556pub fn terminal_prompt_if_interactive() -> Option<ApprovalPrompt> {
557    std::io::stdin()
558        .is_terminal()
559        .then(|| Box::new(terminal_prompt) as ApprovalPrompt)
560}
561
562/// Ask at the terminal whether one side-effecting call may run. Default: no.
563///
564/// The preview is printed above the question, because approving a write
565/// sight-unseen is what this prompt exists to prevent. Python prints the prompt
566/// on stdout; it goes to stderr here so `run --json` output stays one object.
567pub fn terminal_prompt(tool_name: &str, preview: &ApprovalPreview) -> bool {
568    let color = std::io::stderr().is_terminal() && color_allowed();
569    ask(&mut std::io::stderr(), color, tool_name, preview)
570}
571
572/// [`terminal_prompt`] on stdout, as Python's REPL asks; the REPL has no JSON
573/// output to protect.
574pub fn stdout_prompt(tool_name: &str, preview: &ApprovalPreview) -> bool {
575    let color = std::io::stdout().is_terminal() && color_allowed();
576    ask(&mut std::io::stdout(), color, tool_name, preview)
577}
578
579fn color_allowed() -> bool {
580    std::env::var_os("NO_COLOR").is_none_or(|value| value.is_empty())
581}
582
583/// What the terminal prompt prints before reading the answer.
584///
585/// Beyond Python: the detail, the summary it falls back to, and the tool's name
586/// come from the model (an MCP server names its own tools), so their control
587/// characters are shown, not sent ([`crate::escape::show_controls`]). Otherwise a
588/// `\r` or an escape sequence could draw a harmless command over the one that runs.
589pub fn prompt_text(color: bool, tool_name: &str, preview: &ApprovalPreview) -> String {
590    use crate::escape::show_controls;
591    let detail = preview.detail.as_deref().unwrap_or(&preview.summary);
592    let tool_name = show_controls(tool_name);
593    let mut text = String::from("\n");
594    if let Some(warning) = &preview.warning {
595        let warning = show_controls(warning);
596        text.push_str(&if color {
597            format!("\x1b[1;33mwarning:\x1b[0m {warning}\n")
598        } else {
599            format!("warning: {warning}\n")
600        });
601    }
602    text.push_str(&show_controls(&if preview.full {
603        detail.to_owned()
604    } else {
605        cap_lines(detail, APPROVAL_DETAIL_LINES)
606    }));
607    text.push('\n');
608    text.push_str(&if color {
609        format!("\x1b[1;33mapprove \x1b[0m\x1b[1m{tool_name}?\x1b[0m\n")
610    } else {
611        format!("approve {tool_name}?\n")
612    });
613    text.push_str("  [y/N] ");
614    text
615}
616
617fn ask(out: &mut dyn Write, color: bool, tool_name: &str, preview: &ApprovalPreview) -> bool {
618    let _ = write!(out, "{}", prompt_text(color, tool_name, preview));
619    let _ = out.flush();
620
621    let mut answer = String::new();
622    match std::io::stdin().lock().read_line(&mut answer) {
623        Ok(0) | Err(_) => {
624            // Nobody is there to answer: decline, the safe default.
625            let _ = writeln!(out, "declined");
626            false
627        }
628        Ok(_) => matches!(answer.trim().to_lowercase().as_str(), "y" | "yes"),
629    }
630}
631
632/// At most `limit` lines of `text`, saying how many were dropped.
633pub fn cap_lines(text: &str, limit: usize) -> String {
634    let lines = crate::difflib::splitlines(text);
635    if lines.len() <= limit {
636        return text.to_owned();
637    }
638    format!(
639        "{}\n… truncated ({} more lines)",
640        lines[..limit].join("\n"),
641        lines.len() - limit
642    )
643}
644
645#[cfg(test)]
646mod tests {
647    use super::*;
648
649    #[test]
650    fn long_previews_are_capped() {
651        let text: Vec<String> = (0..45).map(|i| format!("line {i}")).collect();
652        let capped = cap_lines(&text.join("\n"), 40);
653        assert!(
654            capped.ends_with("line 39\n… truncated (5 more lines)"),
655            "{capped}"
656        );
657        assert_eq!(cap_lines("short", 40), "short");
658    }
659
660    fn preview(summary: &str, detail: Option<&str>) -> ApprovalPreview {
661        ApprovalPreview {
662            summary: summary.to_owned(),
663            detail: detail.map(str::to_owned),
664            lexer: None,
665            warning: None,
666            full: false,
667            agent: None,
668            change: None,
669            asker: None,
670        }
671    }
672
673    #[test]
674    fn the_prompt_shows_control_characters_instead_of_obeying_them() {
675        // `\r` would return the cursor and draw `echo hi` over `rm -rf x`.
676        let text = prompt_text(
677            false,
678            "run_command",
679            &preview("{}", Some("rm -rf x\recho hi")),
680        );
681        assert_eq!(text, "\nrm -rf x␍echo hi\napprove run_command?\n  [y/N] ");
682
683        // The summary it falls back to, an escape sequence, and a bidi override.
684        let text = prompt_text(
685            false,
686            "mcp\u{1b}[8m_tool",
687            &preview("{\"path\": \"a\u{202e}txt.sh\"}\u{1b}[2K", None),
688        );
689        assert_eq!(
690            text,
691            "\n{\"path\": \"a<U+202E>txt.sh\"}␛[2K\napprove mcp␛[8m_tool?\n  [y/N] "
692        );
693        assert!(!text.contains('\u{1b}') && !text.contains('\u{202e}'));
694    }
695
696    type Views = std::sync::Arc<Mutex<Vec<(Option<String>, Vec<String>)>>>;
697
698    /// A queue whose watcher keeps every view it is shown, by each question's call.
699    fn watched_queue() -> (PromptQueue, Views) {
700        let queue = PromptQueue::default();
701        let views: Views = std::sync::Arc::default();
702        let seen = std::sync::Arc::clone(&views);
703        queue.set_watcher(Some(std::sync::Arc::new(
704            move |asking: Option<&Question>, waiting: &[Question]| {
705                let call = |question: &Question| question.call.clone().unwrap_or_default();
706                seen.lock()
707                    .unwrap()
708                    .push((asking.map(call), waiting.iter().map(call).collect()));
709            },
710        )));
711        (queue, views)
712    }
713
714    fn question(call: &str) -> Question {
715        Question {
716            call: Some(call.to_owned()),
717            ..Question::new(QuestionKind::Approval)
718        }
719    }
720
721    /// Wait until the queue has shown `waiting` questions behind the one asked.
722    fn until_waiting(views: &Views, waiting: usize) {
723        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
724        while views
725            .lock()
726            .unwrap()
727            .last()
728            .is_none_or(|(_, queued)| queued.len() != waiting)
729        {
730            assert!(
731                std::time::Instant::now() < deadline,
732                "{:?}",
733                views.lock().unwrap()
734            );
735            std::thread::sleep(std::time::Duration::from_millis(5));
736        }
737    }
738
739    #[test]
740    fn questions_are_asked_in_arrival_order_and_the_watcher_sees_who_waits() {
741        let (queue, views) = watched_queue();
742        let asked = std::sync::Arc::new(Mutex::new(Vec::new()));
743        let (release, hold) = std::sync::mpsc::channel::<()>();
744        std::thread::scope(|scope| {
745            let first = scope.spawn(|| {
746                let hold = hold;
747                queue.ask(question("a"), || {
748                    asked.lock().unwrap().push("a");
749                    hold.recv().unwrap();
750                })
751            });
752            until_waiting(&views, 0);
753            let mut rest = Vec::new();
754            for (call, behind) in [("b", 1), ("c", 2)] {
755                let (queue, asked) = (&queue, &asked);
756                rest.push(
757                    scope.spawn(move || {
758                        queue.ask(question(call), || asked.lock().unwrap().push(call))
759                    }),
760                );
761                until_waiting(&views, behind);
762            }
763            release.send(()).unwrap();
764            assert!(first.join().unwrap().is_some());
765            for waiter in rest {
766                assert!(waiter.join().unwrap().is_some());
767            }
768        });
769        assert_eq!(*asked.lock().unwrap(), ["a", "b", "c"]);
770        let view = |asking: Option<&str>, waiting: &[&str]| {
771            (
772                asking.map(str::to_owned),
773                waiting
774                    .iter()
775                    .map(|call| (*call).to_owned())
776                    .collect::<Vec<_>>(),
777            )
778        };
779        assert_eq!(
780            *views.lock().unwrap(),
781            [
782                view(Some("a"), &[]),
783                view(Some("a"), &["b"]),
784                view(Some("a"), &["b", "c"]),
785                view(Some("b"), &["c"]),
786                view(Some("c"), &[]),
787                view(None, &[]),
788            ]
789        );
790    }
791
792    #[test]
793    fn questions_waiting_past_a_cancel_are_declined_without_being_asked() {
794        let (queue, views) = watched_queue();
795        let token = crate::agent::CancelToken::default();
796        queue.watch(token.clone());
797        let (release, hold) = std::sync::mpsc::channel::<()>();
798        std::thread::scope(|scope| {
799            let first = scope.spawn(|| {
800                let hold = hold;
801                queue.ask(question("a"), || hold.recv().unwrap())
802            });
803            until_waiting(&views, 0);
804            let second =
805                scope.spawn(|| queue.ask(question("b"), || panic!("asked after a cancel")));
806            until_waiting(&views, 1);
807            token.cancel();
808            release.send(()).unwrap();
809            assert!(first.join().unwrap().is_some());
810            assert!(second.join().unwrap().is_none());
811        });
812        assert_eq!(
813            views.lock().unwrap().last(),
814            Some(&(None, Vec::new())),
815            "the declined question left the queue empty"
816        );
817        // A question arriving after the cancel is declined at once.
818        assert!(queue.ask(question("c"), || ()).is_none());
819    }
820
821    #[test]
822    fn a_sub_agents_call_is_previewed_with_who_asks() {
823        let dir = std::env::temp_dir().join(format!("agent86-asker-{}", std::process::id()));
824        std::fs::create_dir_all(&dir).unwrap();
825        let mut ctx = ToolContext::new(&dir).unwrap();
826        assert_eq!(Asker::of(&ctx), None);
827        let run = std::sync::Arc::new(crate::subagent::SubagentRun::new(7, "writer", 2));
828        ctx.subagent = Some(run);
829        ctx.card = Some(std::sync::Arc::new(crate::subagent::Card::new(
830            "call_9", true,
831        )));
832        let asker = Asker::of(&ctx).unwrap();
833        assert_eq!(
834            asker,
835            Asker {
836                card: Some("call_9".into()),
837                run: 7,
838                agent: "writer".into(),
839                depth: 2,
840                worktree: None,
841                steps: 0,
842                cost_usd: 0.0,
843            }
844        );
845        let call = ToolCall {
846            id: "call_9/3".into(),
847            name: "write_file".into(),
848            arguments: serde_json::Map::new(),
849        };
850        let shown = ApprovalPreview {
851            asker: Some(Box::new(asker)),
852            ..preview("{}", None)
853        };
854        let question = Question::about(QuestionKind::Approval, "write_file", &call, &shown);
855        assert_eq!(question.call.as_deref(), Some("call_9/3"));
856        assert_eq!(question.agent.as_deref(), Some("writer"));
857        assert_eq!(question.card.as_deref(), Some("call_9"));
858        let _ = std::fs::remove_dir_all(&dir);
859    }
860
861    #[test]
862    fn the_prompts_own_colours_survive() {
863        let mut shown = preview("{}", Some("ls"));
864        shown.warning = Some("careful".to_owned());
865        let text = prompt_text(true, "run_command", &shown);
866        assert_eq!(
867            text,
868            "\n\u{1b}[1;33mwarning:\u{1b}[0m careful\nls\n\
869             \u{1b}[1;33mapprove \u{1b}[0m\u{1b}[1mrun_command?\u{1b}[0m\n  [y/N] "
870        );
871    }
872}