use crate::pyjson::python_json_dumps;
use crate::tools::{Tool, ToolContext};
use crate::types::{ApprovalMode, ToolCall};
use serde_json::Value;
use std::io::{BufRead, IsTerminal, Write};
use std::sync::{Mutex, PoisonError};
pub const SUMMARY_LIMIT: usize = 300;
pub const APPROVAL_DETAIL_LINES: usize = 40;
#[derive(Debug, Clone, PartialEq)]
pub struct ApprovalPreview {
pub summary: String,
pub detail: Option<String>,
pub lexer: Option<&'static str>,
pub warning: Option<String>,
pub full: bool,
pub agent: Option<String>,
pub change: Option<crate::tools::FileChange>,
pub asker: Option<Box<Asker>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Asker {
pub card: Option<String>,
pub run: u64,
pub agent: String,
pub depth: u32,
pub worktree: Option<(String, String)>,
pub steps: u32,
pub cost_usd: f64,
}
impl Asker {
pub fn of(ctx: &ToolContext) -> Option<Self> {
let run = ctx.subagent.as_ref()?;
let (steps, cost_usd) = run.progress();
Some(Self {
card: ctx.card.as_ref().map(|card| card.id.clone()),
run: run.run,
agent: run.name.clone(),
depth: run.depth,
worktree: ctx.worktree.as_ref().map(|worktree| {
(
crate::tools::display_path(&worktree.path),
worktree.branch.clone(),
)
}),
steps,
cost_usd,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuestionKind {
Approval,
Specialty,
Limit,
Secret,
Ui,
}
impl QuestionKind {
pub fn as_str(self) -> &'static str {
match self {
Self::Approval => "approval",
Self::Specialty => "specialty",
Self::Limit => "limit",
Self::Secret => "secret",
Self::Ui => "ui",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Question {
pub kind: QuestionKind,
pub tool: Option<String>,
pub call: Option<String>,
pub agent: Option<String>,
pub card: Option<String>,
pub subject: Option<String>,
}
impl Question {
pub fn new(kind: QuestionKind) -> Self {
Self {
kind,
tool: None,
call: None,
agent: None,
card: None,
subject: None,
}
}
pub fn about(
kind: QuestionKind,
tool: &str,
call: &ToolCall,
preview: &ApprovalPreview,
) -> Self {
let asker = preview.asker.as_ref();
Self {
tool: Some(tool.to_owned()),
call: Some(call.id.clone()),
agent: asker.map(|asker| asker.agent.clone()),
card: asker.and_then(|asker| asker.card.clone()),
..Self::new(kind)
}
}
}
pub type QueueWatcher = std::sync::Arc<dyn Fn(Option<&Question>, &[Question]) + Send + Sync>;
pub fn guarded_warning(path: &str) -> String {
format!(
"This writes agent86's own configuration or skills ({}), which changes what \
agent86 runs or is told from now on. Asked even in auto mode.",
crate::escape::show_controls(path)
)
}
pub type ApprovalPrompt = Box<dyn Fn(&str, &ApprovalPreview) -> bool + Send + Sync>;
pub type CallApprovalPrompt = Box<dyn Fn(&ToolCall, &ApprovalPreview) -> bool + Send + Sync>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ApprovalDecision {
pub approved: bool,
pub reason: &'static str,
}
#[derive(Clone, Default)]
pub struct PromptQueue {
inner: std::sync::Arc<QueueInner>,
}
#[derive(Default)]
struct QueueInner {
state: Mutex<QueueState>,
turn_over: std::sync::Condvar,
cancel: Mutex<Option<crate::agent::CancelToken>>,
watcher: Mutex<Option<QueueWatcher>>,
}
#[derive(Default)]
struct QueueState {
next: u64,
asking: Option<Question>,
waiting: std::collections::VecDeque<(u64, Question)>,
}
struct Asked<'a>(&'a PromptQueue);
impl Drop for Asked<'_> {
fn drop(&mut self) {
let mut state = self.0.lock();
state.asking = None;
if state.waiting.is_empty() {
self.0.report(&state);
}
self.0.inner.turn_over.notify_all();
}
}
impl std::fmt::Debug for PromptQueue {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("PromptQueue")
}
}
impl PromptQueue {
pub fn watch(&self, token: crate::agent::CancelToken) {
*self
.inner
.cancel
.lock()
.unwrap_or_else(PoisonError::into_inner) = Some(token);
}
pub fn set_watcher(&self, watcher: Option<QueueWatcher>) {
*self
.inner
.watcher
.lock()
.unwrap_or_else(PoisonError::into_inner) = watcher;
}
pub fn ask<T>(&self, question: Question, ask: impl FnOnce() -> T) -> Option<T> {
let mut state = self.lock();
let waited = state.asking.is_some() || !state.waiting.is_empty();
let question = if waited {
let ticket = state.next;
state.next += 1;
state.waiting.push_back((ticket, question));
self.report(&state);
while state.asking.is_some()
|| state.waiting.front().map(|(first, _)| *first) != Some(ticket)
{
state = self
.inner
.turn_over
.wait(state)
.unwrap_or_else(PoisonError::into_inner);
}
state
.waiting
.pop_front()
.map_or_else(|| unreachable!("first in line"), |(_, question)| question)
} else {
question
};
if self.cancelled() {
if waited {
self.report(&state);
self.inner.turn_over.notify_all();
}
return None;
}
state.asking = Some(question);
self.report(&state);
drop(state);
let _asked = Asked(self);
Some(ask())
}
fn lock(&self) -> std::sync::MutexGuard<'_, QueueState> {
self.inner
.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
}
fn cancelled(&self) -> bool {
self.inner
.cancel
.lock()
.unwrap_or_else(PoisonError::into_inner)
.as_ref()
.is_some_and(crate::agent::CancelToken::is_cancelled)
}
fn report(&self, state: &QueueState) {
let watcher = self
.inner
.watcher
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone();
if let Some(watcher) = watcher {
let waiting: Vec<Question> = state
.waiting
.iter()
.map(|(_, question)| question.clone())
.collect();
watcher(state.asking.as_ref(), &waiting);
}
}
}
pub struct ApprovalGate {
mode: Mutex<ApprovalMode>,
pub prompt: Option<ApprovalPrompt>,
pub call_prompt: Option<CallApprovalPrompt>,
pub queue: PromptQueue,
pub specialty_prompt: Option<CallApprovalPrompt>,
}
impl ApprovalGate {
pub fn new(mode: ApprovalMode, prompt: Option<ApprovalPrompt>) -> Self {
Self {
mode: Mutex::new(mode),
prompt,
call_prompt: None,
queue: PromptQueue::default(),
specialty_prompt: None,
}
}
fn ask(&self, tool: &dyn Tool, call: &ToolCall, preview: &ApprovalPreview) -> Option<bool> {
self.ask_about(tool.name(), call, preview)
}
pub fn mode(&self) -> ApprovalMode {
*self.mode.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn set_mode(&self, mode: ApprovalMode) {
*self.mode.lock().unwrap_or_else(PoisonError::into_inner) = mode;
}
pub fn decide(&self, tool: &dyn Tool, call: &ToolCall, ctx: &ToolContext) -> ApprovalDecision {
let decision = |approved, reason| ApprovalDecision { approved, reason };
let scope = ctx.scope.as_deref();
if !ctx.scope_allows(tool.name()) {
return decision(false, "not permitted for this sub-agent");
}
let mode = crate::tools::stricter(Some(self.mode()), scope.and_then(|s| s.approval))
.unwrap_or(ApprovalMode::Ask);
if let Some(scope) = scope.filter(|s| s.confirm.iter().any(|t| t == tool.name())) {
if mode == ApprovalMode::Deny {
return decision(false, "blocked by approval policy (deny)");
}
if !self.can_ask() {
return decision(
false,
"this sub-agent's calls to this tool need approval, and no prompt is available",
);
}
let mut preview = build_preview(tool, call, ctx);
preview.warning = Some(format!(
"The '{}' sub-agent always asks before running {}.",
scope.label,
tool.name()
));
preview.agent = Some(scope.label.clone());
return if self.ask(tool, call, &preview) == Some(true) {
decision(true, "approved by user")
} else {
decision(false, "declined by user")
};
}
if !tool.side_effecting() {
return decision(true, "read-only");
}
if let Some(path) = tool.guarded_target(&call.arguments, ctx) {
if mode == ApprovalMode::Deny {
return decision(false, "blocked by approval policy (deny)");
}
if !self.can_ask() {
return decision(
false,
"writing agent86's own configuration or skills needs approval, and no \
prompt is available",
);
}
let mut preview = build_preview(tool, call, ctx);
preview.warning = Some(guarded_warning(&path));
preview.agent = scope.map(|scope| scope.label.clone());
return if self.ask(tool, call, &preview) == Some(true) {
decision(true, "approved by user")
} else {
decision(false, "declined by user")
};
}
match mode {
ApprovalMode::Auto => decision(true, "auto-approved"),
ApprovalMode::Deny => decision(false, "blocked by approval policy (deny)"),
ApprovalMode::Ask => {
if !self.can_ask() {
return decision(false, "approval required but no prompt available");
}
let mut preview = build_preview(tool, call, ctx);
if let Some(scope) = scope {
preview.warning = Some(format!("Asked by the '{}' sub-agent.", scope.label));
preview.agent = Some(scope.label.clone());
}
if self.ask(tool, call, &preview) == Some(true) {
decision(true, "approved by user")
} else {
decision(false, "declined by user")
}
}
}
}
pub fn ask_specialty(&self, call: &ToolCall, preview: &ApprovalPreview) -> Option<bool> {
match &self.specialty_prompt {
Some(prompt) => {
let mut question =
Question::about(QuestionKind::Specialty, "delegate", call, preview);
question.subject = preview.agent.clone();
Some(
self.queue
.ask(question, || prompt(call, preview))
.unwrap_or(false),
)
}
None => self.ask_about("delegate", call, preview),
}
}
pub fn can_ask(&self) -> bool {
self.prompt.is_some() || self.call_prompt.is_some()
}
pub fn ask_about(
&self,
name: &str,
call: &ToolCall,
preview: &ApprovalPreview,
) -> Option<bool> {
if !self.can_ask() {
return None;
}
Some(
self.queue
.ask(
Question::about(QuestionKind::Approval, name, call, preview),
|| match &self.call_prompt {
Some(prompt) => prompt(call, preview),
None => self
.prompt
.as_ref()
.is_some_and(|prompt| prompt(name, preview)),
},
)
.unwrap_or(false),
)
}
}
pub fn build_preview(tool: &dyn Tool, call: &ToolCall, ctx: &ToolContext) -> ApprovalPreview {
let text = python_json_dumps(&Value::Object(call.arguments.clone()), false);
let summary = if text.chars().count() <= SUMMARY_LIMIT {
text
} else {
format!(
"{} ...",
text.chars().take(SUMMARY_LIMIT).collect::<String>()
)
};
let expanded = crate::tools::with_secrets(tool, call, ctx)
.map_or_else(|_| call.arguments.clone(), |call| call.arguments.clone());
ApprovalPreview {
summary,
detail: tool
.preview(&expanded, ctx)
.map(|detail| ctx.secrets.redact(&detail))
.filter(|detail| !detail.is_empty()),
lexer: tool.preview_lexer(),
warning: None,
full: false,
agent: None,
change: tool
.change(&expanded, ctx)
.map(|change| change.redacted(&ctx.secrets)),
asker: Asker::of(ctx).map(Box::new),
}
}
pub fn terminal_prompt_if_interactive() -> Option<ApprovalPrompt> {
std::io::stdin()
.is_terminal()
.then(|| Box::new(terminal_prompt) as ApprovalPrompt)
}
pub fn terminal_prompt(tool_name: &str, preview: &ApprovalPreview) -> bool {
let color = std::io::stderr().is_terminal() && color_allowed();
ask(&mut std::io::stderr(), color, tool_name, preview)
}
pub fn stdout_prompt(tool_name: &str, preview: &ApprovalPreview) -> bool {
let color = std::io::stdout().is_terminal() && color_allowed();
ask(&mut std::io::stdout(), color, tool_name, preview)
}
fn color_allowed() -> bool {
std::env::var_os("NO_COLOR").is_none_or(|value| value.is_empty())
}
pub fn prompt_text(color: bool, tool_name: &str, preview: &ApprovalPreview) -> String {
use crate::escape::show_controls;
let detail = preview.detail.as_deref().unwrap_or(&preview.summary);
let tool_name = show_controls(tool_name);
let mut text = String::from("\n");
if let Some(warning) = &preview.warning {
let warning = show_controls(warning);
text.push_str(&if color {
format!("\x1b[1;33mwarning:\x1b[0m {warning}\n")
} else {
format!("warning: {warning}\n")
});
}
text.push_str(&show_controls(&if preview.full {
detail.to_owned()
} else {
cap_lines(detail, APPROVAL_DETAIL_LINES)
}));
text.push('\n');
text.push_str(&if color {
format!("\x1b[1;33mapprove \x1b[0m\x1b[1m{tool_name}?\x1b[0m\n")
} else {
format!("approve {tool_name}?\n")
});
text.push_str(" [y/N] ");
text
}
fn ask(out: &mut dyn Write, color: bool, tool_name: &str, preview: &ApprovalPreview) -> bool {
let _ = write!(out, "{}", prompt_text(color, tool_name, preview));
let _ = out.flush();
let mut answer = String::new();
match std::io::stdin().lock().read_line(&mut answer) {
Ok(0) | Err(_) => {
let _ = writeln!(out, "declined");
false
}
Ok(_) => matches!(answer.trim().to_lowercase().as_str(), "y" | "yes"),
}
}
pub fn cap_lines(text: &str, limit: usize) -> String {
let lines = crate::difflib::splitlines(text);
if lines.len() <= limit {
return text.to_owned();
}
format!(
"{}\n… truncated ({} more lines)",
lines[..limit].join("\n"),
lines.len() - limit
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn long_previews_are_capped() {
let text: Vec<String> = (0..45).map(|i| format!("line {i}")).collect();
let capped = cap_lines(&text.join("\n"), 40);
assert!(
capped.ends_with("line 39\n… truncated (5 more lines)"),
"{capped}"
);
assert_eq!(cap_lines("short", 40), "short");
}
fn preview(summary: &str, detail: Option<&str>) -> ApprovalPreview {
ApprovalPreview {
summary: summary.to_owned(),
detail: detail.map(str::to_owned),
lexer: None,
warning: None,
full: false,
agent: None,
change: None,
asker: None,
}
}
#[test]
fn the_prompt_shows_control_characters_instead_of_obeying_them() {
let text = prompt_text(
false,
"run_command",
&preview("{}", Some("rm -rf x\recho hi")),
);
assert_eq!(text, "\nrm -rf x␍echo hi\napprove run_command?\n [y/N] ");
let text = prompt_text(
false,
"mcp\u{1b}[8m_tool",
&preview("{\"path\": \"a\u{202e}txt.sh\"}\u{1b}[2K", None),
);
assert_eq!(
text,
"\n{\"path\": \"a<U+202E>txt.sh\"}␛[2K\napprove mcp␛[8m_tool?\n [y/N] "
);
assert!(!text.contains('\u{1b}') && !text.contains('\u{202e}'));
}
type Views = std::sync::Arc<Mutex<Vec<(Option<String>, Vec<String>)>>>;
fn watched_queue() -> (PromptQueue, Views) {
let queue = PromptQueue::default();
let views: Views = std::sync::Arc::default();
let seen = std::sync::Arc::clone(&views);
queue.set_watcher(Some(std::sync::Arc::new(
move |asking: Option<&Question>, waiting: &[Question]| {
let call = |question: &Question| question.call.clone().unwrap_or_default();
seen.lock()
.unwrap()
.push((asking.map(call), waiting.iter().map(call).collect()));
},
)));
(queue, views)
}
fn question(call: &str) -> Question {
Question {
call: Some(call.to_owned()),
..Question::new(QuestionKind::Approval)
}
}
fn until_waiting(views: &Views, waiting: usize) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while views
.lock()
.unwrap()
.last()
.is_none_or(|(_, queued)| queued.len() != waiting)
{
assert!(
std::time::Instant::now() < deadline,
"{:?}",
views.lock().unwrap()
);
std::thread::sleep(std::time::Duration::from_millis(5));
}
}
#[test]
fn questions_are_asked_in_arrival_order_and_the_watcher_sees_who_waits() {
let (queue, views) = watched_queue();
let asked = std::sync::Arc::new(Mutex::new(Vec::new()));
let (release, hold) = std::sync::mpsc::channel::<()>();
std::thread::scope(|scope| {
let first = scope.spawn(|| {
let hold = hold;
queue.ask(question("a"), || {
asked.lock().unwrap().push("a");
hold.recv().unwrap();
})
});
until_waiting(&views, 0);
let mut rest = Vec::new();
for (call, behind) in [("b", 1), ("c", 2)] {
let (queue, asked) = (&queue, &asked);
rest.push(
scope.spawn(move || {
queue.ask(question(call), || asked.lock().unwrap().push(call))
}),
);
until_waiting(&views, behind);
}
release.send(()).unwrap();
assert!(first.join().unwrap().is_some());
for waiter in rest {
assert!(waiter.join().unwrap().is_some());
}
});
assert_eq!(*asked.lock().unwrap(), ["a", "b", "c"]);
let view = |asking: Option<&str>, waiting: &[&str]| {
(
asking.map(str::to_owned),
waiting
.iter()
.map(|call| (*call).to_owned())
.collect::<Vec<_>>(),
)
};
assert_eq!(
*views.lock().unwrap(),
[
view(Some("a"), &[]),
view(Some("a"), &["b"]),
view(Some("a"), &["b", "c"]),
view(Some("b"), &["c"]),
view(Some("c"), &[]),
view(None, &[]),
]
);
}
#[test]
fn questions_waiting_past_a_cancel_are_declined_without_being_asked() {
let (queue, views) = watched_queue();
let token = crate::agent::CancelToken::default();
queue.watch(token.clone());
let (release, hold) = std::sync::mpsc::channel::<()>();
std::thread::scope(|scope| {
let first = scope.spawn(|| {
let hold = hold;
queue.ask(question("a"), || hold.recv().unwrap())
});
until_waiting(&views, 0);
let second =
scope.spawn(|| queue.ask(question("b"), || panic!("asked after a cancel")));
until_waiting(&views, 1);
token.cancel();
release.send(()).unwrap();
assert!(first.join().unwrap().is_some());
assert!(second.join().unwrap().is_none());
});
assert_eq!(
views.lock().unwrap().last(),
Some(&(None, Vec::new())),
"the declined question left the queue empty"
);
assert!(queue.ask(question("c"), || ()).is_none());
}
#[test]
fn a_sub_agents_call_is_previewed_with_who_asks() {
let dir = std::env::temp_dir().join(format!("agent86-asker-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut ctx = ToolContext::new(&dir).unwrap();
assert_eq!(Asker::of(&ctx), None);
let run = std::sync::Arc::new(crate::subagent::SubagentRun::new(7, "writer", 2));
ctx.subagent = Some(run);
ctx.card = Some(std::sync::Arc::new(crate::subagent::Card::new(
"call_9", true,
)));
let asker = Asker::of(&ctx).unwrap();
assert_eq!(
asker,
Asker {
card: Some("call_9".into()),
run: 7,
agent: "writer".into(),
depth: 2,
worktree: None,
steps: 0,
cost_usd: 0.0,
}
);
let call = ToolCall {
id: "call_9/3".into(),
name: "write_file".into(),
arguments: serde_json::Map::new(),
};
let shown = ApprovalPreview {
asker: Some(Box::new(asker)),
..preview("{}", None)
};
let question = Question::about(QuestionKind::Approval, "write_file", &call, &shown);
assert_eq!(question.call.as_deref(), Some("call_9/3"));
assert_eq!(question.agent.as_deref(), Some("writer"));
assert_eq!(question.card.as_deref(), Some("call_9"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_prompts_own_colours_survive() {
let mut shown = preview("{}", Some("ls"));
shown.warning = Some("careful".to_owned());
let text = prompt_text(true, "run_command", &shown);
assert_eq!(
text,
"\n\u{1b}[1;33mwarning:\u{1b}[0m careful\nls\n\
\u{1b}[1;33mapprove \u{1b}[0m\u{1b}[1mrun_command?\u{1b}[0m\n [y/N] "
);
}
}