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}
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#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct Question {
122 pub kind: QuestionKind,
123 pub tool: Option<String>,
125 pub call: Option<String>,
128 pub agent: Option<String>,
130 pub card: Option<String>,
132 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 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
167pub type QueueWatcher = std::sync::Arc<dyn Fn(Option<&Question>, &[Question]) + Send + Sync>;
171
172pub 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
181pub type ApprovalPrompt = Box<dyn Fn(&str, &ApprovalPreview) -> bool + Send + Sync>;
183
184pub 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#[derive(Clone, Default)]
203pub struct PromptQueue {
204 inner: std::sync::Arc<QueueInner>,
205}
206
207#[derive(Default)]
208struct QueueInner {
209 state: Mutex<QueueState>,
210 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 waiting: std::collections::VecDeque<(u64, Question)>,
223}
224
225struct 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 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 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 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 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 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
341pub struct ApprovalGate {
343 mode: Mutex<ApprovalMode>,
346 pub prompt: Option<ApprovalPrompt>,
347 pub call_prompt: Option<CallApprovalPrompt>,
349 pub queue: PromptQueue,
351 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 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 if !ctx.scope_allows(tool.name()) {
388 return decision(false, "not permitted for this sub-agent");
389 }
390 let mode = crate::tools::stricter(Some(self.mode()), scope.and_then(|s| s.approval))
393 .unwrap_or(ApprovalMode::Ask);
394 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 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 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 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 pub fn can_ask(&self) -> bool {
486 self.prompt.is_some() || self.call_prompt.is_some()
487 }
488
489 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 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
520pub 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
554pub fn terminal_prompt_if_interactive() -> Option<ApprovalPrompt> {
557 std::io::stdin()
558 .is_terminal()
559 .then(|| Box::new(terminal_prompt) as ApprovalPrompt)
560}
561
562pub 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
572pub 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
583pub 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 let _ = writeln!(out, "declined");
626 false
627 }
628 Ok(_) => matches!(answer.trim().to_lowercase().as_str(), "y" | "yes"),
629 }
630}
631
632pub 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 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 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 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 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 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}