Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
29o deny-with-reason (server): a Deny can say why, and the bot hears it (#840)
Oleksandr Ivanchenkoecbc134f8b48
diff --git a/docs/approvals.md b/docs/approvals.mdindex 05aa3f91..8abe0054 100644--- a/docs/approvals.md+++ b/docs/approvals.md@@ -162,6 +162,8 @@ keep asking. The bot hears `DECLINED_BEFORE_TEXT` and the step shows as declinedthe person writes in that conversation again, and only in memory: a restart, another conversationor another bot asks as before. An unanswered card, a card its turn dropped, and kwnt's own refusalsdon't count, and a late Allow on an earlier card still runs that call (`src/mcp/declined.rs`).+A Deny with a reason (the person says why on the card) isn't remembered: the bot hears the reason,+may try the other way it points to, and that call gets its own card (29o).## Testsdiff --git a/src/broker/mod.rs b/src/broker/mod.rsindex 97a97b81..58c4460e 100644--- a/src/broker/mod.rs+++ b/src/broker/mod.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};use serde_json::Value;-use std::collections::{HashMap, HashSet};+use std::collections::{HashMap, HashSet, VecDeque};use std::sync::Arc;use tokio::sync::{oneshot, Mutex};@@ -37,8 +37,15 @@ pub struct PermissionBroker {/// 27b: what the person declined, per bot and conversation, until they write there again./// In memory only.pub declined: crate::mcp::declined::Declines,+ /// 29o: the person's reason on a Deny, by ticket, from [`resolve_with_reason`](Self::resolve_with_reason)+ /// until the waiting call takes it. At most [`DENY_REASONS_KEPT`]: a call whose turn ended+ /// in the same instant never takes its own, and the oldest goes first.+ deny_reasons: Arc<std::sync::Mutex<VecDeque<(String, String)>>>,}+/// 29o: how many untaken Deny reasons the broker keeps at most.+pub const DENY_REASONS_KEPT: usize = 32;+/// How long a late Allow waits for the resumed turn to make its call again.pub const GRANT_TTL: std::time::Duration = std::time::Duration::from_secs(30 * 60);@@ -70,6 +77,7 @@ impl PermissionBroker {always_allowed: Arc::new(Mutex::new(HashSet::new())),grants: Default::default(),declined: Default::default(),+ deny_reasons: Default::default(),store: Default::default(),loaded: Default::default(),}@@ -173,14 +181,50 @@ impl PermissionBroker {/// Resolves an approval ticket by sending the user's decision to the waiting oneshot channel.pub async fn resolve(&self, ticket_id: &str, decision: ApprovalDecision) -> bool {+ self.resolve_with_reason(ticket_id, decision, None).await+ }++ /// [`resolve`](Self::resolve), with the reason the person gave for a Deny (29o): kept for+ /// the waiting call ([`take_deny_reason`](Self::take_deny_reason)) before it hears the+ /// decision. Ignored for an Allow, and dropped when no call waits (a late answer).+ pub async fn resolve_with_reason(&self, ticket_id: &str, decision: ApprovalDecision, reason: Option<String>) -> bool {let mut map = self.pending.lock().await;- if let Some(sender) = map.remove(ticket_id) {- sender.send(decision).is_ok()- } else {- false+ let Some(sender) = map.remove(ticket_id) else {+ return false;+ };+ let reason = reason.filter(|_| decision == ApprovalDecision::Deny);+ if let Some(why) = reason.clone() {+ self.keep_deny_reason(ticket_id, why);+ }+ let sent = sender.send(decision).is_ok();+ if !sent && reason.is_some() {+ self.take_deny_reason(ticket_id);+ }+ sent+ }++ fn keep_deny_reason(&self, ticket_id: &str, reason: String) {+ if let Ok(mut kept) = self.deny_reasons.lock() {+ kept.retain(|(t, _)| t != ticket_id);+ while kept.len() >= DENY_REASONS_KEPT {+ kept.pop_front();+ }+ kept.push_back((ticket_id.to_string(), reason));}}+ /// 29o: the reason the person gave when they denied `ticket_id`, once; `None` for a plain Deny.+ pub fn take_deny_reason(&self, ticket_id: &str) -> Option<String> {+ let mut kept = self.deny_reasons.lock().ok()?;+ let i = kept.iter().position(|(t, _)| t == ticket_id)?;+ kept.remove(i).map(|(_, why)| why)+ }++ /// 29o: how many Deny reasons wait for a call to take them.+ pub fn deny_reasons_held(&self) -> usize {+ self.deny_reasons.lock().map(|k| k.len()).unwrap_or(0)+ }+/// Drops a pending ticket without a decision; its waiter sees the channel close.pub async fn cancel(&self, ticket_id: &str) -> bool {self.pending.lock().await.remove(ticket_id).is_some()@@ -276,6 +320,44 @@ impl PermissionBroker {mod tests {use super::*;+ fn ask(id: &str) -> ApprovalRequest {+ ApprovalRequest { id: id.into(), kwant_id: "k1".into(), tool_name: "Bash".into(), details: Value::Null }+ }++ /// 29o: a Deny's reason waits for its own call, once; an Allow, a late answer and a call that+ /// stopped waiting leave nothing behind, and untaken ones never pile up.+ #[tokio::test]+ async fn a_deny_reason_waits_for_its_own_call_only() {+ let b = PermissionBroker::new();+ let rx = b.request_approval(ask("a1")).await;+ assert!(b.resolve_with_reason("a1", ApprovalDecision::Deny, Some("use staging".into())).await);+ assert_eq!(rx.await.unwrap(), ApprovalDecision::Deny);+ assert_eq!(b.take_deny_reason("a1").as_deref(), Some("use staging"));+ assert_eq!(b.take_deny_reason("a1"), None, "taken once");++ let rx = b.request_approval(ask("a2")).await;+ assert!(b.resolve_with_reason("a2", ApprovalDecision::AllowOnce, Some("why".into())).await);+ assert_eq!(rx.await.unwrap(), ApprovalDecision::AllowOnce);+ assert_eq!(b.deny_reasons_held(), 0, "an Allow keeps no reason");++ assert!(!b.resolve_with_reason("gone", ApprovalDecision::Deny, Some("late".into())).await);+ assert_eq!(b.deny_reasons_held(), 0, "no call waits: dropped");++ let rx = b.request_approval(ask("a3")).await;+ drop(rx);+ assert!(!b.resolve_with_reason("a3", ApprovalDecision::Deny, Some("nobody hears".into())).await);+ assert_eq!(b.deny_reasons_held(), 0, "the call stopped waiting: dropped");++ for i in 0..DENY_REASONS_KEPT + 5 {+ let id = format!("n{i}");+ let _rx = b.request_approval(ask(&id)).await;+ assert!(b.resolve_with_reason(&id, ApprovalDecision::Deny, Some("x".into())).await);+ }+ assert_eq!(b.deny_reasons_held(), DENY_REASONS_KEPT);+ assert_eq!(b.take_deny_reason("n0"), None, "the oldest went first");+ assert!(b.take_deny_reason(&format!("n{}", DENY_REASONS_KEPT + 4)).is_some());+ }+#[tokio::test]async fn without_a_store_an_answer_lasts_for_this_broker_only() {let b = PermissionBroker::new();diff --git a/src/mcp/mod.rs b/src/mcp/mod.rsindex 6b7e97fe..786eca3a 100644--- a/src/mcp/mod.rs+++ b/src/mcp/mod.rs@@ -465,6 +465,62 @@ pub enum ApprovalOutcome {/// What the bot is told when the person refused a call: that, and [`NOT_ANOTHER_WAY_TEXT`].pub const DENIED_TEXT: &str = "The user denied this tool call. Don't try it again or another way unless the person asks.";+/// 29o: the longest reason, in chars, the person can give with a Deny ([`deny_reason`]).+pub const DENY_REASON_MAX: usize = 500;++/// 29o: the person's reason on a Deny as the bot hears it: control characters (newlines, tabs)+/// and runs of spaces become one space, trimmed, cut at [`DENY_REASON_MAX`] chars. `None` when+/// nothing is left: a plain Deny.+pub fn deny_reason(raw: &str) -> Option<String> {+ let flat: String = raw.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();+ let line = flat.split_whitespace().collect::<Vec<_>>().join(" ");+ let cut: String = line.chars().take(DENY_REASON_MAX).collect();+ let cut = cut.trim_end();+ (!cut.is_empty()).then(|| cut.to_string())+}++/// 29o: what the bot is told when the person refused a call and said why. Unlike+/// [`DENIED_TEXT`] it may try another way the person pointed to; that call asks again. Its first+/// sentence is [`DENIED_TEXT`]'s, word for word: the activity log pairs a CLI's denial with the+/// person's card by that sentence (28b/28q), so the step still ends "You said no; nothing ran".+pub fn denied_with_reason_text(reason: &str) -> String {+ format!(+ "The user denied this tool call. They said why: \"{reason}\". Don't make this same call again. \+If what they said points to another way, you may try that; it will ask them again. Otherwise say in your reply what you couldn't do."+ )+}++tokio::task_local! {+ /// 29o: where [`tell_deny_reason`] leaves the person's reason for [`hear_deny_reason`].+ static DENY_REASON: Arc<Mutex<Option<String>>>;+}++/// 29o: runs `decide` (an approver's [`ToolApprover::decide`] or+/// [`decide_granted`](ToolApprover::decide_granted)) and hears the reason the person gave if they+/// denied its card with one. [`ApprovalOutcome`] stays `Copy` and every approver that wraps+/// another passes it through unchanged: the reason travels beside it, in this task only.+pub async fn hear_deny_reason<F>(decide: F) -> (ApprovalOutcome, Option<String>)+where+ F: std::future::Future<Output = ApprovalOutcome>,+{+ let slot = Arc::new(Mutex::new(None));+ let outcome = DENY_REASON.scope(slot.clone(), decide).await;+ let reason = slot.lock().ok().and_then(|mut s| s.take());+ (outcome, reason.filter(|_| outcome == ApprovalOutcome::Denied))+}++/// 29o: hands the person's reason for a Deny to the caller waiting in [`hear_deny_reason`];+/// false when nobody in this task listens (the bot then hears [`DENIED_TEXT`]).+pub fn tell_deny_reason(reason: String) -> bool {+ DENY_REASON+ .try_with(|slot| {+ if let Ok(mut s) = slot.lock() {+ *s = Some(reason);+ }+ })+ .is_ok()+}+/// 27b: the end of [`DENIED_TEXT`], for the bot only; a step's detail leaves it out.pub const NOT_ANOTHER_WAY_TEXT: &str = "Don't try it again or another way unless the person asks.";/// 27b: what the bot is told when kwant refused a call because the person already said no to one@@ -542,6 +598,15 @@ impl ApprovalOutcome {}}+ /// [`refusal_text`](Self::refusal_text), or on the person's Deny with a reason (29o)+ /// [`denied_with_reason_text`].+ pub fn refusal(self, reason: Option<&str>) -> String {+ match (self, reason) {+ (ApprovalOutcome::Denied, Some(why)) => denied_with_reason_text(why),+ _ => self.refusal_text().to_string(),+ }+ }+/// The record status of a call that didn't run.pub fn record_status(self) -> &'static str {match self {@@ -747,6 +812,90 @@ mod folder_file_tests {mod tests {use super::*;+ /// 29o: a Deny's reason is one line, trimmed and at most 500 chars; nothing left is a plain Deny.+ #[test]+ fn a_deny_reason_is_one_trimmed_line_of_at_most_500_chars() {+ assert_eq!(deny_reason(" use the staging database ").as_deref(), Some("use the staging database"));+ assert_eq!(deny_reason("push\nwithout\r\n--force\there\u{7}now").as_deref(), Some("push without --force here now"));+ assert_eq!(deny_reason("a \n\n b").as_deref(), Some("a b"));+ for empty in ["", " ", "\n\t\r", "\u{0}"] {+ assert_eq!(deny_reason(empty), None, "{empty:?}");+ }+ let long = "é".repeat(501);+ assert_eq!(deny_reason(&long).map(|r| r.chars().count()), Some(DENY_REASON_MAX));+ assert_eq!(deny_reason(&"x".repeat(500)).map(|r| r.len()), Some(500));+ // Cut at 500, then trimmed: no trailing space+ let edge = format!("{} y", "x".repeat(499));+ assert_eq!(deny_reason(&edge), Some("x".repeat(499)));+ }++ /// 29o: a plain Deny is still told [`DENIED_TEXT`] word for word; a Deny with a reason hears it,+ /// and may try another way the person pointed to. Other refusals ignore a reason.+ #[test]+ fn a_deny_with_a_reason_tells_the_bot_why() {+ assert_eq!(ApprovalOutcome::Denied.refusal(None), DENIED_TEXT);+ assert_eq!(+ ApprovalOutcome::Denied.refusal(Some("use the staging database")),+ "The user denied this tool call. They said why: \"use the staging database\". Don't make this same call again. \+If what they said points to another way, you may try that; it will ask them again. Otherwise say in your reply what you couldn't do."+ );+ for other in [ApprovalOutcome::DeclinedBefore, ApprovalOutcome::Unanswered, ApprovalOutcome::Rehearsed] {+ assert_eq!(other.refusal(Some("why")), other.refusal_text(), "{other:?}");+ }+ }++ /// 29o round 2: a Deny with a reason, as the claude CLI reports it back (an error carrying the+ /// permission prompt's message), still ends the tool step `declined` in the person's words,+ /// paired with its card; the reason and the rest of the bot's text stay out of the step.+ #[test]+ fn a_deny_with_a_reason_still_ends_the_step_declined() {+ use crate::drivers::activity::ActivityLog;+ use crate::drivers::events::RuntimeEvent;+ let first = |t: &str| t.split_inclusive('.').next().unwrap_or(t).to_string();+ let said = ApprovalOutcome::Denied.refusal(Some("push without --force"));+ assert_eq!(first(&said), first(DENIED_TEXT), "same first sentence as DENIED_TEXT");+ for text in [with_no_false_claims(&said), said.clone()] {+ let mut log = ActivityLog::default();+ log.wait("approval", "t1", "Waiting for your approval: Running `git push --force`", Some("Bash"));+ log.settle("t1", "declined");+ log.observe(&RuntimeEvent::ToolCallPending {+ id: "a".into(),+ name: "Bash".into(),+ args: serde_json::json!({"command": "git push --force"}),+ });+ let ended = log.observe(&RuntimeEvent::ToolCallCompleted {+ id: "a".into(),+ result: serde_json::json!({"status": "error", "error": text}),+ });+ assert_eq!(+ (ended[0].kind, ended[0].status, ended[0].detail.as_deref()),+ ("tool", "declined", Some(DENIED_STEP_DETAIL))+ );+ let shown = serde_json::to_string(log.steps()).unwrap();+ assert!(!shown.contains("without --force") && !shown.contains("They said why"), "{shown}");+ }+ }++ /// 29o: the reason reaches only the call that is listening, and only on a denial.+ #[tokio::test]+ async fn a_deny_reason_is_heard_only_by_its_own_call() {+ let denied = || async {+ assert!(tell_deny_reason("use staging".into()));+ ApprovalOutcome::Denied+ };+ assert_eq!(hear_deny_reason(denied()).await, (ApprovalOutcome::Denied, Some("use staging".into())));+ // Nobody listening: dropped+ assert!(!tell_deny_reason("lost".into()));+ // A reason left beside an outcome that isn't a denial is never heard+ let allowed = async {+ tell_deny_reason("why".into());+ ApprovalOutcome::Allowed+ };+ assert_eq!(hear_deny_reason(allowed).await, (ApprovalOutcome::Allowed, None));+ // A plain Deny has none+ assert_eq!(hear_deny_reason(async { ApprovalOutcome::Denied }).await, (ApprovalOutcome::Denied, None));+ }+/// 27b: a first no tells the bot not to try another way; a call refused because of an earlier/// no says so, and is recorded as a denial (no extra reminder, nothing claimed done).#[test]diff --git a/src/mcp/session.rs b/src/mcp/session.rsindex 3cb27659..989b11e5 100644--- a/src/mcp/session.rs+++ b/src/mcp/session.rs@@ -330,12 +330,16 @@ impl McpToolSession {}Ok(pass) => {// A push the person's Retry or Override covers skips the ordinary card (0.9.7)- let outcome = match &pass.grant {- Some(g) => self.ctx.approver.decide_granted(req, g).await,- None => self.ctx.approver.decide(req).await,- };+ // 29o: and a Deny may come with the person's reason+ let (outcome, reason) = super::hear_deny_reason(async {+ match &pass.grant {+ Some(g) => self.ctx.approver.decide_granted(req, g).await,+ None => self.ctx.approver.decide(req).await,+ }+ })+ .await;if !outcome.allowed() {- (outcome.record_status(), outcome.refusal_text().to_string())+ (outcome.record_status(), outcome.refusal(reason.as_deref()))} else if let Some(why) = self.ctx.approver.prepush_use(&pass.overrides).await {held();("denied", why)diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rsindex e7af19f7..36b24778 100644--- a/src/server/mcp_runtime.rs+++ b/src/server/mcp_runtime.rs@@ -575,8 +575,15 @@ impl BrokerApprover {// 27b: only the person's own no is remembered, not a dropped card. A card that was// withdrawn or whose channel dropped (28k) runs nothing either, but it wasn't the// person's no, so its step settled `stopped` above+ // 29o: a Deny with the person's reason goes back to the call, and its family isn't+ // remembered: they said what to do instead, and the adjusted call gets its own cardOk(Ok(ApprovalDecision::Deny)) => {- self.broker.declined.record(&req.kwant_id, &self.conversation, &families, &ticket);+ // A reason nobody is listening for (no caller scoped by `hear_deny_reason`) means+ // the bot hears the plain DENIED_TEXT, so the no is remembered as a plain one+ let heard = self.broker.take_deny_reason(&ticket).is_some_and(mcp::tell_deny_reason);+ if !heard {+ self.broker.declined.record(&req.kwant_id, &self.conversation, &families, &ticket);+ }ApprovalOutcome::Denied}// The card was withdrawn or its channel dropped (28k): nothing runs, but it wasn't@@ -617,6 +624,19 @@ impl BrokerApprover {}}+/// How an approval card's step settles once its wait ends with `decision`: "ok" on an Allow,+/// "declined" only on the person's Deny, and "stopped" when the card was withdrawn or its+/// channel dropped with no answer (28k: nobody pressed Deny, so it isn't the person's no). `None`+/// when the wait ran out: the timeout path settles it (`unanswered` or `stopped`).+fn card_settles<E, T>(decision: &Result<Result<ApprovalDecision, E>, T>) -> Option<&'static str> {+ match decision {+ Ok(Ok(ApprovalDecision::AllowOnce | ApprovalDecision::AlwaysAllowSession)) => Some("ok"),+ Ok(Ok(ApprovalDecision::Deny)) => Some("declined"),+ Ok(Err(_)) => Some("stopped"),+ Err(_) => None,+ }+}+/// 26h: why a call to a renamed credit app (FLUX, Picsart) asks: the bot's stored server with/// this name is at the app's address ([`mcp::payment_floor::credits_reason`]). Calls kwnt runs/// itself already carry the address in `req.payment`; this covers the ones an agent CLI asks@@ -657,19 +677,6 @@ pub async fn home_server_names(db: &Database, servers: &[McpServer]) -> Vec<Strinames}-/// How an approval card's step settles once its wait ends with `decision`: "ok" on an Allow,-/// "declined" only on the person's Deny, and "stopped" when the card was withdrawn or its-/// channel dropped with no answer (28k: nobody pressed Deny, so it isn't the person's no). `None`-/// when the wait ran out: the timeout path settles it (`unanswered` or `stopped`).-fn card_settles<E, T>(decision: &Result<Result<ApprovalDecision, E>, T>) -> Option<&'static str> {- match decision {- Ok(Ok(ApprovalDecision::AllowOnce | ApprovalDecision::AlwaysAllowSession)) => Some("ok"),- Ok(Ok(ApprovalDecision::Deny)) => Some("declined"),- Ok(Err(_)) => Some("stopped"),- Err(_) => None,- }-}-/// 26f: whether `req` acts on a lock, a door, a garage door, a gate or an alarm on a Home/// Assistant server ([`mcp::home_floor`]), so it always asks. What the server is comes from what/// it said on kwnt's last connection to it in this run, else from what its last test stored; one@@ -1450,15 +1457,16 @@ async fn decide(session: &PermissionSession, args: &Value, smart: bool, grant: Opayment: None,};// A push the person's Retry or Override covers skips the ordinary card (0.9.7)- let approval = async {+ // 29o: and a Deny may come with the person's reason+ let approval = mcp::hear_deny_reason(async {match grant {Some(g) => session.ctx.approver.decide_granted(req, g).await,None => session.ctx.approver.decide(req).await,}- };+ });// Dropping the approval withdraws its card when the turn ends first- let outcome = tokio::select! {- outcome = approval => outcome,+ let (outcome, reason) = tokio::select! {+ heard = approval => heard,_ = session.ended.cancelled() => {session.ctx.record(cancelled_record(&tool_use_id, tool_name, server, tool, &input));return json!({"behavior": "deny", "message": "The turn ended before the user answered."});@@ -1480,9 +1488,9 @@ async fn decide(session: &PermissionSession, args: &Value, smart: bool, grant: Oif outcome.allowed() {json!({"behavior": "allow", "updatedInput": input})} else if remind {- json!({"behavior": "deny", "message": mcp::with_no_false_claims(outcome.refusal_text())})+ json!({"behavior": "deny", "message": mcp::with_no_false_claims(&outcome.refusal(reason.as_deref()))})} else {- json!({"behavior": "deny", "message": outcome.refusal_text()})+ json!({"behavior": "deny", "message": outcome.refusal(reason.as_deref())})}}@@ -1743,6 +1751,55 @@ mod expired_tests {}}+#[cfg(test)]+mod card_settles_tests {+ use super::*;++ /// 28k: only the person's Deny settles a card `declined`. A card that was withdrawn, or whose+ /// channel dropped, settles `stopped`: nobody pressed Deny. The bot's outcome is `Denied`+ /// either way (nothing runs), and it hears the same text.+ #[tokio::test]+ async fn a_withdrawn_card_settles_stopped_and_only_a_deny_settles_declined() {+ let broker = PermissionBroker::new();+ let ask = |id: &str| ApprovalRequest {+ id: id.into(),+ kwant_id: "k1".into(),+ tool_name: "Bash".into(),+ details: Value::Null,+ };+ let wait = |rx: tokio::sync::oneshot::Receiver<ApprovalDecision>| tokio::time::timeout(Duration::from_secs(5), rx);++ // Withdrawn: the broker drops the ticket with no decision+ let rx = broker.request_approval(ask("apr_withdrawn")).await;+ assert!(broker.cancel("apr_withdrawn").await);+ let withdrawn = wait(rx).await;+ assert!(matches!(withdrawn, Ok(Err(_))), "the waiter sees the channel close");+ assert_eq!(card_settles(&withdrawn), Some("stopped"));++ // The person pressed Deny+ let rx = broker.request_approval(ask("apr_deny")).await;+ assert!(broker.resolve("apr_deny", ApprovalDecision::Deny).await);+ assert_eq!(card_settles(&wait(rx).await), Some("declined"));++ // Allow, once or for the session+ for d in [ApprovalDecision::AllowOnce, ApprovalDecision::AlwaysAllowSession] {+ let rx = broker.request_approval(ask("apr_ok")).await;+ assert!(broker.resolve("apr_ok", d).await);+ assert_eq!(card_settles(&wait(rx).await), Some("ok"));+ }++ // The wait ran out: the timeout path settles it, not this+ let rx = broker.request_approval(ask("apr_slow")).await;+ let ran_out = tokio::time::timeout(Duration::from_millis(1), rx).await;+ assert!(ran_out.is_err());+ assert_eq!(card_settles(&ran_out), None);++ // What the bot hears doesn't change: a withdrawn card and a Deny are both `Denied`+ assert_eq!(ApprovalOutcome::Denied.refusal_text(), mcp::DENIED_TEXT);+ assert_eq!(ApprovalOutcome::Denied.record_status(), "denied");+ }+}+#[cfg(test)]mod engine_call_id_tests {use super::*;@@ -1871,14 +1928,69 @@ mod declined_tests {Drop,/// Nobody answers before the approver stops waiting.Nothing,+ /// 29o: answered through the app's route, `{decision, reason}` as the card sends it.+ Route(&'static str, Option<&'static str>),+ }++ /// 29o: the person answers card `id` through the app's route with `{decision, reason}`:+ /// the route's reply.+ async fn answer_route(state: &AppState, id: &str, decision: &str, reason: Option<&str>) -> Value {+ let mut body = json!({"decision": decision});+ if let Some(r) = reason {+ body["reason"] = json!(r);+ }+ let payload = serde_json::from_value(body).expect("the card's body parses");+ let resp = super::super::routes::resolve_approval(State(state.clone()), Path(id.to_string()), Json(payload))+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ serde_json::from_slice(&to_bytes(resp.into_body(), usize::MAX).await.unwrap()).unwrap()+ }++ /// 29o: what the bot hears when the person said no with `reason` (the brief's words).+ fn said_why(reason: &str) -> String {+ format!(+ "The user denied this tool call. They said why: \"{reason}\". Don't make this same call again. \+If what they said points to another way, you may try that; it will ask them again. Otherwise say in your reply what you couldn't do."+ )+ }++ const fn why(reason: &'static str) -> Answer {+ Answer::Route("deny", Some(reason))}/// `a.decide(req)`, answering the card it shows with `answer`: the outcome and the card's- /// ticket, `None` when no card went out.+ /// ticket, `None` when no card went out. Like both real callers (the MCP session and the+ /// permission prompt) it listens for a Deny's reason ([`mcp::hear_deny_reason`]).async fn ask(e: &Env, a: &BrokerApprover, req: ToolApprovalRequest, answer: Answer) -> (ApprovalOutcome, Option<String>) {+ let (outcome, card, _) = asked(e, a, req, answer, true).await;+ (outcome, card)+ }++ /// [`ask`] from a caller that doesn't listen for a Deny's reason: the bot would hear the+ /// plain `DENIED_TEXT`.+ async fn ask_unheard(e: &Env, a: &BrokerApprover, req: ToolApprovalRequest, answer: Answer) -> (ApprovalOutcome, Option<String>) {+ let (outcome, card, _) = asked(e, a, req, answer, false).await;+ (outcome, card)+ }++ /// [`ask`], also giving the reason the call heard (`None` when `listening` is false).+ async fn asked(+ e: &Env,+ a: &BrokerApprover,+ req: ToolApprovalRequest,+ answer: Answer,+ listening: bool,+ ) -> (ApprovalOutcome, Option<String>, Option<String>) {let mut events = e.state.event_sender.subscribe();let broker = e.state.broker.clone();- let decide = a.decide(req);+ let decide = async move {+ if listening {+ mcp::hear_deny_reason(a.decide(req)).await+ } else {+ (a.decide(req).await, None)+ }+ };tokio::pin!(decide);let mut card = None;let outcome = loop {@@ -1891,6 +2003,9 @@ mod declined_tests {Answer::Decide(d) => assert!(broker.resolve(&id, d).await),Answer::Drop => assert!(broker.cancel(&id).await),Answer::Nothing => {}+ Answer::Route(d, r) => {+ answer_route(&e.state, &id, d, r).await;+ }}card = Some(id);}@@ -1902,7 +2017,8 @@ mod declined_tests {panic!("a card went out after the call was settled: {id}");}}- (outcome, card)+ let (outcome, heard) = outcome;+ (outcome, card, heard)}/// The bot's approvals rows: (status, details).@@ -2064,8 +2180,12 @@ mod declined_tests {resp = &mut prompt => break resp.unwrap(),ev = events.recv() => {if let Ok(RuntimeEvent::ApprovalRequired { id, .. }) = ev {- if let Answer::Decide(d) = answer.clone() {- assert!(e.state.broker.resolve(&id, d).await);+ match answer.clone() {+ Answer::Decide(d) => assert!(e.state.broker.resolve(&id, d).await),+ Answer::Route(d, r) => {+ answer_route(&e.state, &id, d, r).await;+ }+ Answer::Drop | Answer::Nothing => {}}card = Some(id);}@@ -2091,6 +2211,153 @@ mod declined_tests {assert_eq!(reply, json!({"behavior": "deny", "message": mcp::DECLINED_BEFORE_TEXT}));}+ /// 29o (a, b, c) on claude's permission prompt: the card's `{decision: "deny", reason}` reaches+ /// the bot as one trimmed line of at most 500 chars, and the same family asks again; the old+ /// body, an empty reason and a plain Deny still tell it `DENIED_TEXT` word for word, and only+ /// the plain Deny is remembered (27b).+ #[tokio::test]+ async fn claude_hears_why_the_person_said_no() {+ let e = setup().await;+ let denied = |message: String| json!({"behavior": "deny", "message": message});+ let push = |args: &str| json!({"command": format!("git push {args}")});+ let (reply, card) = claude_asks(&e, "Bash", push("--force origin main"), why(" push without\n--force \r\n")).await;+ assert!(card.is_some());+ assert_eq!(reply, denied(said_why("push without --force")));++ // Capped at 500 chars, on a char boundary+ let long: &'static str = "é".repeat(501).leak();+ let (reply, card) = claude_asks(&e, "Bash", push("origin main"), why(long)).await;+ assert!(card.is_some(), "a no with a reason isn't remembered: the same family asks again");+ assert_eq!(reply, denied(said_why(&"é".repeat(500))));++ // Nothing left of the reason, or the old body: a plain Deny, remembered as before (27b)+ let (reply, card) = claude_asks(&e, "Bash", push("origin dev"), why(" \n\t ")).await;+ assert!(card.is_some());+ assert_eq!(reply, denied(mcp::DENIED_TEXT.to_string()));+ let (reply, card) = claude_asks(&e, "Bash", json!({"command": "gh pr merge 7"}), Answer::Route("deny", None)).await;+ assert!(card.is_some());+ assert_eq!(reply, denied(mcp::DENIED_TEXT.to_string()));+ for command in ["git push origin main", "gh pr merge 8"] {+ let (reply, card) = claude_asks(&e, "Bash", json!({"command": command}), ALLOW).await;+ assert_eq!(card, None, "{command}");+ assert_eq!(reply, denied(mcp::DECLINED_BEFORE_TEXT.to_string()), "{command}");+ }++ // A reason on an Allow is ignored: the call runs+ let (reply, card) = claude_asks(&e, "Bash", json!({"command": "npm publish"}), Answer::Route("allow_once", Some("fine"))).await;+ assert!(card.is_some());+ assert_eq!(reply["behavior"], "allow");+ assert_eq!(e.state.broker.deny_reasons_held(), 0, "nothing left behind");+ }++ /// 29o (c) on the approver itself: after a no with a reason, a call of the same family gets+ /// its own card, so nothing runs without the person's yes.+ #[tokio::test]+ async fn a_no_with_a_reason_lets_the_adjusted_call_ask() {+ let e = setup().await;+ let a = approver(&e, &e.general, Duration::from_secs(10));+ let (out, card, heard) = asked(&e, &a, bash(&e.bot, "git push --force origin main"), why("push without --force"), true).await;+ assert_eq!((out, card.is_some()), (ApprovalOutcome::Denied, true));+ assert_eq!(heard.as_deref(), Some("push without --force"), "the waiting call hears the reason");+ let (out, card) = ask(&e, &a, bash(&e.bot, "git push origin main"), ALLOW).await;+ assert_eq!((out, card.is_some()), (ApprovalOutcome::Allowed, true), "the adjusted call asks, and the person allows it");+ let (out, card) = ask(&e, &a, bash(&e.bot, "git push origin main"), DENY).await;+ assert_eq!((out, card.is_some()), (ApprovalOutcome::Denied, true));+ let (out, card) = ask(&e, &a, bash(&e.bot, "git push origin dev"), ALLOW).await;+ assert_eq!((out, card), (ApprovalOutcome::DeclinedBefore, None), "a plain no still stays a no");+ assert_eq!(e.state.broker.deny_reasons_held(), 0);+ }++ /// 29o round 2: a reason no call listens for reaches nobody (the bot hears the plain+ /// `DENIED_TEXT`), so the no is remembered as a plain one: the same family isn't asked again.+ #[tokio::test]+ async fn a_reason_nobody_hears_stays_a_plain_no() {+ let e = setup().await;+ let a = approver(&e, &e.general, Duration::from_secs(10));+ let (out, card) = ask_unheard(&e, &a, bash(&e.bot, "git push --force origin main"), why("push without --force")).await;+ assert_eq!((out, card.is_some()), (ApprovalOutcome::Denied, true));+ let (out, card) = ask(&e, &a, bash(&e.bot, "git push origin main"), ALLOW).await;+ assert_eq!((out, card), (ApprovalOutcome::DeclinedBefore, None), "an unheard reason is a plain no");+ assert_eq!(e.state.broker.deny_reasons_held(), 0, "nothing left behind");+ }++ /// 29o (d): a late Deny with a reason (its turn stopped waiting) answers as a plain late Deny+ /// does, and keeps nothing for a call that will never come.+ #[tokio::test]+ async fn a_late_deny_with_a_reason_answers_as_today() {+ let e = setup().await;+ let a = approver(&e, &e.general, Duration::from_millis(200));+ let mut bodies = vec![];+ for (n, reason) in [(1, None), (2, Some("use staging"))] {+ let (out, card) = ask(&e, &a, bash(&e.bot, &format!("gh pr merge {n}")), Answer::Nothing).await;+ assert_eq!(out, ApprovalOutcome::Unanswered);+ let card = card.unwrap();+ let mut body = answer_route(&e.state, &card, "deny", reason).await;+ assert_eq!(body["ticket_id"], json!(card));+ body.as_object_mut().unwrap().remove("ticket_id");+ bodies.push(body);+ }+ assert_eq!(bodies[0], bodies[1]);+ assert_eq!(bodies[1], json!({"resolved": true, "status": "denied", "resumed": false}));+ assert_eq!(e.state.broker.deny_reasons_held(), 0, "nothing kept for a call that won't come");+ }++ /// 29o (b) on kwnt's own tool calls (an API engine, codex, grok and claude through the+ /// gateway): the bot's tool result says why the person said no; a plain Deny still says+ /// `DENIED_TEXT` (`an_api_bot_s_tool_result_says_it_was_already_declined`).+ #[tokio::test]+ async fn an_api_bot_s_tool_result_says_why_the_person_said_no() {+ let e = setup().await;+ let (_, token) = prepare_turn_with_opts(&e.state, &e.bot, Some("t-host-why".into()), None, None, Default::default()).await.unwrap();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let app = super::super::create_router(e.state.clone());+ let serve = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ let server = http_server("perm", &format!("http://{addr}/api/mcp/permission/{token}"));+ let ctx = McpTurnContext {+ servers: vec![server],+ approver: Arc::new(approver(&e, &e.general, Duration::from_secs(10))),+ config_dir: std::env::temp_dir(),+ permission_url: None,+ gateway: None,+ max_tool_iterations: 5,+ approvals: mcp::Approvals::Ask,+ records: Default::default(),+ kwnt_only: false,+ media: None,+ };+ let (session, problems) = McpToolSession::open(&ctx, None).await;+ assert!(problems.is_empty(), "{problems:?}");+ let caller = Caller { kwant_id: e.bot.id.clone(), kwant_name: e.bot.name.clone(), turn_id: "t-api-why".into() };++ let mut events = e.state.event_sender.subscribe();+ let mut cards = 0;+ for (n, reason) in [(1, "use the read-only tool\ninstead"), (2, "ask Ada first")] {+ let call_id = format!("c{n}");+ let call = session.call(&caller, &call_id, "mcp__perm__approve", r#"{"tool_name": "Bash", "input": {}}"#);+ tokio::pin!(call);+ let out = loop {+ tokio::select! {+ out = &mut call => break out,+ ev = events.recv() => {+ if let Ok(RuntimeEvent::ApprovalRequired { id, .. }) = ev {+ cards += 1;+ answer_route(&e.state, &id, "deny", Some(reason)).await;+ }+ }+ }+ };+ let heard = said_why(&reason.replace('\n', " "));+ assert_eq!((out.status, out.text.as_str()), ("denied", heard.as_str()));+ assert_eq!(out.record["status"], "denied");+ }+ assert_eq!(cards, 2, "the second call asked: a no with a reason isn't remembered");+ assert_eq!(e.state.broker.deny_reasons_held(), 0);+ session.shutdown().await;+ finish_turn(&e.state, &token).await;+ serve.abort();+ }+#[tokio::test]async fn an_api_bot_s_tool_result_says_it_was_already_declined() {let e = setup().await;@@ -2146,52 +2413,3 @@ mod declined_tests {serve.abort();}}--#[cfg(test)]-mod card_settles_tests {- use super::*;-- /// 28k: only the person's Deny settles a card `declined`. A card that was withdrawn, or whose- /// channel dropped, settles `stopped`: nobody pressed Deny. The bot's outcome is `Denied`- /// either way (nothing runs), and it hears the same text.- #[tokio::test]- async fn a_withdrawn_card_settles_stopped_and_only_a_deny_settles_declined() {- let broker = PermissionBroker::new();- let ask = |id: &str| ApprovalRequest {- id: id.into(),- kwant_id: "k1".into(),- tool_name: "Bash".into(),- details: Value::Null,- };- let wait = |rx: tokio::sync::oneshot::Receiver<ApprovalDecision>| tokio::time::timeout(Duration::from_secs(5), rx);-- // Withdrawn: the broker drops the ticket with no decision- let rx = broker.request_approval(ask("apr_withdrawn")).await;- assert!(broker.cancel("apr_withdrawn").await);- let withdrawn = wait(rx).await;- assert!(matches!(withdrawn, Ok(Err(_))), "the waiter sees the channel close");- assert_eq!(card_settles(&withdrawn), Some("stopped"));-- // The person pressed Deny- let rx = broker.request_approval(ask("apr_deny")).await;- assert!(broker.resolve("apr_deny", ApprovalDecision::Deny).await);- assert_eq!(card_settles(&wait(rx).await), Some("declined"));-- // Allow, once or for the session- for d in [ApprovalDecision::AllowOnce, ApprovalDecision::AlwaysAllowSession] {- let rx = broker.request_approval(ask("apr_ok")).await;- assert!(broker.resolve("apr_ok", d).await);- assert_eq!(card_settles(&wait(rx).await), Some("ok"));- }-- // The wait ran out: the timeout path settles it, not this- let rx = broker.request_approval(ask("apr_slow")).await;- let ran_out = tokio::time::timeout(Duration::from_millis(1), rx).await;- assert!(ran_out.is_err());- assert_eq!(card_settles(&ran_out), None);-- // What the bot hears doesn't change: a withdrawn card and a Deny are both `Denied`- assert_eq!(ApprovalOutcome::Denied.refusal_text(), mcp::DENIED_TEXT);- assert_eq!(ApprovalOutcome::Denied.record_status(), "denied");- }-}diff --git a/src/server/routes.rs b/src/server/routes.rsindex 27c8335d..e03424a9 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -5201,6 +5201,21 @@ pub struct ResolveApprovalPayload {/// kwant's guess (22f). Refused on any other card that needs a backup.#[serde(default)]pub without_backup: bool,+ /// 29o: why the person pressed Deny ("use the staging database"), for the waiting bot. Only+ /// read on a Deny, made one line of at most 500 chars ([`crate::mcp::deny_reason`]); empty is+ /// a plain Deny.+ #[serde(default)]+ pub reason: Option<String>,+}++impl ResolveApprovalPayload {+ /// 29o: the Deny's reason as the bot will hear it; `None` for an Allow or a plain Deny.+ pub fn deny_reason(&self, decision: &ApprovalDecision) -> Option<String> {+ match decision {+ ApprovalDecision::Deny => self.reason.as_deref().and_then(crate::mcp::deny_reason),+ _ => None,+ }+ }}pub async fn resolve_approval(@@ -5213,7 +5228,8 @@ pub async fn resolve_approval("always_allow" => ApprovalDecision::AlwaysAllowSession,_ => ApprovalDecision::Deny,};- let (status, body) = resolve_approval_inner(&state, &ticket_id, decision, None, payload.without_backup).await;+ let reason = payload.deny_reason(&decision);+ let (status, body) = resolve_approval_inner(&state, &ticket_id, decision, None, payload.without_backup, reason).await;Ok((status, Json(body)).into_response())}@@ -5240,12 +5256,16 @@ pub async fn retry_expired_approval(State(state): State<AppState>, Path(ticket_i////// `without_backup` is the person's "Allow without a backup" (22f): only the app's route, which is/// person-only, ever passes `true`; see [`super::dev::floor::allow_check`] for which cards take it.+///+/// `reason` is the person's reason on a Deny (29o, the app's route only): the waiting call+/// hears it; a late answer drops it.pub(crate) async fn resolve_approval_inner(state: &AppState,ticket_id: &str,decision: ApprovalDecision,via: Option<&str>,without_backup: bool,+ reason: Option<String>,) -> (StatusCode, serde_json::Value) {let status_str = match decision {ApprovalDecision::AllowOnce => "allowed_once",@@ -5281,7 +5301,7 @@ pub(crate) async fn resolve_approval_inner(// Only a ticket still waiting can be answered; a withdrawn one (turn ended, expired)// keeps its status and its tool never runs- let resolved = state.broker.resolve(ticket_id, decision.clone()).await;+ let resolved = state.broker.resolve_with_reason(ticket_id, decision.clone(), reason).await;if !resolved {// A card whose turn stopped waiting (or that kwant kept over a restart): a late answer,// and Allow resumes the work@@ -7480,6 +7500,24 @@ pub async fn execute_tool(#[cfg(test)]mod tests {+ /// 29o: the card's resolve body may carry a Deny's reason; the old body still parses, and a+ /// reason only counts on a Deny.+ #[test]+ fn a_resolve_body_may_carry_a_deny_reason() {+ use super::ResolveApprovalPayload;+ use crate::broker::ApprovalDecision;+ use serde_json::json;+ let body = |v: serde_json::Value| serde_json::from_value::<ResolveApprovalPayload>(v).unwrap();+ assert_eq!(body(json!({"decision": "deny"})).deny_reason(&ApprovalDecision::Deny), None);+ let with = body(json!({"decision": "deny", "reason": " use the\nstaging database "}));+ assert_eq!(with.deny_reason(&ApprovalDecision::Deny).as_deref(), Some("use the staging database"));+ for allow in [ApprovalDecision::AllowOnce, ApprovalDecision::AlwaysAllowSession] {+ assert_eq!(with.deny_reason(&allow), None);+ }+ assert_eq!(body(json!({"decision": "deny", "reason": " "})).deny_reason(&ApprovalDecision::Deny), None);+ assert_eq!(body(json!({"decision": "deny", "reason": null})).deny_reason(&ApprovalDecision::Deny), None);+ }+#[test]fn a_mention_in_inline_code_leaves_no_stray_backtick_in_the_title() {use super::handoff_title;diff --git a/src/server/telegram/bridge.rs b/src/server/telegram/bridge.rsindex 4a423062..381ce1a1 100644--- a/src/server/telegram/bridge.rs+++ b/src/server/telegram/bridge.rs@@ -376,7 +376,7 @@ async fn allow_once(state: &AppState, runner: &Runner, link: &TelegramLink, ask:let _ = runner.client.answer_callback(cb_id, Some(copy::ALREADY_ANSWERED)).await;return;}- let (status, body) = crate::server::routes::resolve_approval_inner(state, &ask.ref_id, ApprovalDecision::AllowOnce, Some("telegram"), false).await;+ let (status, body) = crate::server::routes::resolve_approval_inner(state, &ask.ref_id, ApprovalDecision::AllowOnce, Some("telegram"), false, None).await;if status.is_success() {let _ = runner.client.answer_callback(cb_id, None).await;edit_answered(state, runner, ask, &format!("{TEAL_CHECK} Allowed once from Telegram · {}", hhmm(state).await)).await;