1use 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
16pub const SUMMARY_LIMIT: usize = 300;
18pub const APPROVAL_DETAIL_LINES: usize = 40;
20
21#[derive(Debug, Clone, PartialEq)]
23pub struct ApprovalPreview {
24 pub summary: String,
26 pub detail: Option<String>,
28 pub lexer: Option<&'static str>,
30 pub warning: Option<String>,
33 pub full: bool,
36 pub agent: Option<String>,
39 pub change: Option<crate::tools::FileChange>,
43 pub asker: Option<Box<Asker>>,
47}
48
49#[derive(Debug, Clone, PartialEq)]
54pub struct Asker {
55 pub card: Option<String>,
58 pub run: u64,
60 pub agent: String,
62 pub depth: u32,
63 pub worktree: Option<(String, String)>,
65 pub steps: u32,
67 pub cost_usd: f64,
69}
70
71impl Asker {
72 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum QuestionKind {
96 Approval,
98 Specialty,
100 Limit,
102 Secret,
104 Ui,
106 Ask,
108}
109
110impl QuestionKind {
111 pub fn as_str(self) -> &'static str {
112 match self {
113 Self::Approval => "approval",
114 Self::Specialty => "specialty",
115 Self::Limit => "limit",
116 Self::Secret => "secret",
117 Self::Ui => "ui",
118 Self::Ask => "ask",
119 }
120 }
121}
122
123#[derive(Debug, Clone, PartialEq, Eq)]
127pub struct Question {
128 pub kind: QuestionKind,
129 pub tool: Option<String>,
131 pub call: Option<String>,
134 pub agent: Option<String>,
136 pub card: Option<String>,
138 pub subject: Option<String>,
141}
142
143impl Question {
144 pub fn new(kind: QuestionKind) -> Self {
145 Self {
146 kind,
147 tool: None,
148 call: None,
149 agent: None,
150 card: None,
151 subject: None,
152 }
153 }
154
155 pub fn about(
157 kind: QuestionKind,
158 tool: &str,
159 call: &ToolCall,
160 preview: &ApprovalPreview,
161 ) -> Self {
162 let asker = preview.asker.as_ref();
163 Self {
164 tool: Some(tool.to_owned()),
165 call: Some(call.id.clone()),
166 agent: asker.map(|asker| asker.agent.clone()),
167 card: asker.and_then(|asker| asker.card.clone()),
168 ..Self::new(kind)
169 }
170 }
171}
172
173pub type QueueWatcher = std::sync::Arc<dyn Fn(Option<&Question>, &[Question]) + Send + Sync>;
177
178pub fn guarded_warning(path: &str) -> String {
180 format!(
181 "This writes agent86's own configuration or skills ({}), which changes what \
182 agent86 runs or is told from now on. Asked even in auto mode.",
183 crate::escape::show_controls(path)
184 )
185}
186
187pub type ApprovalPrompt = Box<dyn Fn(&str, &ApprovalPreview) -> bool + Send + Sync>;
189
190pub type CallApprovalPrompt = Box<dyn Fn(&ToolCall, &ApprovalPreview) -> bool + Send + Sync>;
194
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub struct ApprovalDecision {
197 pub approved: bool,
198 pub reason: &'static str,
199}
200
201#[derive(Clone, Default)]
209pub struct PromptQueue {
210 inner: std::sync::Arc<QueueInner>,
211}
212
213#[derive(Default)]
214struct QueueInner {
215 state: Mutex<QueueState>,
216 turn_over: std::sync::Condvar,
219 cancel: Mutex<Option<crate::agent::CancelToken>>,
220 watcher: Mutex<Option<QueueWatcher>>,
221}
222
223#[derive(Default)]
224struct QueueState {
225 next: u64,
226 asking: Option<Question>,
227 waiting: std::collections::VecDeque<(u64, Question)>,
229}
230
231struct Asked<'a>(&'a PromptQueue);
233
234impl Drop for Asked<'_> {
235 fn drop(&mut self) {
236 let mut state = self.0.lock();
237 state.asking = None;
238 if state.waiting.is_empty() {
241 self.0.report(&state);
242 }
243 self.0.inner.turn_over.notify_all();
244 }
245}
246
247impl std::fmt::Debug for PromptQueue {
248 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
249 formatter.write_str("PromptQueue")
250 }
251}
252
253impl PromptQueue {
254 pub fn watch(&self, token: crate::agent::CancelToken) {
256 *self
257 .inner
258 .cancel
259 .lock()
260 .unwrap_or_else(PoisonError::into_inner) = Some(token);
261 }
262
263 pub fn set_watcher(&self, watcher: Option<QueueWatcher>) {
265 *self
266 .inner
267 .watcher
268 .lock()
269 .unwrap_or_else(PoisonError::into_inner) = watcher;
270 }
271
272 pub fn ask<T>(&self, question: Question, ask: impl FnOnce() -> T) -> Option<T> {
275 let mut state = self.lock();
276 let waited = state.asking.is_some() || !state.waiting.is_empty();
277 let question = if waited {
278 let ticket = state.next;
279 state.next += 1;
280 state.waiting.push_back((ticket, question));
281 self.report(&state);
282 while state.asking.is_some()
283 || state.waiting.front().map(|(first, _)| *first) != Some(ticket)
284 {
285 state = self
286 .inner
287 .turn_over
288 .wait(state)
289 .unwrap_or_else(PoisonError::into_inner);
290 }
291 state
292 .waiting
293 .pop_front()
294 .map_or_else(|| unreachable!("first in line"), |(_, question)| question)
295 } else {
296 question
297 };
298 if self.cancelled() {
299 if waited {
300 self.report(&state);
301 self.inner.turn_over.notify_all();
302 }
303 return None;
304 }
305 state.asking = Some(question);
306 self.report(&state);
307 drop(state);
308 let _asked = Asked(self);
309 Some(ask())
310 }
311
312 fn lock(&self) -> std::sync::MutexGuard<'_, QueueState> {
313 self.inner
314 .state
315 .lock()
316 .unwrap_or_else(PoisonError::into_inner)
317 }
318
319 fn cancelled(&self) -> bool {
320 self.inner
321 .cancel
322 .lock()
323 .unwrap_or_else(PoisonError::into_inner)
324 .as_ref()
325 .is_some_and(crate::agent::CancelToken::is_cancelled)
326 }
327
328 fn report(&self, state: &QueueState) {
330 let watcher = self
331 .inner
332 .watcher
333 .lock()
334 .unwrap_or_else(PoisonError::into_inner)
335 .clone();
336 if let Some(watcher) = watcher {
337 let waiting: Vec<Question> = state
338 .waiting
339 .iter()
340 .map(|(_, question)| question.clone())
341 .collect();
342 watcher(state.asking.as_ref(), &waiting);
343 }
344 }
345}
346
347pub struct ApprovalGate {
349 mode: Mutex<ApprovalMode>,
352 pub prompt: Option<ApprovalPrompt>,
353 pub call_prompt: Option<CallApprovalPrompt>,
355 pub queue: PromptQueue,
357 pub specialty_prompt: Option<CallApprovalPrompt>,
361}
362
363impl ApprovalGate {
364 pub fn new(mode: ApprovalMode, prompt: Option<ApprovalPrompt>) -> Self {
365 Self {
366 mode: Mutex::new(mode),
367 prompt,
368 call_prompt: None,
369 queue: PromptQueue::default(),
370 specialty_prompt: None,
371 }
372 }
373
374 fn ask(&self, tool: &dyn Tool, call: &ToolCall, preview: &ApprovalPreview) -> Option<bool> {
377 self.ask_about(tool.name(), call, preview)
378 }
379
380 pub fn mode(&self) -> ApprovalMode {
381 *self.mode.lock().unwrap_or_else(PoisonError::into_inner)
382 }
383
384 pub fn set_mode(&self, mode: ApprovalMode) {
385 *self.mode.lock().unwrap_or_else(PoisonError::into_inner) = mode;
386 }
387
388 pub fn decide(&self, tool: &dyn Tool, call: &ToolCall, ctx: &ToolContext) -> ApprovalDecision {
389 let decision = |approved, reason| ApprovalDecision { approved, reason };
390 let scope = ctx.scope.as_deref();
391 if !ctx.scope_allows(tool.name()) {
394 return decision(false, "not permitted for this sub-agent");
395 }
396 let mode = crate::tools::stricter(Some(self.mode()), scope.and_then(|s| s.approval))
399 .unwrap_or(ApprovalMode::Ask);
400 if let Some(scope) = scope.filter(|s| s.confirm.iter().any(|t| t == tool.name())) {
403 if mode == ApprovalMode::Deny {
404 return decision(false, "blocked by approval policy (deny)");
405 }
406 if !self.can_ask() {
407 return decision(
408 false,
409 "this sub-agent's calls to this tool need approval, and no prompt is available",
410 );
411 }
412 let mut preview = build_preview(tool, call, ctx);
413 preview.warning = Some(format!(
414 "The '{}' sub-agent always asks before running {}.",
415 scope.label,
416 tool.name()
417 ));
418 preview.agent = Some(scope.label.clone());
419 return if self.ask(tool, call, &preview) == Some(true) {
420 decision(true, "approved by user")
421 } else {
422 decision(false, "declined by user")
423 };
424 }
425 if !tool.side_effecting() {
426 return decision(true, "read-only");
427 }
428 if let Some(path) = tool.guarded_target(&call.arguments, ctx) {
431 if mode == ApprovalMode::Deny {
432 return decision(false, "blocked by approval policy (deny)");
433 }
434 if !self.can_ask() {
435 return decision(
436 false,
437 "writing agent86's own configuration or skills needs approval, and no \
438 prompt is available",
439 );
440 }
441 let mut preview = build_preview(tool, call, ctx);
442 preview.warning = Some(guarded_warning(&path));
443 preview.agent = scope.map(|scope| scope.label.clone());
444 return if self.ask(tool, call, &preview) == Some(true) {
445 decision(true, "approved by user")
446 } else {
447 decision(false, "declined by user")
448 };
449 }
450 match mode {
451 ApprovalMode::Auto => decision(true, "auto-approved"),
452 ApprovalMode::Deny => decision(false, "blocked by approval policy (deny)"),
453 ApprovalMode::Ask => {
454 if !self.can_ask() {
455 return decision(false, "approval required but no prompt available");
456 }
457 let mut preview = build_preview(tool, call, ctx);
458 if let Some(scope) = scope {
460 preview.warning = Some(format!("Asked by the '{}' sub-agent.", scope.label));
461 preview.agent = Some(scope.label.clone());
462 }
463 if self.ask(tool, call, &preview) == Some(true) {
464 decision(true, "approved by user")
465 } else {
466 decision(false, "declined by user")
467 }
468 }
469 }
470 }
471
472 pub fn ask_specialty(&self, call: &ToolCall, preview: &ApprovalPreview) -> Option<bool> {
475 match &self.specialty_prompt {
476 Some(prompt) => {
477 let mut question =
478 Question::about(QuestionKind::Specialty, "delegate", call, preview);
479 question.subject = preview.agent.clone();
480 Some(
481 self.queue
482 .ask(question, || prompt(call, preview))
483 .unwrap_or(false),
484 )
485 }
486 None => self.ask_about("delegate", call, preview),
487 }
488 }
489
490 pub fn can_ask(&self) -> bool {
492 self.prompt.is_some() || self.call_prompt.is_some()
493 }
494
495 pub fn ask_about(
500 &self,
501 name: &str,
502 call: &ToolCall,
503 preview: &ApprovalPreview,
504 ) -> Option<bool> {
505 if !self.can_ask() {
506 return None;
507 }
508 Some(
510 self.queue
511 .ask(
512 Question::about(QuestionKind::Approval, name, call, preview),
513 || match &self.call_prompt {
514 Some(prompt) => prompt(call, preview),
515 None => self
516 .prompt
517 .as_ref()
518 .is_some_and(|prompt| prompt(name, preview)),
519 },
520 )
521 .unwrap_or(false),
522 )
523 }
524}
525
526pub fn build_preview(tool: &dyn Tool, call: &ToolCall, ctx: &ToolContext) -> ApprovalPreview {
532 let text = python_json_dumps(&Value::Object(call.arguments.clone()), false);
533 let summary = if text.chars().count() <= SUMMARY_LIMIT {
534 text
535 } else {
536 format!(
537 "{} ...",
538 text.chars().take(SUMMARY_LIMIT).collect::<String>()
539 )
540 };
541 let expanded = crate::tools::with_secrets(tool, call, ctx)
542 .map_or_else(|_| call.arguments.clone(), |call| call.arguments.clone());
543 ApprovalPreview {
544 summary,
545 detail: tool
546 .preview(&expanded, ctx)
547 .map(|detail| ctx.secrets.redact(&detail))
548 .filter(|detail| !detail.is_empty()),
549 lexer: tool.preview_lexer(),
550 warning: None,
551 full: false,
552 agent: None,
553 change: tool
554 .change(&expanded, ctx)
555 .map(|change| change.redacted(&ctx.secrets)),
556 asker: Asker::of(ctx).map(Box::new),
557 }
558}
559
560pub fn terminal_prompt_if_interactive() -> Option<ApprovalPrompt> {
563 std::io::stdin()
564 .is_terminal()
565 .then(|| Box::new(terminal_prompt) as ApprovalPrompt)
566}
567
568pub fn terminal_prompt(tool_name: &str, preview: &ApprovalPreview) -> bool {
574 let color = std::io::stderr().is_terminal() && color_allowed();
575 ask(&mut std::io::stderr(), color, tool_name, preview)
576}
577
578pub fn stdout_prompt(tool_name: &str, preview: &ApprovalPreview) -> bool {
581 let color = std::io::stdout().is_terminal() && color_allowed();
582 ask(&mut std::io::stdout(), color, tool_name, preview)
583}
584
585fn color_allowed() -> bool {
586 std::env::var_os("NO_COLOR").is_none_or(|value| value.is_empty())
587}
588
589pub fn prompt_text(color: bool, tool_name: &str, preview: &ApprovalPreview) -> String {
596 use crate::escape::show_controls;
597 let detail = preview.detail.as_deref().unwrap_or(&preview.summary);
598 let tool_name = show_controls(tool_name);
599 let mut text = String::from("\n");
600 if let Some(warning) = &preview.warning {
601 let warning = show_controls(warning);
602 text.push_str(&if color {
603 format!("\x1b[1;33mwarning:\x1b[0m {warning}\n")
604 } else {
605 format!("warning: {warning}\n")
606 });
607 }
608 text.push_str(&show_controls(&if preview.full {
609 detail.to_owned()
610 } else {
611 cap_lines(detail, APPROVAL_DETAIL_LINES)
612 }));
613 text.push('\n');
614 text.push_str(&if color {
615 format!("\x1b[1;33mapprove \x1b[0m\x1b[1m{tool_name}?\x1b[0m\n")
616 } else {
617 format!("approve {tool_name}?\n")
618 });
619 text.push_str(" [y/N] ");
620 text
621}
622
623fn ask(out: &mut dyn Write, color: bool, tool_name: &str, preview: &ApprovalPreview) -> bool {
624 let _ = write!(out, "{}", prompt_text(color, tool_name, preview));
625 let _ = out.flush();
626
627 let mut answer = String::new();
628 match std::io::stdin().lock().read_line(&mut answer) {
629 Ok(0) | Err(_) => {
630 let _ = writeln!(out, "declined");
632 false
633 }
634 Ok(_) => matches!(answer.trim().to_lowercase().as_str(), "y" | "yes"),
635 }
636}
637
638pub fn cap_lines(text: &str, limit: usize) -> String {
640 let lines = crate::difflib::splitlines(text);
641 if lines.len() <= limit {
642 return text.to_owned();
643 }
644 format!(
645 "{}\n… truncated ({} more lines)",
646 lines[..limit].join("\n"),
647 lines.len() - limit
648 )
649}
650
651#[cfg(test)]
652mod tests {
653 use super::*;
654
655 #[test]
656 fn long_previews_are_capped() {
657 let text: Vec<String> = (0..45).map(|i| format!("line {i}")).collect();
658 let capped = cap_lines(&text.join("\n"), 40);
659 assert!(
660 capped.ends_with("line 39\n… truncated (5 more lines)"),
661 "{capped}"
662 );
663 assert_eq!(cap_lines("short", 40), "short");
664 }
665
666 fn preview(summary: &str, detail: Option<&str>) -> ApprovalPreview {
667 ApprovalPreview {
668 summary: summary.to_owned(),
669 detail: detail.map(str::to_owned),
670 lexer: None,
671 warning: None,
672 full: false,
673 agent: None,
674 change: None,
675 asker: None,
676 }
677 }
678
679 #[test]
680 fn the_prompt_shows_control_characters_instead_of_obeying_them() {
681 let text = prompt_text(
683 false,
684 "run_command",
685 &preview("{}", Some("rm -rf x\recho hi")),
686 );
687 assert_eq!(text, "\nrm -rf x␍echo hi\napprove run_command?\n [y/N] ");
688
689 let text = prompt_text(
691 false,
692 "mcp\u{1b}[8m_tool",
693 &preview("{\"path\": \"a\u{202e}txt.sh\"}\u{1b}[2K", None),
694 );
695 assert_eq!(
696 text,
697 "\n{\"path\": \"a<U+202E>txt.sh\"}␛[2K\napprove mcp␛[8m_tool?\n [y/N] "
698 );
699 assert!(!text.contains('\u{1b}') && !text.contains('\u{202e}'));
700 }
701
702 type Views = std::sync::Arc<Mutex<Vec<(Option<String>, Vec<String>)>>>;
703
704 fn watched_queue() -> (PromptQueue, Views) {
706 let queue = PromptQueue::default();
707 let views: Views = std::sync::Arc::default();
708 let seen = std::sync::Arc::clone(&views);
709 queue.set_watcher(Some(std::sync::Arc::new(
710 move |asking: Option<&Question>, waiting: &[Question]| {
711 let call = |question: &Question| question.call.clone().unwrap_or_default();
712 seen.lock()
713 .unwrap()
714 .push((asking.map(call), waiting.iter().map(call).collect()));
715 },
716 )));
717 (queue, views)
718 }
719
720 fn question(call: &str) -> Question {
721 Question {
722 call: Some(call.to_owned()),
723 ..Question::new(QuestionKind::Approval)
724 }
725 }
726
727 fn until_waiting(views: &Views, waiting: usize) {
729 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
730 while views
731 .lock()
732 .unwrap()
733 .last()
734 .is_none_or(|(_, queued)| queued.len() != waiting)
735 {
736 assert!(
737 std::time::Instant::now() < deadline,
738 "{:?}",
739 views.lock().unwrap()
740 );
741 std::thread::sleep(std::time::Duration::from_millis(5));
742 }
743 }
744
745 #[test]
746 fn questions_are_asked_in_arrival_order_and_the_watcher_sees_who_waits() {
747 let (queue, views) = watched_queue();
748 let asked = std::sync::Arc::new(Mutex::new(Vec::new()));
749 let (release, hold) = std::sync::mpsc::channel::<()>();
750 std::thread::scope(|scope| {
751 let first = scope.spawn(|| {
752 let hold = hold;
753 queue.ask(question("a"), || {
754 asked.lock().unwrap().push("a");
755 hold.recv().unwrap();
756 })
757 });
758 until_waiting(&views, 0);
759 let mut rest = Vec::new();
760 for (call, behind) in [("b", 1), ("c", 2)] {
761 let (queue, asked) = (&queue, &asked);
762 rest.push(
763 scope.spawn(move || {
764 queue.ask(question(call), || asked.lock().unwrap().push(call))
765 }),
766 );
767 until_waiting(&views, behind);
768 }
769 release.send(()).unwrap();
770 assert!(first.join().unwrap().is_some());
771 for waiter in rest {
772 assert!(waiter.join().unwrap().is_some());
773 }
774 });
775 assert_eq!(*asked.lock().unwrap(), ["a", "b", "c"]);
776 let view = |asking: Option<&str>, waiting: &[&str]| {
777 (
778 asking.map(str::to_owned),
779 waiting
780 .iter()
781 .map(|call| (*call).to_owned())
782 .collect::<Vec<_>>(),
783 )
784 };
785 assert_eq!(
786 *views.lock().unwrap(),
787 [
788 view(Some("a"), &[]),
789 view(Some("a"), &["b"]),
790 view(Some("a"), &["b", "c"]),
791 view(Some("b"), &["c"]),
792 view(Some("c"), &[]),
793 view(None, &[]),
794 ]
795 );
796 }
797
798 #[test]
799 fn questions_waiting_past_a_cancel_are_declined_without_being_asked() {
800 let (queue, views) = watched_queue();
801 let token = crate::agent::CancelToken::default();
802 queue.watch(token.clone());
803 let (release, hold) = std::sync::mpsc::channel::<()>();
804 std::thread::scope(|scope| {
805 let first = scope.spawn(|| {
806 let hold = hold;
807 queue.ask(question("a"), || hold.recv().unwrap())
808 });
809 until_waiting(&views, 0);
810 let second =
811 scope.spawn(|| queue.ask(question("b"), || panic!("asked after a cancel")));
812 until_waiting(&views, 1);
813 token.cancel();
814 release.send(()).unwrap();
815 assert!(first.join().unwrap().is_some());
816 assert!(second.join().unwrap().is_none());
817 });
818 assert_eq!(
819 views.lock().unwrap().last(),
820 Some(&(None, Vec::new())),
821 "the declined question left the queue empty"
822 );
823 assert!(queue.ask(question("c"), || ()).is_none());
825 }
826
827 #[test]
828 fn a_sub_agents_call_is_previewed_with_who_asks() {
829 let dir = std::env::temp_dir().join(format!("agent86-asker-{}", std::process::id()));
830 std::fs::create_dir_all(&dir).unwrap();
831 let mut ctx = ToolContext::new(&dir).unwrap();
832 assert_eq!(Asker::of(&ctx), None);
833 let run = std::sync::Arc::new(crate::subagent::SubagentRun::new(7, "writer", 2));
834 ctx.subagent = Some(run);
835 ctx.card = Some(std::sync::Arc::new(crate::subagent::Card::new(
836 "call_9", true,
837 )));
838 let asker = Asker::of(&ctx).unwrap();
839 assert_eq!(
840 asker,
841 Asker {
842 card: Some("call_9".into()),
843 run: 7,
844 agent: "writer".into(),
845 depth: 2,
846 worktree: None,
847 steps: 0,
848 cost_usd: 0.0,
849 }
850 );
851 let call = ToolCall {
852 id: "call_9/3".into(),
853 name: "write_file".into(),
854 arguments: serde_json::Map::new(),
855 };
856 let shown = ApprovalPreview {
857 asker: Some(Box::new(asker)),
858 ..preview("{}", None)
859 };
860 let question = Question::about(QuestionKind::Approval, "write_file", &call, &shown);
861 assert_eq!(question.call.as_deref(), Some("call_9/3"));
862 assert_eq!(question.agent.as_deref(), Some("writer"));
863 assert_eq!(question.card.as_deref(), Some("call_9"));
864 let _ = std::fs::remove_dir_all(&dir);
865 }
866
867 #[test]
868 fn the_prompts_own_colours_survive() {
869 let mut shown = preview("{}", Some("ls"));
870 shown.warning = Some("careful".to_owned());
871 let text = prompt_text(true, "run_command", &shown);
872 assert_eq!(
873 text,
874 "\n\u{1b}[1;33mwarning:\u{1b}[0m careful\nls\n\
875 \u{1b}[1;33mapprove \u{1b}[0m\u{1b}[1mrun_command?\u{1b}[0m\n [y/N] "
876 );
877 }
878}