Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

27b: a no stays a no for the rest of the chat (#781)

Oleksandr Ivanchenkoc1d5b785d4b7
diff --git a/docs/approvals.md b/docs/approvals.md
index 388a05d9..80bf3126 100644
--- a/docs/approvals.md
+++ b/docs/approvals.md
@@ -148,7 +148,20 @@ person takes it back (`DELETE /api/kwants/:id/always-allowed`, see [mcp-api.md](
command only. Neither covers a payment or a Home Assistant lock, door or alarm, and "Always this
session" on such a card allows that one call.
+## A no stays a no
+
+When the person presses Deny, the bot is told not to try it again or another way, and for the
+rest of that conversation (a thread, else the channel or direct chat) kwnt refuses a call of the
+same family from that bot at once, with no card. A family is a shell program and its first
+subcommand (`gh pr`, `git push`), or a URL program and its host (`curl` to `api.github.com`); a
+file and whether it's read or written; a page's host; an MCP server's tool. Other built-in tools
+keep asking. The bot hears `DECLINED_BEFORE_TEXT` and the step shows as declined. It lasts until
+the person writes in that conversation again, and only in memory: a restart, another conversation
+or another bot asks as before. An unanswered card, a card its turn dropped, and kwnt's own refusals
+don't count, and a late Allow on an earlier card still runs that call (`src/mcp/declined.rs`).
+
## Tests
`cargo test --test smart_approvals_test --test approvals_off_test --test approvals_passwords_test --test payment_floor_test --test home_locks_always_ask_test`
-and the classifier tables in `src/mcp/shell_risk.rs` (`cargo test --lib shell_risk`).
+and the classifier tables in `src/mcp/shell_risk.rs` (`cargo test --lib shell_risk`); a no that
+stays a no: `cargo test --lib declined`.
diff --git a/site-src/docs-approvals.html b/site-src/docs-approvals.html
index 6529447c..64272c7c 100644
--- a/site-src/docs-approvals.html
+++ b/site-src/docs-approvals.html
@@ -15,8 +15,9 @@ card_art: avatar:qa
<ul>
<li><strong>Allow once</strong> runs this one call.</li>
<li><strong>Always allow</strong> allows that tool for that bot until kwant restarts.</li>
- <li><strong>Deny</strong> refuses it, and the bot is told.</li>
+ <li><strong>Deny</strong> refuses it, and the bot is told not to try it again or another way.</li>
</ul>
+<p>After you deny a call, the bot can't ask again for the same kind of thing in that chat: a command with the same program and first word (any <code>git push</code>), the same website, or the same file. kwant refuses it without a card until you write in that chat again.</p>
<figure>
<div class="frame">{{shot:desktop-approval|Ann's chat. Right under the request Tests are passing. Please open the pull request for the waitlist branch, an Approval needed card says Ann wants to open a pull request on GitHub, with the title Trip waitlist with timed seat holds and the repo trailhead/storefront, and Deny, Always allow and Allow once buttons.|(max-width: 860px) 100vw, 760px}}</div>
<figcaption>Ann asks before opening a pull request.</figcaption>
diff --git a/src/broker/mod.rs b/src/broker/mod.rs
index cfad5840..97a97b81 100644
--- a/src/broker/mod.rs
+++ b/src/broker/mod.rs
@@ -34,6 +34,9 @@ pub struct PermissionBroker {
/// Calls the person allowed after their turn had stopped waiting: the resumed turn's same
/// call runs once without a new card, until the grant lapses.
grants: Arc<Mutex<Vec<Grant>>>,
+ /// 27b: what the person declined, per bot and conversation, until they write there again.
+ /// In memory only.
+ pub declined: crate::mcp::declined::Declines,
}
/// How long a late Allow waits for the resumed turn to make its call again.
@@ -66,6 +69,7 @@ impl PermissionBroker {
pending: Arc::new(Mutex::new(HashMap::new())),
always_allowed: Arc::new(Mutex::new(HashSet::new())),
grants: Default::default(),
+ declined: Default::default(),
store: Default::default(),
loaded: Default::default(),
}
@@ -237,6 +241,7 @@ impl PermissionBroker {
self.load_saved().await;
self.always_allowed.lock().await.retain(|(k, _, _)| k != kwant_id);
self.grants.lock().await.retain(|g| g.kwant_id != kwant_id);
+ self.declined.forget_kwant(kwant_id);
if let Some(db) = self.store.get() {
if let Err(e) = db.delete_all_always_allowed(kwant_id).await {
tracing::warn!(kwant = %kwant_id, error = %e, "could not forget a deleted bot's \"always allow\" answers");
@@ -249,6 +254,7 @@ impl PermissionBroker {
self.load_saved().await;
self.always_allowed.lock().await.retain(|(_, c, _)| c != conversation);
self.grants.lock().await.retain(|g| g.conversation != conversation);
+ self.declined.forget_conversation(conversation);
if let Some(db) = self.store.get() {
if let Err(e) = db.delete_always_allowed_in(conversation).await {
tracing::warn!(conversation, error = %e, "could not forget a deleted conversation's \"always allow\" answers");
diff --git a/src/drivers/activity.rs b/src/drivers/activity.rs
index f0cedf59..96447908 100644
--- a/src/drivers/activity.rs
+++ b/src/drivers/activity.rs
@@ -593,12 +593,20 @@ pub fn step_end(result: &Value) -> (&'static str, Option<String>) {
Some(crate::mcp::REHEARSED_STEP_DETAIL.to_string()),
);
}
+ // 27b: refused with no card, because the person already said no to one like it
+ if refused && said(first_sentence(crate::mcp::DECLINED_BEFORE_TEXT)) {
+ return (
+ "declined",
+ Some(crate::mcp::DECLINED_BEFORE_STEP_DETAIL.to_string()),
+ );
+ }
match failed_reason(result) {
None => ("ok", None),
Some(why) => (
"failed",
why.map(|w| {
w.replace(crate::mcp::NO_FALSE_CLAIMS_TEXT, "")
+ .replace(crate::mcp::NOT_ANOTHER_WAY_TEXT, "")
.trim()
.to_string()
})
@@ -1181,9 +1189,10 @@ mod tests {
let (status, why) = step_end(
&json!({"status": "error", "error": crate::mcp::with_no_false_claims(crate::mcp::DENIED_TEXT)}),
);
+ // 27b: the "don't try another way" sentence is for the bot too
assert_eq!(
(status, why.as_deref()),
- ("failed", Some(crate::mcp::DENIED_TEXT))
+ ("failed", Some("The user denied this tool call."))
);
assert_eq!(
step_end(&json!({"status": "ok", "content": "fine"})),
@@ -1195,6 +1204,20 @@ mod tests {
);
}
+ /// 27b: a call refused because the person already said no ends `declined`, with the step
+ /// detail for the person, however the engine reports it.
+ #[test]
+ fn a_call_refused_for_an_earlier_no_shows_as_declined() {
+ let want = ("declined", Some(crate::mcp::DECLINED_BEFORE_STEP_DETAIL.to_string()));
+ // claude CLI: the permission route's deny message comes back as the error
+ assert_eq!(step_end(&json!({"status": "error", "error": crate::mcp::DECLINED_BEFORE_TEXT})), want);
+ // API engine: kwnt's own record, status `denied`
+ assert_eq!(step_end(&json!({"status": "denied", "content": crate::mcp::DECLINED_BEFORE_TEXT})), want);
+ assert_eq!(step_end(&json!({"status": "error", "content": crate::mcp::with_no_false_claims(crate::mcp::DECLINED_BEFORE_TEXT)})), want);
+ // An ok result quoting it is still ok
+ assert_eq!(step_end(&json!({"status": "ok", "content": crate::mcp::DECLINED_BEFORE_TEXT})).0, "ok");
+ }
+
#[test]
fn steps_and_thinking_are_capped() {
let mut log = ActivityLog::default();
diff --git a/src/mcp/declined.rs b/src/mcp/declined.rs
new file mode 100644
index 00000000..b74dedcc
--- /dev/null
+++ b/src/mcp/declined.rs
@@ -0,0 +1,542 @@
+//! 27b: a no stays a no. Once the person declines a card, a later call of the same kind in that
+//! chat is refused at once, with no card, until the person writes there again. Without it a bot
+//! that heard "no" to `gh pr view 12` tried `gh pr view --json title`, then `/usr/bin/gh pr view`,
+//! each one a new card (Compass trial, problems B and C).
+//!
+//! What a no covers is the call's *family* ([`families`]):
+//!
+//! | Call | Family |
+//! |---|---|
+//! | Shell | program + first subcommand word (`gh pr`, `git push`); wrappers, env assignments, paths and `cd` left out |
+//! | Shell, a URL program (curl, wget, http, xh) | program + host (`curl` + `localhost`, any port or path) |
+//! | File tools | write or read + the file's path |
+//! | WebFetch, the bot browser's open or navigate | host |
+//! | Any other MCP tool | server + tool |
+//!
+//! A shell line with several commands has a family for each; it is refused when any one was
+//! declined. Remembered in memory only, per bot and conversation, and capped
+//! ([`MAX_PER_CONVERSATION`]): a restart ends the turn anyway.
+
+use super::ToolApprovalRequest;
+use serde_json::Value;
+use std::collections::{HashMap, VecDeque};
+use std::sync::{Arc, Mutex};
+use std::time::Instant;
+
+/// Declined families kept per bot and conversation; the oldest goes first.
+pub const MAX_PER_CONVERSATION: usize = 32;
+/// Conversations with something declined kept at once; the one declined in longest ago goes first.
+pub const MAX_CONVERSATIONS: usize = 1024;
+
+/// Programs whose family is the host they reach, not a subcommand.
+const URL_PROGRAMS: &[&str] = &["curl", "wget", "http", "https", "xh", "xhs"];
+/// Programs that run the rest of the line: skipped, with their options.
+const WRAPPERS: &[&str] = &["sudo", "env", "command", "nohup", "time", "exec", "nice", "timeout", "doas", "stdbuf"];
+/// The wrappers' options that take the next word.
+const WRAPPER_VALUED: &[&str] = &["-u", "-g", "-n", "-s", "-k", "-C", "-D", "-p", "-U", "--user", "--group", "--signal", "--kill-after", "--unset", "--chdir"];
+/// Steps around the real command (moving, printing, filtering a pipe): no family of their own,
+/// so `cd repo && gh pr view | jq .title` is just `gh pr`.
+const PLUMBING: &[&str] = &[
+ "cd", "pushd", "popd", "echo", "printf", "true", "false", "sleep", "set", "export", "test", "[", ":", "head", "tail",
+ "jq", "grep", "egrep", "fgrep", "sort", "uniq", "wc", "cat", "less", "more", "cut", "tr",
+];
+const SHELLS: &[&str] = &["bash", "sh", "zsh", "dash", "ksh"];
+/// Global options that take the next word, by program, so `git -C repo push` is still `git push`.
+/// (A `match`, not a table: tests/host_git_calls_test.rs accepts a git name as a match pattern.)
+fn global_valued(program: &str) -> &'static [&'static str] {
+ match program {
+ "git" => &["-C", "-c", "--git-dir", "--work-tree", "--namespace"],
+ "gh" => &["-R", "--repo", "--hostname"],
+ "docker" => &["-H", "--host", "--context", "-c", "--config", "-l", "--log-level"],
+ "kubectl" => &["-n", "--namespace", "--context", "--cluster", "--kubeconfig", "-s", "--server", "--user"],
+ "npm" => &["--prefix", "-w", "--workspace"],
+ "cargo" => &["--manifest-path", "-Z", "--config"],
+ _ => &[],
+ }
+}
+/// curl's, wget's and httpie's options that take the next word (it is never the address).
+const URL_VALUED: &[&str] = &[
+ "-o", "--output", "-H", "--header", "-d", "--data", "--data-raw", "--data-binary", "--data-urlencode", "-X", "--request",
+ "-u", "--user", "-A", "--user-agent", "-e", "--referer", "-b", "--cookie", "-c", "--cookie-jar", "-w", "--write-out",
+ "-T", "--upload-file", "-F", "--form", "-m", "--max-time", "--connect-timeout", "-x", "--proxy", "-K", "--config",
+ "-r", "--range", "--retry", "--cacert", "--cert", "--key", "-E", "--resolve", "-O", "--output-document",
+ "--output-file", "-P", "--directory-prefix", "-U", "--post-data", "--post-file", "-t", "--tries", "--timeout",
+ "--auth", "-a",
+];
+
+/// What a "no" to `req` covers: one family per part of the call, empty when it covers nothing
+/// kwant can name (a shell line it can't read, a fetch with no address, one of claude's other
+/// tools), so the next such call asks again.
+pub fn families(req: &ToolApprovalRequest) -> Vec<String> {
+ let name = if req.builtin.is_some() || req.server.is_empty() { req.tool_name.as_str() } else { req.tool.as_str() };
+ let lower = name.rsplit("__").next().unwrap_or(name).to_ascii_lowercase();
+ let mut out = Vec::new();
+ if crate::drivers::activity::is_shell_tool(&req.tool_name) || crate::drivers::activity::is_shell_tool(&req.tool) {
+ if let Some(line) = shell_line(&req.arguments) {
+ shell_families(&line, 0, &mut out);
+ }
+ } else if let Some(kind) = file_kind(&lower) {
+ let cwd = req.builtin.as_ref().and_then(|b| b.cwd.as_deref());
+ if let Some(path) = arg(&req.arguments, &["file_path", "path", "notebook_path", "filePath", "target_file"]) {
+ out.push(format!("file:{kind}:{}", normal_path(path, cwd)));
+ }
+ } else if matches!(lower.as_str(), "webfetch" | "fetch" | "web_fetch") || crate::drivers::activity::opens_page(&lower) {
+ if let Some(host) = arg(&req.arguments, &["url", "href", "uri"]).and_then(host_of) {
+ out.push(format!("web:{host}"));
+ }
+ } else if req.builtin.is_none() && !req.server.is_empty() {
+ out.push(format!("mcp:{}/{}", req.server, req.tool));
+ }
+ out.dedup();
+ out
+}
+
+fn arg<'a>(args: &'a Value, keys: &[&str]) -> Option<&'a str> {
+ keys.iter().find_map(|k| args[*k].as_str()).map(str::trim).filter(|s| !s.is_empty())
+}
+
+/// `write` (Write, Edit, MultiEdit, NotebookEdit, kwnt's `write_file`…) or `read`.
+fn file_kind(tool: &str) -> Option<&'static str> {
+ match tool {
+ "write" | "write_file" | "create_file" | "edit" | "multiedit" | "edit_file" | "str_replace" | "str_replace_based_edit_tool"
+ | "notebookedit" => Some("write"),
+ "read" | "read_file" | "notebookread" => Some("read"),
+ _ => None,
+ }
+}
+
+/// The command a shell tool runs: `command` or `cmd`, as a string, or as words (`["bash", "-lc",
+/// "gh pr view"]` is its last word).
+fn shell_line(args: &Value) -> Option<String> {
+ let v = ["command", "cmd"].iter().map(|k| &args[*k]).find(|v| !v.is_null())?;
+ if let Some(s) = v.as_str() {
+ return Some(s.to_string());
+ }
+ let words: Vec<&str> = v.as_array()?.iter().filter_map(Value::as_str).collect();
+ match words.as_slice() {
+ [sh, flag, line] if SHELLS.contains(&base(sh)) && flag.starts_with('-') && flag.contains('c') => Some(line.to_string()),
+ // Plain words: quote each one so the lexer reads them back as they are
+ _ => Some(words.iter().map(|w| format!("'{}'", w.replace('\'', "'\\''"))).collect::<Vec<_>>().join(" ")),
+ }
+}
+
+fn base(program: &str) -> &str {
+ program.rsplit('/').next().unwrap_or(program)
+}
+
+/// Adds the families of every simple command in `line`. A line the shell lexer can't read
+/// (`$VAR`, a subshell) is read up to its first such character, by whitespace.
+fn shell_families(line: &str, depth: u8, out: &mut Vec<String>) {
+ let commands = super::shell_risk::simple_commands(line).unwrap_or_else(|| {
+ let head = line.split(['$', '`', '(', ')', '|', ';', '&', '<', '>', '\n', '"', '\'']).next().unwrap_or("");
+ vec![head.split_whitespace().map(str::to_string).collect()]
+ });
+ for words in commands {
+ if let Some(f) = command_family(&words, depth, out) {
+ out.push(f);
+ }
+ }
+}
+
+/// The family of one simple command, or `None` (plumbing, nothing to name). A shell's `-c` line
+/// adds its own families to `out` instead.
+fn command_family(words: &[String], depth: u8, out: &mut Vec<String>) -> Option<String> {
+ let mut i = 0;
+ // Env assignments, then wrappers (with their options and env's assignments)
+ loop {
+ let w = words.get(i)?;
+ if super::shell_risk::assignment(w).is_some() {
+ i += 1;
+ continue;
+ }
+ let program = base(w);
+ if !WRAPPERS.contains(&program) {
+ break;
+ }
+ i += 1;
+ let mut positional = usize::from(program == "timeout");
+ while let Some(a) = words.get(i) {
+ if a.starts_with('-') {
+ i += if WRAPPER_VALUED.contains(&a.as_str()) { 2 } else { 1 };
+ } else if super::shell_risk::assignment(a).is_some() {
+ i += 1;
+ } else if positional > 0 {
+ positional -= 1;
+ i += 1;
+ } else {
+ break;
+ }
+ }
+ }
+ let program = base(words.get(i)?);
+ let args = &words[i + 1..];
+ if program.is_empty() || PLUMBING.contains(&program) {
+ return None;
+ }
+ if SHELLS.contains(&program) && depth < 2 {
+ let at = args.iter().position(|a| a.starts_with('-') && !a.starts_with("--") && a.contains('c'))?;
+ shell_families(args.get(at + 1)?, depth + 1, out);
+ return None;
+ }
+ if URL_PROGRAMS.contains(&program) {
+ return url_host(args).map(|host| format!("sh:{program}@{host}"));
+ }
+ let valued = global_valued(program);
+ let mut j = 0;
+ let first = loop {
+ let Some(a) = args.get(j) else { break None };
+ if a == "--" {
+ break args.get(j + 1);
+ }
+ if a.starts_with('-') {
+ j += if valued.contains(&a.as_str()) { 2 } else { 1 };
+ continue;
+ }
+ break Some(a);
+ };
+ match first.filter(|a| bare_word(a)) {
+ Some(sub) => Some(format!("sh:{program} {sub}")),
+ None => Some(format!("sh:{program}")),
+ }
+}
+
+/// A subcommand-looking word: letters, digits, `-` and `_`, with no `/`, `.`, `:` or `=`.
+fn bare_word(word: &str) -> bool {
+ !word.is_empty()
+ && !word.starts_with('-')
+ && word.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
+ && word.chars().any(|c| c.is_ascii_alphabetic())
+}
+
+/// The host a curl, wget or httpie line reaches: its first address with a scheme, else its first
+/// word that looks like `host[:port][/path]` (or httpie's `:port`), skipping option values.
+fn url_host(args: &[String]) -> Option<String> {
+ let mut positional = Vec::new();
+ let mut j = 0;
+ while let Some(a) = args.get(j) {
+ if a == "--url" {
+ if let Some(u) = args.get(j + 1) {
+ positional.push(u.as_str());
+ }
+ j += 2;
+ } else if a.starts_with('-') {
+ j += if URL_VALUED.contains(&a.as_str()) { 2 } else { 1 };
+ } else {
+ positional.push(a.as_str());
+ j += 1;
+ }
+ }
+ if let Some(host) = positional.iter().filter(|a| a.contains("://")).find_map(|a| host_of(a)) {
+ return Some(host);
+ }
+ positional
+ .iter()
+ // httpie's method word and its `key=value` / `Header:value` items are not addresses
+ .filter(|a| !a.chars().all(|c| c.is_ascii_uppercase()) && !a.contains('='))
+ .find_map(|a| {
+ let a: &str = a;
+ if a.starts_with(':') && a[1..].chars().next().is_some_and(|c| c.is_ascii_digit()) {
+ return Some("localhost".to_string());
+ }
+ let host = host_of(a)?;
+ (host == "localhost" || host.contains('.') || a.contains(':')).then_some(host)
+ })
+}
+
+/// The host of an address, lowercased, without scheme, user, port or path. Every loopback
+/// address (`127.0.0.1`, `::1`, `0.0.0.0`) is `localhost`, so a port probe is one family.
+pub fn host_of(url: &str) -> Option<String> {
+ let rest = url.trim().split_once("://").map_or(url.trim(), |(_, r)| r);
+ let authority = rest.split(['/', '?', '#']).next()?;
+ let authority = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
+ let host = if let Some(v6) = authority.strip_prefix('[') {
+ v6.split(']').next()?
+ } else {
+ match authority.rsplit_once(':') {
+ Some((h, port)) if port.chars().all(|c| c.is_ascii_digit()) => h,
+ _ => authority,
+ }
+ };
+ let host = host.trim_end_matches('.').to_ascii_lowercase();
+ if host.is_empty() || !host.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | ':')) {
+ return None;
+ }
+ let loopback = host == "localhost" || host.ends_with(".localhost") || host.starts_with("127.") || host == "::1" || host == "0.0.0.0";
+ Some(if loopback { "localhost".into() } else { host })
+}
+
+/// `path` joined to `cwd` when relative, with `.` and `..` resolved by name (nothing is read
+/// from disk) and no trailing `/`.
+fn normal_path(path: &str, cwd: Option<&str>) -> String {
+ let joined = match cwd {
+ Some(c) if !path.starts_with('/') && !path.starts_with('~') => format!("{}/{path}", c.trim_end_matches('/')),
+ _ => path.to_string(),
+ };
+ let mut parts: Vec<&str> = Vec::new();
+ for part in joined.split('/') {
+ match part {
+ "" | "." => {}
+ ".." => {
+ parts.pop();
+ }
+ p => parts.push(p),
+ }
+ }
+ let lead = if joined.starts_with('/') { "/" } else { "" };
+ format!("{lead}{}", parts.join("/"))
+}
+
+#[derive(Debug, Clone)]
+struct Entry {
+ family: String,
+ ticket: String,
+}
+
+#[derive(Debug, Default)]
+struct Inner {
+ by_chat: HashMap<(String, String), VecDeque<Entry>>,
+ /// When each conversation last had something declined, for [`MAX_CONVERSATIONS`].
+ last: HashMap<(String, String), Instant>,
+}
+
+/// What the person declined, per bot and conversation, until they write there again.
+#[derive(Debug, Clone, Default)]
+pub struct Declines(Arc<Mutex<Inner>>);
+
+impl Declines {
+ fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
+ self.0.lock().unwrap_or_else(|p| p.into_inner())
+ }
+
+ /// The person said no to the call with `families` on card `ticket`.
+ pub fn record(&self, kwant_id: &str, conversation: &str, families: &[String], ticket: &str) {
+ if families.is_empty() {
+ return;
+ }
+ let key = (kwant_id.to_string(), conversation.to_string());
+ let mut inner = self.lock();
+ if !inner.by_chat.contains_key(&key) && inner.by_chat.len() >= MAX_CONVERSATIONS {
+ if let Some(oldest) = inner.last.iter().min_by_key(|(_, at)| **at).map(|(k, _)| k.clone()) {
+ inner.by_chat.remove(&oldest);
+ inner.last.remove(&oldest);
+ }
+ }
+ inner.last.insert(key.clone(), Instant::now());
+ let list = inner.by_chat.entry(key).or_default();
+ for family in families {
+ list.retain(|e| &e.family != family);
+ list.push_back(Entry { family: family.clone(), ticket: ticket.to_string() });
+ }
+ while list.len() > MAX_PER_CONVERSATION {
+ list.pop_front();
+ }
+ }
+
+ /// The card the person declined one of `families` on, in this bot's conversation.
+ pub fn check(&self, kwant_id: &str, conversation: &str, families: &[String]) -> Option<String> {
+ if families.is_empty() {
+ return None;
+ }
+ let inner = self.lock();
+ let list = inner.by_chat.get(&(kwant_id.to_string(), conversation.to_string()))?;
+ list.iter().rev().find(|e| families.contains(&e.family)).map(|e| e.ticket.clone())
+ }
+
+ /// The person wrote again in this conversation: what they declined there may be asked again.
+ pub fn clear(&self, kwant_id: &str, conversation: &str) {
+ let key = (kwant_id.to_string(), conversation.to_string());
+ let mut inner = self.lock();
+ inner.by_chat.remove(&key);
+ inner.last.remove(&key);
+ }
+
+ /// A deleted bot.
+ pub fn forget_kwant(&self, kwant_id: &str) {
+ let mut inner = self.lock();
+ inner.by_chat.retain(|(k, _), _| k != kwant_id);
+ inner.last.retain(|(k, _), _| k != kwant_id);
+ }
+
+ /// A deleted thread or channel.
+ pub fn forget_conversation(&self, conversation: &str) {
+ let mut inner = self.lock();
+ inner.by_chat.retain(|(_, c), _| c != conversation);
+ inner.last.retain(|(_, c), _| c != conversation);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::mcp::BuiltinCall;
+ use serde_json::json;
+
+ fn call(tool_name: &str, server: &str, tool: &str, arguments: Value, builtin: bool) -> ToolApprovalRequest {
+ ToolApprovalRequest {
+ kwant_id: "k1".into(),
+ kwant_name: "Forge".into(),
+ turn_id: "t1".into(),
+ tool_name: tool_name.into(),
+ server: server.into(),
+ tool: tool.into(),
+ arguments,
+ builtin: builtin.then(|| BuiltinCall { cwd: Some("/work/repo".into()), outside_folder: true }),
+ smart: None,
+ payment: None,
+ }
+ }
+
+ fn bash(command: &str) -> ToolApprovalRequest {
+ call("Bash", "", "Bash", json!({"command": command, "description": "x"}), true)
+ }
+
+ fn fam(command: &str) -> Vec<String> {
+ families(&bash(command))
+ }
+
+ fn same(a: &[String], b: &[String]) -> bool {
+ !a.is_empty() && a.iter().any(|f| b.contains(f))
+ }
+
+ /// The shell rows of the table: program + first subcommand word, whatever is around it.
+ #[test]
+ fn a_shell_command_is_its_program_and_subcommand() {
+ for (cmd, want) in [
+ ("gh pr view 12", "sh:gh pr"),
+ ("gh pr view --json title", "sh:gh pr"),
+ ("/usr/bin/gh pr view", "sh:gh pr"),
+ ("GH_PAGER=cat gh pr view 12", "sh:gh pr"),
+ ("sudo -u root gh pr view", "sh:gh pr"),
+ ("env GH_PAGER= gh pr view", "sh:gh pr"),
+ ("command gh pr view", "sh:gh pr"),
+ ("cd /work/repo && gh pr view 12", "sh:gh pr"),
+ ("gh -R acme/site pr view 12", "sh:gh pr"),
+ ("gh pr view 12 --json title | jq .title", "sh:gh pr"),
+ ("git push origin main", "sh:git push"),
+ ("git push -f", "sh:git push"),
+ ("git -C /work/repo push", "sh:git push"),
+ ("timeout 30 git push", "sh:git push"),
+ ("bash -lc 'gh pr view 12'", "sh:gh pr"),
+ ("gh pr view $(git branch --show-current)", "sh:gh pr"),
+ ("ls /tmp", "sh:ls"),
+ ("./deploy.sh --prod", "sh:deploy.sh"),
+ ] {
+ assert_eq!(fam(cmd), vec![want.to_string()], "{cmd}");
+ }
+ // Another subcommand is another family: it still asks
+ for (a, b) in [("gh pr view", "gh issue list"), ("git push", "git status"), ("npm publish", "npm test")] {
+ assert!(!same(&fam(a), &fam(b)), "{a} vs {b}");
+ }
+ // Codex's words form
+ let codex = call("exec_command", "", "exec_command", json!({"cmd": ["bash", "-lc", "gh pr view 3"]}), true);
+ assert_eq!(families(&codex), vec!["sh:gh pr".to_string()]);
+ let words = call("shell", "", "shell", json!({"command": ["gh", "pr", "view", "3"]}), true);
+ assert_eq!(families(&words), vec!["sh:gh pr".to_string()]);
+ }
+
+ /// Compass B: port probes on localhost are one family, whatever the port, path or spelling.
+ #[test]
+ fn a_url_program_is_its_program_and_host() {
+ for cmd in [
+ "curl localhost:9/health",
+ "curl -s http://localhost:9/",
+ "curl -sS -o /dev/null -w '%{http_code}' http://127.0.0.1:3000/api",
+ "curl http://localhost:8080",
+ "curl -H 'Accept: text/html' --max-time 3 localhost:5173",
+ "curl --url http://[::1]:4000/x",
+ ] {
+ assert_eq!(fam(cmd), vec!["sh:curl@localhost".to_string()], "{cmd}");
+ }
+ assert_eq!(fam("wget -O out.html https://Example.com/a"), vec!["sh:[email protected]".to_string()]);
+ assert_eq!(fam("http GET :8080/x"), vec!["sh:http@localhost".to_string()]);
+ assert_eq!(fam("xh POST api.example.com/v1 name=x"), vec!["sh:[email protected]".to_string()]);
+ assert!(!same(&fam("curl https://api.github.com/x"), &fam("curl https://example.com/x")), "another host still asks");
+ assert!(fam("curl -s").is_empty(), "no address: nothing to name");
+ }
+
+ /// Several commands in one line: each has its family; plumbing has none.
+ #[test]
+ fn a_line_has_every_command_s_family() {
+ assert_eq!(fam("git add . && git commit -m wip && git push"), vec!["sh:git add", "sh:git commit", "sh:git push"]);
+ assert_eq!(fam("echo hi; cd x | head -3"), Vec::<String>::new());
+ assert!(same(&fam("git status && git push origin main"), &fam("git push")));
+ }
+
+ #[test]
+ fn a_file_tool_is_its_kind_and_path() {
+ let write = |tool: &str, path: &str| families(&call(tool, "", tool, json!({"file_path": path, "content": "x"}), true));
+ assert_eq!(write("Write", "/etc/hosts"), vec!["file:write:/etc/hosts".to_string()]);
+ // The same file, written another way, or named another way
+ for (tool, path) in [("Edit", "/etc/hosts"), ("MultiEdit", "/etc/./hosts"), ("Write", "/etc/x/../hosts"), ("Edit", "../../etc/hosts")] {
+ assert_eq!(write(tool, path), vec!["file:write:/etc/hosts".to_string()], "{tool} {path}");
+ }
+ let nb = families(&call("NotebookEdit", "", "NotebookEdit", json!({"notebook_path": "a.ipynb"}), true));
+ assert_eq!(nb, vec!["file:write:/work/repo/a.ipynb".to_string()]);
+ let own = families(&call("mcp__kwnt__write_file", "kwnt", "write_file", json!({"path": "/etc/hosts"}), false));
+ assert_eq!(own, vec!["file:write:/etc/hosts".to_string()], "kwnt's own file writes");
+ assert!(!same(&write("Write", "/etc/hosts"), &write("Write", "/etc/passwd")), "another file still asks");
+ let read = families(&call("Read", "", "Read", json!({"file_path": "/etc/hosts"}), true));
+ assert!(!same(&read, &write("Write", "/etc/hosts")), "a read isn't a write");
+ }
+
+ #[test]
+ fn a_page_is_its_host() {
+ let fetch = |url: &str| families(&call("WebFetch", "", "WebFetch", json!({"url": url, "prompt": "x"}), true));
+ assert_eq!(fetch("https://news.example.com/a?b=1"), vec!["web:news.example.com".to_string()]);
+ assert_eq!(fetch("http://news.example.com:8443/other"), vec!["web:news.example.com".to_string()]);
+ let open = families(&call("mcp__kwnt__browser_open", "kwnt", "browser_open", json!({"url": "https://news.example.com/"}), false));
+ assert_eq!(open, vec!["web:news.example.com".to_string()]);
+ let nav = families(&call("mcp__playwright__navigate", "playwright", "navigate", json!({"url": "https://shop.example.org"}), false));
+ assert_eq!(nav, vec!["web:shop.example.org".to_string()]);
+ assert!(!same(&fetch("https://a.example.com"), &fetch("https://b.example.com")));
+ }
+
+ #[test]
+ fn another_mcp_tool_is_its_server_and_tool() {
+ let merge = |args: Value| families(&call("mcp__github__merge_pull_request", "github", "merge_pull_request", args, false));
+ assert_eq!(merge(json!({"pr": 1})), vec!["mcp:github/merge_pull_request".to_string()]);
+ assert_eq!(merge(json!({"pr": 2, "method": "squash"})), merge(json!({"pr": 1})));
+ let other = families(&call("mcp__github__create_issue", "github", "create_issue", json!({}), false));
+ assert!(!same(&other, &merge(json!({}))));
+ // One of claude's other tools names nothing: it always asks
+ assert!(families(&call("WebSearch", "", "WebSearch", json!({"query": "x"}), true)).is_empty());
+ }
+
+ #[test]
+ fn a_no_is_kept_per_bot_and_conversation_until_cleared() {
+ let d = Declines::default();
+ d.record("k1", "th1", &fam("gh pr view 12"), "ap1");
+ assert_eq!(d.check("k1", "th1", &fam("/usr/bin/gh pr view --json title")).as_deref(), Some("ap1"));
+ assert_eq!(d.check("k1", "th1", &fam("gh issue list")), None, "another family");
+ assert_eq!(d.check("k1", "th2", &fam("gh pr view")), None, "another conversation");
+ assert_eq!(d.check("k2", "th1", &fam("gh pr view")), None, "another bot");
+ assert_eq!(d.check("k1", "th1", &fam("git status && gh pr view")).as_deref(), Some("ap1"), "any part of a line");
+ assert_eq!(d.check("k1", "th1", &[]), None);
+ d.clear("k1", "th1");
+ assert_eq!(d.check("k1", "th1", &fam("gh pr view")), None, "the person wrote again");
+
+ d.record("k1", "th1", &fam("gh pr view"), "ap2");
+ d.record("k2", "th1", &fam("gh pr view"), "ap3");
+ d.record("k1", "th2", &fam("gh pr view"), "ap4");
+ d.forget_kwant("k1");
+ assert_eq!(d.check("k1", "th1", &fam("gh pr view")), None);
+ assert_eq!(d.check("k2", "th1", &fam("gh pr view")).as_deref(), Some("ap3"));
+ d.forget_conversation("th1");
+ assert_eq!(d.check("k2", "th1", &fam("gh pr view")), None);
+ }
+
+ #[test]
+ fn the_memory_is_capped() {
+ let d = Declines::default();
+ for i in 0..MAX_PER_CONVERSATION + 5 {
+ d.record("k1", "th1", &[format!("mcp:s/t{i}")], &format!("ap{i}"));
+ }
+ assert_eq!(d.check("k1", "th1", &["mcp:s/t0".into()]), None, "the oldest went first");
+ assert!(d.check("k1", "th1", &[format!("mcp:s/t{}", MAX_PER_CONVERSATION + 4)]).is_some());
+ for i in 0..MAX_CONVERSATIONS + 3 {
+ d.record("k1", &format!("c{i}"), &["mcp:s/t".into()], "ap");
+ }
+ assert!(d.lock().by_chat.len() <= MAX_CONVERSATIONS);
+ assert!(d.check("k1", &format!("c{}", MAX_CONVERSATIONS + 2), &["mcp:s/t".into()]).is_some());
+ }
+}
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
index 3574b792..5ca2ee1b 100644
--- a/src/mcp/mod.rs
+++ b/src/mcp/mod.rs
@@ -6,6 +6,7 @@ pub mod cli_config;
pub mod cli_hooks;
pub mod client;
pub mod composio;
+pub mod declined;
pub mod echo_server;
pub mod fetch_risk;
pub mod home_floor;
@@ -456,10 +457,21 @@ pub enum ApprovalOutcome {
/// A Skill Foundry replay (a dry run): the call didn't run and was recorded as what the bot
/// would have done.
Rehearsed,
-}
-
-/// What the bot is told when the person refused a call.
-pub const DENIED_TEXT: &str = "The user denied this tool call.";
+ /// 27b: the person already declined a call of this kind in this chat ([`declined`]), so it was
+ /// refused with no card. Recorded as `denied`.
+ DeclinedBefore,
+}
+
+/// 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.";
+/// 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
+/// like it in this chat ([`ApprovalOutcome::DeclinedBefore`]).
+pub const DECLINED_BEFORE_TEXT: &str = "The person already said no to a call like this in this chat, so kwant didn't run it or ask again. \
+Don't try it again or another way. In your reply, say what you couldn't do; if the person still wants it, they can say so in this chat and you can try again.";
+/// 27b: the step detail of a call refused as [`ApprovalOutcome::DeclinedBefore`].
+pub const DECLINED_BEFORE_STEP_DETAIL: &str = "You said no to a call like this earlier in this chat; kwant didn't ask again";
/// What the bot is told when nobody answered the card in time.
pub const UNANSWERED_TEXT: &str = "No one has answered the approval card for this call yet, so it did not run. \
The card stays open: if the person allows it later, you will be started again to make this same call and continue. \
@@ -511,6 +523,7 @@ impl ApprovalOutcome {
match self {
ApprovalOutcome::Unanswered => UNANSWERED_TEXT,
ApprovalOutcome::Rehearsed => REHEARSED_TEXT,
+ ApprovalOutcome::DeclinedBefore => DECLINED_BEFORE_TEXT,
_ => DENIED_TEXT,
}
}
@@ -519,7 +532,7 @@ impl ApprovalOutcome {
pub fn record_status(self) -> &'static str {
match self {
ApprovalOutcome::Allowed => "allowed",
- ApprovalOutcome::Denied => "denied",
+ ApprovalOutcome::Denied | ApprovalOutcome::DeclinedBefore => "denied",
ApprovalOutcome::Unanswered => "unanswered",
ApprovalOutcome::Rehearsed => "rehearsed",
}
@@ -715,6 +728,19 @@ mod folder_file_tests {
mod tests {
use super::*;
+ /// 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]
+ fn a_no_tells_the_bot_not_to_try_another_way() {
+ assert!(DENIED_TEXT.starts_with("The user denied this tool call. "));
+ assert!(DENIED_TEXT.ends_with(NOT_ANOTHER_WAY_TEXT));
+ assert_eq!(ApprovalOutcome::Denied.refusal_text(), DENIED_TEXT);
+ assert_eq!(ApprovalOutcome::DeclinedBefore.refusal_text(), DECLINED_BEFORE_TEXT);
+ assert_eq!(ApprovalOutcome::DeclinedBefore.record_status(), "denied");
+ assert!(!ApprovalOutcome::DeclinedBefore.allowed());
+ assert!(missed_status("denied") && !reminds("denied"));
+ }
+
fn input(json: Value) -> McpServerInput {
serde_json::from_value(json).unwrap()
}
diff --git a/src/mcp/shell_risk.rs b/src/mcp/shell_risk.rs
index af3a9739..837560e6 100644
--- a/src/mcp/shell_risk.rs
+++ b/src/mcp/shell_risk.rs
@@ -171,6 +171,26 @@ fn lex(command: &str) -> Result<Vec<Tok>, String> {
Ok(toks)
}
+/// 27b: the simple commands in `command`, each as its words the way the shell passes them on
+/// (quotes removed), with redirects and their files left out. `None` when the line can't be read
+/// (a variable, a subshell, a heredoc, more than one line).
+pub(crate) fn simple_commands(command: &str) -> Option<Vec<Vec<String>>> {
+ let mut commands = vec![Vec::new()];
+ let mut toks = lex(command).ok()?.into_iter();
+ while let Some(tok) = toks.next() {
+ match tok {
+ Tok::Word(w) => commands.last_mut()?.push(w.text),
+ Tok::Sep => commands.push(Vec::new()),
+ Tok::Redirect => {
+ toks.next();
+ }
+ Tok::Dup => {}
+ }
+ }
+ commands.retain(|c| !c.is_empty());
+ Some(commands)
+}
+
/// Programs that reach outside the folder by their nature, with what they do.
const RISKY: &[(&str, &str)] = &[
("curl", "uses the network"),
@@ -441,7 +461,7 @@ fn simple_command(words: &[Word], ctx: &mut Ctx) -> Verdict {
}
/// `NAME=` at the start of a word: the name.
-fn assignment(text: &str) -> Option<(&str, ())> {
+pub(crate) fn assignment(text: &str) -> Option<(&str, ())> {
let (name, _) = text.split_once('=')?;
let mut chars = name.chars();
let first = chars.next()?;
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index 92735e79..7191cdcd 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -460,6 +460,22 @@ impl BrokerApprover {
}
return (ApprovalOutcome::Denied, "denied", None);
}
+ // 27b: the person already said no to a call like this in this chat. Their no wins over
+ // "not risky", "always allow" and the floors, until they write here again; a late Allow
+ // on an older card is still the person saying yes
+ let families = mcp::declined::families(&req);
+ if let Some(before) = self.broker.declined.check(&req.kwant_id, &self.conversation, &families) {
+ if self.broker.take_grant(&req.kwant_id, &self.conversation, &req.tool_name, &req.arguments).await {
+ return (ApprovalOutcome::Allowed, "approved", None);
+ }
+ tracing::info!(kwant = %req.kwant_id, tool = %req.tool_name, declined_before = %before, "refused without a card: the person already said no to this");
+ let mut record = record;
+ record.parameters["declined_before"] = json!(before);
+ if let Err(e) = self.db.save_refused(&record).await {
+ tracing::warn!(error = %e, "could not record a refused call");
+ }
+ return (ApprovalOutcome::DeclinedBefore, "denied", None);
+ }
if let Some(mcp::SmartVerdict::Allow(why)) = &smart {
tracing::info!(kwant = %req.kwant_id, tool = %req.tool_name, reason = %why, "ran without a card: not risky");
if let Err(e) = self.db.save_auto_allowed(&record).await {
@@ -556,7 +572,12 @@ impl BrokerApprover {
self.broker.allow_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await;
ApprovalOutcome::Allowed
}
- Ok(Ok(ApprovalDecision::Deny)) | Ok(Err(_)) => ApprovalOutcome::Denied,
+ // 27b: only the person's own no is remembered, not a dropped card
+ Ok(Ok(ApprovalDecision::Deny)) => {
+ self.broker.declined.record(&req.kwant_id, &self.conversation, &families, &ticket);
+ ApprovalOutcome::Denied
+ }
+ Ok(Err(_)) => ApprovalOutcome::Denied,
// Nobody answered: the card stays up as `waiting`, and a late Allow resumes the work
// (see `resume_late_approval`)
Err(_) => {
@@ -652,10 +673,22 @@ fn turn_conversation(state: &AppState, turn_id: &str) -> String {
.active_turns()
.into_iter()
.find(|t| t.turn_id == turn_id)
- .map(|t| t.thread_id.unwrap_or(t.context_id))
+ .map(|t| conversation_of(t.thread_id, t.context_id))
.unwrap_or_else(|| format!("turn:{turn_id}"))
}
+/// The conversation of a turn in `thread_id`, else in `context_id` (its channel or direct chat):
+/// what "always allow" and a declined call (27b) are kept for.
+pub(super) fn conversation_of(thread_id: Option<String>, context_id: String) -> String {
+ thread_id.unwrap_or(context_id)
+}
+
+/// 27b: the person wrote to `kwant_id` in the conversation of `thread_id`, else `context_id`, so
+/// what they declined there may be asked again.
+pub(super) fn person_wrote(broker: &PermissionBroker, kwant_id: &str, thread_id: Option<String>, context_id: String) {
+ broker.declined.clear(kwant_id, &conversation_of(thread_id, context_id));
+}
+
/// The chat a tracked turn runs in, as `{"thread_id"}`, `{"channel_id"}` or
/// `{"direct_kwant_id"}`; `None` for a turn kwnt isn't tracking.
pub(super) async fn turn_chat(state: &AppState, turn_id: &str) -> Option<Value> {
@@ -1604,3 +1637,389 @@ mod expired_tests {
assert_eq!((p.direct_kwant_id, p.channel_id.as_deref()), (None, Some("c1")));
}
}
+
+/// 27b: after the person declines a card, a call of the same family in that chat is refused
+/// without a card until they write there again.
+#[cfg(test)]
+mod declined_tests {
+ use super::*;
+ use crate::config::Config;
+ use crate::db::{models::NewKwant, spaces::SpaceId};
+ use crate::router::LayaRouter;
+ use crate::tools::ToolRunner;
+ use axum::body::{to_bytes, Body};
+ use tempfile::{tempdir, TempDir};
+ use tower::ServiceExt;
+
+ struct Env {
+ state: AppState,
+ bot: Kwant,
+ general: String,
+ _tmp: TempDir,
+ }
+
+ async fn setup() -> Env {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ let space = SpaceId::default_space();
+ // The space's one MCP server is a plain http one, so a turn is set up the same on every
+ // OS: the seeded stdio servers can all be dropped by `isolate_stdio_servers` (they are on
+ // Windows), and with no server left `prepare_turn_with_opts` returns None
+ for s in state.db.list_mcp_servers(&space).await.unwrap() {
+ state.db.delete_mcp_server(&s.id).await.unwrap();
+ }
+ state.db.create_mcp_server(&space, &http_server("tools", "http://127.0.0.1:9/mcp")).await.unwrap();
+ let bot = state.db.list_kwants(&space).await.unwrap()[0].clone();
+ let general = state.db.list_channels(&space).await.unwrap().into_iter().find(|c| c.name == "general").unwrap().id;
+ Env { state, bot, general, _tmp: tmp }
+ }
+
+ fn http_server(name: &str, url: &str) -> McpServer {
+ McpServer {
+ id: format!("s-{name}"),
+ name: name.into(),
+ transport: "http".into(),
+ command: None,
+ args: vec![],
+ url: Some(url.into()),
+ env: Default::default(),
+ headers: Default::default(),
+ enabled: true,
+ timeout_secs: 10,
+ created_at: None,
+ }
+ }
+
+ async fn other_bot(e: &Env) -> Kwant {
+ let input = NewKwant {
+ name: "Other".into(),
+ title: "Tester".into(),
+ persona_prompt: String::new(),
+ soul: String::new(),
+ avatar_sprite: "s".into(),
+ driver_type: "cli".into(),
+ preferred_model: "codex".into(),
+ };
+ e.state.db.create_kwant(&SpaceId::default_space(), &input).await.unwrap()
+ }
+
+ fn approver(e: &Env, conversation: &str, timeout: Duration) -> BrokerApprover {
+ BrokerApprover {
+ db: e.state.db.clone(),
+ data_dir: e.state.config.data_dir.clone(),
+ broker: e.state.broker.clone(),
+ events: e.state.event_sender.clone(),
+ timeout,
+ conversation: conversation.to_string(),
+ chat: None,
+ always_ask: false,
+ strict_ask: false,
+ started_by: None,
+ }
+ }
+
+ fn bash(bot: &Kwant, command: &str) -> ToolApprovalRequest {
+ ToolApprovalRequest {
+ kwant_id: bot.id.clone(),
+ kwant_name: bot.name.clone(),
+ turn_id: "t-27b".into(),
+ tool_name: "Bash".into(),
+ server: String::new(),
+ tool: "Bash".into(),
+ arguments: json!({"command": command}),
+ builtin: Some(mcp::BuiltinCall { cwd: None, outside_folder: false }),
+ smart: None,
+ payment: None,
+ }
+ }
+
+ /// How a card was answered in [`ask`].
+ #[derive(Clone)]
+ enum Answer {
+ Decide(ApprovalDecision),
+ /// Its channel goes away with no decision.
+ Drop,
+ /// Nobody answers before the approver stops waiting.
+ Nothing,
+ }
+
+ /// `a.decide(req)`, answering the card it shows with `answer`: the outcome and the card's
+ /// ticket, `None` when no card went out.
+ async fn ask(e: &Env, a: &BrokerApprover, req: ToolApprovalRequest, answer: Answer) -> (ApprovalOutcome, Option<String>) {
+ let mut events = e.state.event_sender.subscribe();
+ let broker = e.state.broker.clone();
+ let decide = a.decide(req);
+ tokio::pin!(decide);
+ let mut card = None;
+ let outcome = loop {
+ tokio::select! {
+ out = &mut decide => break out,
+ ev = events.recv() => {
+ if let Ok(RuntimeEvent::ApprovalRequired { id, .. }) = ev {
+ assert!(card.is_none(), "two cards for one call");
+ match answer.clone() {
+ Answer::Decide(d) => assert!(broker.resolve(&id, d).await),
+ Answer::Drop => assert!(broker.cancel(&id).await),
+ Answer::Nothing => {}
+ }
+ card = Some(id);
+ }
+ }
+ }
+ };
+ while let Ok(ev) = events.try_recv() {
+ if let RuntimeEvent::ApprovalRequired { id, .. } = ev {
+ panic!("a card went out after the call was settled: {id}");
+ }
+ }
+ (outcome, card)
+ }
+
+ /// The bot's approvals rows: (status, details).
+ async fn approvals_of(e: &Env, bot: &Kwant) -> Vec<(String, Value)> {
+ let rows = e.state.db.list_approvals(&SpaceId::default_space(), None, Some(&bot.id)).await.unwrap();
+ rows.into_iter().map(|r| (r.status, serde_json::from_str(&r.parameters).unwrap())).collect()
+ }
+
+ const DENY: Answer = Answer::Decide(ApprovalDecision::Deny);
+ const ALLOW: Answer = Answer::Decide(ApprovalDecision::AllowOnce);
+
+ #[tokio::test]
+ async fn a_declined_call_s_family_is_refused_without_a_card() {
+ let e = setup().await;
+ let a = approver(&e, &e.general, Duration::from_secs(10));
+ let (out, card) = ask(&e, &a, bash(&e.bot, "gh pr view 12"), DENY).await;
+ assert_eq!(out, ApprovalOutcome::Denied);
+ let declined = card.expect("the first call asks");
+ let rows = approvals_of(&e, &e.bot).await.len();
+
+ // The same family another way: refused at once, no card, and no new ticket to answer
+ let (out, card) = ask(&e, &a, bash(&e.bot, "gh pr view --json title"), ALLOW).await;
+ assert_eq!(out, ApprovalOutcome::DeclinedBefore);
+ assert_eq!(card, None);
+ let after = approvals_of(&e, &e.bot).await;
+ assert_eq!(after.len(), rows + 1, "one closed record, not a card");
+ let (status, details) = after.iter().find(|(_, d)| d["declined_before"].is_string()).expect("the refusal is on record");
+ assert_eq!(status, "denied");
+ assert_eq!(details["declined_before"], json!(declined));
+ assert!(e.state.broker.pending_ids().await.is_empty(), "nothing waits for an answer");
+
+ // Wrapped, piped or behind a cd: still the same family
+ for again in ["cd repo && gh pr view 12 | head", "sudo gh -R o/r pr view 13", "bash -c 'gh pr view 14'"] {
+ let (out, card) = ask(&e, &a, bash(&e.bot, again), ALLOW).await;
+ assert_eq!((out, card), (ApprovalOutcome::DeclinedBefore, None), "{again}");
+ }
+
+ // Another family still asks
+ let (out, card) = ask(&e, &a, bash(&e.bot, "gh issue list"), ALLOW).await;
+ assert_eq!(out, ApprovalOutcome::Allowed);
+ assert!(card.is_some(), "gh issue list asks");
+ }
+
+ #[tokio::test]
+ async fn only_the_person_s_no_is_remembered() {
+ let e = setup().await;
+
+ // Nobody answered: the card is parked, and the next call asks again
+ let a = approver(&e, &e.general, Duration::from_millis(200));
+ let (out, card) = ask(&e, &a, bash(&e.bot, "gh pr view 1"), Answer::Nothing).await;
+ assert_eq!((out, card.is_some()), (ApprovalOutcome::Unanswered, true));
+ let (out, card) = ask(&e, &a, bash(&e.bot, "gh pr view 2"), Answer::Nothing).await;
+ assert_eq!((out, card.is_some()), (ApprovalOutcome::Unanswered, true), "unanswered isn't a no");
+
+ // The card's channel went away (its turn ended): not a no either
+ let a = approver(&e, &e.general, Duration::from_secs(10));
+ let (out, card) = ask(&e, &a, bash(&e.bot, "docker run x"), Answer::Drop).await;
+ assert_eq!((out, card.is_some()), (ApprovalOutcome::Denied, true));
+ let (out, card) = ask(&e, &a, bash(&e.bot, "docker run y"), ALLOW).await;
+ assert_eq!((out, card.is_some()), (ApprovalOutcome::Allowed, true), "a dropped card isn't a no");
+
+ // kwnt refusing a call that names its own secrets: no card, and nothing remembered
+ let (out, card) = ask(&e, &a, bash(&e.bot, "gh api --input ~/.kwnt/api-token user"), ALLOW).await;
+ assert_eq!((out, card), (ApprovalOutcome::Denied, None));
+ let (out, card) = ask(&e, &a, bash(&e.bot, "gh api user"), ALLOW).await;
+ assert_eq!((out, card.is_some()), (ApprovalOutcome::Allowed, true), "kwnt's refusal isn't the person's no");
+ }
+
+ #[tokio::test]
+ async fn a_no_holds_in_its_own_chat_and_bot_until_the_person_writes_there() {
+ let e = setup().await;
+ let other = other_bot(&e).await;
+ let here = approver(&e, &e.general, Duration::from_secs(10));
+ let (out, _) = ask(&e, &here, bash(&e.bot, "npm publish"), DENY).await;
+ assert_eq!(out, ApprovalOutcome::Denied);
+
+ // Another conversation with the same bot asks
+ let thread = approver(&e, "thread-1", Duration::from_secs(10));
+ let (out, card) = ask(&e, &thread, bash(&e.bot, "npm publish --tag next"), DENY).await;
+ assert_eq!((out, card.is_some()), (ApprovalOutcome::Denied, true));
+ // Another bot in the same conversation asks
+ let (out, card) = ask(&e, &here, bash(&other, "npm publish"), ALLOW).await;
+ assert_eq!((out, card.is_some()), (ApprovalOutcome::Allowed, true));
+ // This bot here doesn't
+ let (out, card) = ask(&e, &here, bash(&e.bot, "npm publish --dry-run"), ALLOW).await;
+ assert_eq!((out, card), (ApprovalOutcome::DeclinedBefore, None));
+
+ // The person writes to another bot, or to this bot in the thread: still a no here
+ person_wrote(&e.state.broker, &other.id, None, e.general.clone());
+ person_wrote(&e.state.broker, &e.bot.id, Some("thread-1".into()), e.general.clone());
+ let (out, card) = ask(&e, &here, bash(&e.bot, "npm publish"), ALLOW).await;
+ assert_eq!((out, card), (ApprovalOutcome::DeclinedBefore, None));
+ // The thread's no went with the person's message there
+ let (out, card) = ask(&e, &thread, bash(&e.bot, "npm publish"), ALLOW).await;
+ assert_eq!((out, card.is_some()), (ApprovalOutcome::Allowed, true));
+
+ // The person writes to this bot here: it asks again
+ person_wrote(&e.state.broker, &e.bot.id, None, e.general.clone());
+ let (out, card) = ask(&e, &here, bash(&e.bot, "npm publish"), ALLOW).await;
+ assert_eq!((out, card.is_some()), (ApprovalOutcome::Allowed, true));
+ }
+
+ #[tokio::test]
+ async fn the_approver_s_conversation_is_the_one_a_message_clears() {
+ let e = setup().await;
+ for thread_id in [None, Some("thread-9".to_string())] {
+ let turn_id = uuid::Uuid::new_v4().to_string();
+ e.state.turns.set_turn(super::super::turns::ActiveTurn {
+ turn_id: turn_id.clone(),
+ kwant_id: e.bot.id.clone(),
+ context_id: e.general.clone(),
+ thread_id: thread_id.clone(),
+ state: "running".into(),
+ since: chrono::Utc::now(),
+ purpose: None,
+ audit: None,
+ });
+ assert_eq!(turn_conversation(&e.state, &turn_id), conversation_of(thread_id, e.general.clone()));
+ e.state.turns.end_turn(&turn_id);
+ }
+ }
+
+ /// claude's permission prompt for `tool {input}` in a live turn of the bot in #general, the
+ /// card (if any) answered with `answer`: the permission tool's reply.
+ async fn claude_asks(e: &Env, tool: &str, input: Value, answer: Answer) -> (Value, Option<String>) {
+ let turn_id = uuid::Uuid::new_v4().to_string();
+ let folder = tempdir().unwrap();
+ // The turn is registered before its MCP context is built, as `turn_once` does: the
+ // approver takes its conversation from the registry then, and an unregistered turn is a
+ // conversation of its own (`turn:<id>`), so two asks wouldn't share the person's no
+ e.state.turns.set_turn(super::super::turns::ActiveTurn {
+ turn_id: turn_id.clone(),
+ kwant_id: e.bot.id.clone(),
+ context_id: e.general.clone(),
+ thread_id: None,
+ state: "running".into(),
+ since: chrono::Utc::now(),
+ purpose: None,
+ audit: None,
+ });
+ let (_, token) = prepare_turn_with_opts(&e.state, &e.bot, Some(turn_id.clone()), Some(folder.path().to_path_buf()), None, Default::default())
+ .await
+ .unwrap();
+ let app = super::super::create_router(e.state.clone());
+ let body = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "approve",
+ "arguments": {"tool_name": tool, "input": input, "tool_use_id": "tu_1"}}});
+ let request = axum::http::Request::builder()
+ .method("POST")
+ .uri(format!("/api/mcp/permission/{token}"))
+ .header("content-type", "application/json")
+ .body(Body::from(body.to_string()))
+ .unwrap();
+ let mut events = e.state.event_sender.subscribe();
+ let prompt = app.oneshot(request);
+ tokio::pin!(prompt);
+ let mut card = None;
+ let resp = loop {
+ tokio::select! {
+ 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);
+ }
+ card = Some(id);
+ }
+ }
+ }
+ };
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ let v: Value = serde_json::from_slice(&bytes).unwrap();
+ finish_turn(&e.state, &token).await;
+ e.state.turns.end_turn(&turn_id);
+ let text = v["result"]["content"][0]["text"].as_str().unwrap_or_else(|| panic!("{v}"));
+ (serde_json::from_str(text).unwrap(), card)
+ }
+
+ #[tokio::test]
+ async fn claude_is_told_it_was_already_declined() {
+ let e = setup().await;
+ let (reply, card) = claude_asks(&e, "Bash", json!({"command": "git push origin main"}), DENY).await;
+ assert!(card.is_some());
+ assert_eq!(reply["behavior"], "deny");
+ let (reply, card) = claude_asks(&e, "Bash", json!({"command": "git push --force origin main"}), ALLOW).await;
+ assert_eq!(card, None, "no card the second time");
+ assert_eq!(reply, json!({"behavior": "deny", "message": mcp::DECLINED_BEFORE_TEXT}));
+ }
+
+ #[tokio::test]
+ async fn an_api_bot_s_tool_result_says_it_was_already_declined() {
+ let e = setup().await;
+ // A real MCP server over http for the API engine's tool session: kwnt's own permission
+ // endpoint for a live turn, whose one tool is `approve`
+ let (_, token) = prepare_turn_with_opts(&e.state, &e.bot, Some("t-host".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,
+ };
+ 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".into() };
+
+ let mut events = e.state.event_sender.subscribe();
+ let first = {
+ let call = session.call(&caller, "c1", "mcp__perm__approve", r#"{"tool_name": "Bash", "input": {}}"#);
+ tokio::pin!(call);
+ loop {
+ tokio::select! {
+ out = &mut call => break out,
+ ev = events.recv() => {
+ if let Ok(RuntimeEvent::ApprovalRequired { id, .. }) = ev {
+ assert!(e.state.broker.resolve(&id, ApprovalDecision::Deny).await);
+ }
+ }
+ }
+ }
+ };
+ assert_eq!((first.status, first.text.as_str()), ("denied", mcp::DENIED_TEXT));
+
+ let second = session.call(&caller, "c2", "mcp__perm__approve", r#"{"tool_name": "Read", "input": {}}"#).await;
+ assert_eq!((second.status, second.text.as_str()), ("denied", mcp::DECLINED_BEFORE_TEXT));
+ assert_eq!(second.record["status"], "denied");
+ while let Ok(ev) = events.try_recv() {
+ assert!(!matches!(ev, RuntimeEvent::ApprovalRequired { .. }), "no card the second time");
+ }
+ session.shutdown().await;
+ finish_turn(&e.state, &token).await;
+ serve.abort();
+ }
+}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 511bbe14..2661bdf7 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -2446,6 +2446,11 @@ pub(super) async fn turn_once(
// Only the person's own message carries a nav prompt (hand-offs, routines, missions and Jira
// tasks never do), so this is how the stop knows it held the person's message
let person_turn = opts.nav_prompt.is_some();
+ // 27b: the person wrote again, so what they declined in this conversation may be asked again.
+ // A turn kwant starts on its own (follow-through, keep-going, a hand-off, a routine) keeps it
+ if person_turn {
+ super::mcp_runtime::person_wrote(&scope.state.broker, &target_kwant.id, tag.thread_id.clone(), tag.context_id.clone());
+ }
super::spend_stop::gate(scope, target_kwant, quiet_stop, person_turn).await?;
// Then the bot's own monthly budget (G2): daily stop, mission budget (checked by the mission
// runner before it asks for a turn), bot budget; the first one hit holds the turn. A turn that
diff --git a/tests/builtin_tools_test.rs b/tests/builtin_tools_test.rs
index 7c931f74..8b6b972d 100644
--- a/tests/builtin_tools_test.rs
+++ b/tests/builtin_tools_test.rs
@@ -107,7 +107,7 @@ async fn built_in_tools_follow_the_folder_policy() {
// Writing outside the folder (or escaping it with ..) shows a card; Deny refuses it
let outside = tmp.path().join("elsewhere.txt").display().to_string();
- for path in [outside.clone(), "../elsewhere.txt".to_string()] {
+ for path in [outside.clone(), "../other.txt".to_string()] {
let ask = tokio::spawn({
let (app, token) = (app.clone(), token.clone());
async move { claude_asks(&app, &token, "Write", json!({"file_path": path, "content": "x"})).await }
@@ -121,6 +121,12 @@ async fn built_in_tools_follow_the_folder_policy() {
assert_eq!(status, StatusCode::OK);
assert_eq!(ask.await.unwrap()["behavior"], "deny");
}
+ // 27b: writing a file the person said no to is refused at once, with no card
+ let again = tokio::time::timeout(Duration::from_secs(5), claude_asks(&app, &token, "Write", json!({"file_path": outside, "content": "y"})))
+ .await
+ .expect("no card the second time");
+ assert_eq!(again, json!({"behavior": "deny", "message": kwnt::mcp::DECLINED_BEFORE_TEXT}));
+ assert!(state.broker.pending_ids().await.is_empty());
// A shell command shows a card with the command and folder; Allow once runs it once
let bash = |cmd: &str| json!({"command": cmd, "description": "List files"});
diff --git a/tests/mcp_api_loop_test.rs b/tests/mcp_api_loop_test.rs
index 8b96f3ba..72ae83ac 100644
--- a/tests/mcp_api_loop_test.rs
+++ b/tests/mcp_api_loop_test.rs
@@ -193,7 +193,7 @@ async fn denied_call_is_not_run_and_model_is_told() {
let c = ctx(Arc::new(FixedApprover(false)), 10, 8);
let (out, _) = run(url, input(Some(c.clone()))).await;
assert_eq!(out.text, "ok, no tool");
- assert_eq!(tool_message(&mock, 1)["content"], "The user denied this tool call.");
+ assert_eq!(tool_message(&mock, 1)["content"], kwnt::mcp::DENIED_TEXT);
let records = c.take_records();
assert_eq!(records[0]["status"], "denied");
assert!(records[0].get("result").is_none());
@@ -329,7 +329,7 @@ async fn anthropic_tool_calls_go_through_the_approver() {
assert_eq!(out.text, "ok, no tool");
let requests = mock.requests.lock().unwrap().clone();
let last = requests[1]["messages"].as_array().unwrap().last().unwrap().clone();
- assert_eq!(last["content"][0]["content"], "The user denied this tool call.");
+ assert_eq!(last["content"][0]["content"], kwnt::mcp::DENIED_TEXT);
assert_eq!(c.take_records()[0]["status"], "denied");
}
diff --git a/tests/mcp_gateway_test.rs b/tests/mcp_gateway_test.rs
index e18f6ada..39bc7993 100644
--- a/tests/mcp_gateway_test.rs
+++ b/tests/mcp_gateway_test.rs
@@ -139,7 +139,7 @@ async fn gateway_denied_call_returns_no_output() {
let mut client = McpClient::connect(&gateway(&base, Some("deny-tok")), None).await.unwrap();
let out = client.call_tool("echo__echo", json!({"text": "must not run"})).await.unwrap();
assert!(out.is_error);
- assert_eq!(out.text, "The user denied this tool call.");
+ assert_eq!(out.text, kwnt::mcp::DENIED_TEXT);
client.shutdown().await;
let records = ctx.take_records();
diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rs
index adbe4e42..1ccf9549 100644
--- a/tests/mcp_runtime_test.rs
+++ b/tests/mcp_runtime_test.rs
@@ -131,6 +131,10 @@ async fn broker_approver_follows_user_decisions() {
let (h, ticket) = ask(&state, a.clone(), "echo").await;
assert!(state.broker.resolve(&ticket, ApprovalDecision::Deny).await);
assert!(!h.await.unwrap(), "denied by broker");
+ // 27b: the same tool in the same chat is refused at once, with no card, until the person writes
+ assert!(!tokio::time::timeout(Duration::from_secs(5), a.approve(request("echo"))).await.expect("no card the second time"));
+ assert!(state.broker.pending_ids().await.is_empty());
+ state.broker.declined.clear("k1", "conv-test");
let (h, ticket) = ask(&state, a.clone(), "echo").await;
assert_eq!(state.db.get_approval(&ticket).await.unwrap().unwrap().status, "pending");