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