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.

Payments always ask, even with approvals off (Phase C D8)

Lin (kwant bot)63c1e0da748d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8c4f6113..1b8fd384 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
its card has a Connect button. It opens the app's sign-in in your browser (in the Mac app too), shows
"Connected" once the sign-in finishes, and offers to open the sign-in again. Without a usable Composio
connector, the card says what's missing and opens Connections instead.
+- **Payments always ask.** A bot's tool call that looks like paying now shows an approval card even
+ with approvals off, even when "Ask only when risky" finds it safe, and even after "Always this
+ session". Allowing a payment covers that one call. kwant recognises payment apps and Composio
+ actions (Stripe, PayPal, Square, Wise, Coinbase and others), commands that post to payment
+ services or send crypto, and in its browser pay buttons, any click on a checkout page and typed
+ card numbers. It can't catch everything, such as a plain "Continue" on an unusual checkout page or a
+ card a site already saved: see `docs/payments.md`. Sending, deleting, publishing and signing in still
+ run without asking when approvals are off.
- **Mission board: AutoFix, change approvals and restore.** A failed task shows why it failed in plain
words, what AutoFix plans, its tries and what retries cost, with Retry now and Don't retry. Proposed
changes to a check, the acceptance or a routine appear in Needs you with before and after, and only
diff --git a/docs/approvals.md b/docs/approvals.md
index 4b557808..04de1ee4 100644
--- a/docs/approvals.md
+++ b/docs/approvals.md
@@ -9,13 +9,16 @@ refuse it.
|---|---|---|
| `ask` | Ask before running commands | Every tool call outside the bot's folder shows an approval card. |
| `smart` (default for new spaces) | Ask only when risky | Ordinary work runs without a card; anything risky or unclear shows the card, with the reason. |
-| `off` | Don’t ask | Everything runs. |
+| `off` | Don’t ask | Everything runs, except payments: they always ask (see [payments.md](payments.md)). |
A new space, and a fresh install's Default space, start on `smart`. A space made before that
default (it has no approvals row) keeps asking after an upgrade, so updating kwnt never loosens
an install; switch it in Settings when you're ready. While the built-in password store holds
passwords, a new space starts on `ask` instead (see below). An unknown bot always asks.
+Whatever the mode, a call that looks like a payment shows a card, even when `smart` finds it
+safe or "Always this session" was given: see [payments.md](payments.md).
+
Whatever the mode, a call that names kwnt's own secret files (the vault, its key, the API token)
is refused and recorded as `denied`. Calls that run without a card are recorded as
`auto_allowed` (`GET /api/approvals?status=auto_allowed`); under `smart` the row's
@@ -104,9 +107,10 @@ Writes and edits outside the folder and unknown tools still ask. Under every mod
Under `ask` and `smart`, "Always this session" on a claude tool's card allows that tool (e.g. all
`Bash`) for that bot and conversation until kwnt restarts. Under `smart`, API drivers'
`execute_shell` is remembered the same way, per conversation; under `ask` it covers that one
-command only.
+command only. Neither covers a payment, and "Always this session" on a payment's card allows that
+one call.
## Tests
-`cargo test --test smart_approvals_test --test approvals_off_test --test approvals_passwords_test`
+`cargo test --test smart_approvals_test --test approvals_off_test --test approvals_passwords_test --test payment_floor_test`
and the classifier tables in `src/mcp/shell_risk.rs` (`cargo test --lib shell_risk`).
diff --git a/docs/payments.md b/docs/payments.md
new file mode 100644
index 00000000..f65548ee
--- /dev/null
+++ b/docs/payments.md
@@ -0,0 +1,92 @@
+# Payments always ask
+
+A tool call that looks like paying always shows an approval card, whatever the bot's approvals
+say: `ask`, `smart` or `off`. Oleks decided this on 2026-10-27 (Phase C D8): with approvals off,
+sending, deleting, publishing and signing in run without asking, but payments still ask. The
+same will hold at every Flight School tier.
+
+- "Ask only when risky" saying a payment is safe doesn't skip the card.
+- "Always this session" for the tool (e.g. all `Bash`) doesn't skip it.
+- "Always this session" on a payment's own card allows that one call; nothing is remembered,
+ and the next payment asks again.
+- No setting turns this off. It costs the occasional card for something that wasn't a payment.
+- A card the person allowed after its turn ended (late Allow) runs that exact call once, as for
+ any card.
+
+The check is `src/mcp/payment_floor.rs`, a pure function of the tool's name, its arguments and,
+for kwnt's own browser, the address the browser itself reports. Nothing the bot writes, no
+"Ask only when risky" verdict and no task field can mark a call as "not a payment". The card's
+`details.payment_reason` says why it asked. It runs in `BrokerApprover` (claude's tools and
+every MCP tool, through claude's permission prompt and the MCP gateway), in
+`SelfToolsApprover` (kwnt's own `browser_act`), and for API drivers' `execute_shell`.
+
+## What counts as a payment
+
+**MCP and Composio tools** (by tool name, server name, and the `tool_slug`s inside
+`COMPOSIO_MULTI_EXECUTE_TOOL`):
+
+- Every tool of a money-only app that doesn't start with a read verb (`get`, `list`, `retrieve`,
+ `search`, …): Stripe, PayPal, Square, Wise, Coinbase, Braintree, Adyen, Revolut, Mollie,
+ Paddle, Lemon Squeezy, Razorpay, GoCardless, Klarna, Venmo, Cash App, Chargebee, Recurly,
+ Payoneer, Checkout.com, Authorize.net, Plaid, MoonPay, Kraken, Binance.
+- Any other tool whose name has a pay word (`pay`, `payment`, `payout`, `purchase`, `checkout`,
+ `buy`, `charge`, `donate`, …), a money move (`send`/`transfer`/`withdraw` with `money`,
+ `funds`, `crypto`, `btc`, `usd`, …), or an order step (`place`/`submit`/`confirm` with
+ `order`, `purchase`, `booking`, `subscription`).
+- A browser-type MCP tool (name with `click`, `tap`, `press`, `submit`) whose arguments name a
+ pay-type label, or one that types (`type`, `fill`, `input`, …) a card number.
+- A remote shell tool (`bash`, `shell`, `exec`, `command`…) whose `command` is a payment below.
+
+**Shell commands** (claude's `Bash`, API drivers' `execute_shell`, MCP shell tools):
+
+- A request that writes (`-X POST/PUT/PATCH/DELETE`, `-d`, `--data*`, `--json`, `-F`, `--form`,
+ wget `--post-*`, httpie's method word, or code calling `.post(`) to a payment host:
+ `stripe.com`, `paypal.com`, `squareup.com`, `wise.com`, `coinbase.com`, `adyen.com`, … (the
+ list in `PAYMENT_HOSTS`). A GET doesn't count.
+- `stripe` CLI commands that change something (`post`, `create`, `update`, `delete`,
+ `capture`, `confirm`, `refund`, `trigger`, …).
+- Crypto wallet sends: `cast send`, `bitcoin-cli sendtoaddress/sendmany/send…`, `solana
+ transfer`, `spl-token transfer`, `electrum payto`, `lncli sendpayment/payinvoice/sendcoins`,
+ `lightning-cli pay/withdraw`, `monero-wallet-cli transfer`, `cardano-cli … submit`, and others
+ in `WALLETS`.
+
+**kwnt's own browser** (`browser_act`):
+
+- Clicking a pay-type label: `Pay`, `Buy`, `Purchase`, `Checkout`/`Check out`, `Subscribe`,
+ `Upgrade`, `Donate`, `Place order`, `Confirm order`, `Complete payment`, `Book now`, `Top up`,
+ … or any label with a price on it (`$12.99`, `12,99 €`, `USD 10`).
+- Any click, or Enter, on a checkout page: a payment host (`checkout.stripe.com`, `paypal.com`,
+ `pay.google.com`, …), a host starting `checkout.`/`pay.`/`payment.`/`billing.`, or a path
+ segment like `/checkout`, `/payment`, `/pay`, `/billing`, `/buy`, `/subscribe`. The address
+ comes from the browser, not the bot.
+- Typing anything that looks like a card number: 13–19 digits (spaces or dashes allowed) that
+ pass the Luhn check.
+
+`WebFetch` never pays (it only reads). kwnt's own other tools don't pay, and
+`self_tools_have_no_money_words` fails if one is added with a money word in its name until it is
+classified here.
+
+## What it doesn't catch
+
+- A plain "Continue", "Next" or "Confirm" button on a checkout page whose address doesn't look
+ like one (no checkout word in the host or path).
+- A card the website already has saved, one-click buying, and Apple Pay or Google Pay sheets.
+- Payment fields inside another site's frame on a normal-looking page (the address checked is
+ the page's, not the frame's).
+- A card number typed in pieces (one field for each group of 4 digits).
+- Shell commands that hide the host or method: variables (`$URL`), scripts, config files, other
+ languages' HTTP libraries without `.post(`, and SDKs (`stripe.Charge.create(...)` in Python).
+- Payment services, MCP tools and wallets missing from the lists, and tools whose names don't
+ say what they do.
+- Codex's own shell, which kwnt never sees. Its sandbox has no network, so it can't reach a
+ payment service.
+- Someone else's browser tools the bot drives through an MCP server, unless the tool's label or
+ typed text matches the rules above.
+
+It also asks for some things that aren't payments, e.g. an "Upgrade" link in docs or any click on
+a `/billing` page. That's accepted: an extra card costs a tap, a missed payment costs money.
+
+## Tests
+
+`cargo test --test payment_floor_test` and the tables in `src/mcp/payment_floor.rs`
+(`cargo test --lib payment_floor`).
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
index 47a605d2..19df03e5 100644
--- a/src/mcp/mod.rs
+++ b/src/mcp/mod.rs
@@ -8,6 +8,7 @@ pub mod composio;
pub mod echo_server;
pub mod fetch_risk;
pub mod oauth;
+pub mod payment_floor;
pub mod oauth_mock;
pub mod registry;
pub mod session;
@@ -266,6 +267,9 @@ pub struct ToolApprovalRequest {
/// What "Ask only when risky" makes of this call; `None` asks. Only read when the bot's
/// approvals are `smart`.
pub smart: Option<SmartVerdict>,
+ /// Why the caller already knows this call pays (kwnt's browser on a checkout page), for the
+ /// payment floor; the approver also checks the call itself ([`payment_floor::reason`]).
+ pub payment: Option<String>,
}
/// Whether a call may run without a card under "Ask only when risky", and why.
diff --git a/src/mcp/payment_floor.rs b/src/mcp/payment_floor.rs
new file mode 100644
index 00000000..affdf27c
--- /dev/null
+++ b/src/mcp/payment_floor.rs
@@ -0,0 +1,589 @@
+//! The payment floor: tool calls that look like paying always get an approval card, whatever the
+//! bot's approvals are (`ask`, `smart` or `off`), whatever "always allow" was given, and at every
+//! tier. Oleks's decision D8 (2026-10-27): with approvals off, everything else runs without
+//! asking, but payments still ask.
+//!
+//! [`reason`] is pure: it reads only the tool's name, its arguments and, for kwnt's own browser,
+//! the address the browser itself reports. Nothing the bot writes can mark a call as "not a
+//! payment". The lists err on the side of asking: an extra card costs a tap, a missed payment
+//! costs money. What it can't catch is written down in docs/payments.md.
+
+use super::ToolApprovalRequest;
+use serde_json::Value;
+
+/// Apps whose every write tool moves money (MCP server names, Composio toolkit prefixes).
+const MONEY_APPS: &[&str] = &[
+ "stripe", "paypal", "square", "squareup", "wise", "transferwise", "coinbase", "braintree", "adyen", "revolut", "mollie",
+ "paddle", "lemonsqueezy", "razorpay", "gocardless", "klarna", "venmo", "cashapp", "chargebee", "recurly", "payoneer",
+ "checkoutcom", "authorizenet", "plaid", "moonpay", "kraken", "binance",
+];
+
+/// Words that name paying on their own.
+const PAY_WORDS: &[&str] = &[
+ "pay", "payment", "payments", "payout", "payouts", "purchase", "purchases", "checkout", "buy", "donate", "donation",
+ "charge", "charges", "remittance", "remit",
+];
+
+/// Verbs that move money when the noun is money.
+const MOVE_VERBS: &[&str] = &["send", "transfer", "withdraw", "wire", "move", "deposit"];
+const MONEY_NOUNS: &[&str] = &[
+ "money", "funds", "fund", "cash", "crypto", "bitcoin", "btc", "eth", "ether", "usdc", "usdt", "sol", "usd", "eur", "gbp",
+];
+
+/// Verbs that complete an order.
+const ORDER_VERBS: &[&str] = &["place", "submit", "confirm", "complete", "finalize", "finalise"];
+const ORDER_NOUNS: &[&str] = &["order", "orders", "purchase", "booking", "subscription"];
+
+/// A tool whose first action word is one of these only reads.
+const READ_VERBS: &[&str] = &[
+ "get", "list", "retrieve", "search", "find", "read", "fetch", "describe", "view", "show", "count", "lookup", "query",
+ "estimate", "preview", "check", "verify", "validate", "export", "download", "inspect", "status", "info", "balance",
+];
+
+/// Tools that type or fill text in a page (any browser MCP): a card number typed there pays.
+const TYPE_WORDS: &[&str] = &["type", "fill", "input", "enter", "keyboard", "insert", "set", "write"];
+/// Tools that click or submit in a page (any browser MCP): a pay-type label there pays.
+const CLICK_WORDS: &[&str] = &["click", "tap", "press", "submit"];
+
+/// Button and link labels that pay, as whole words or phrases.
+const PAY_LABEL_WORDS: &[&str] = &["pay", "buy", "purchase", "checkout", "subscribe", "upgrade", "donate"];
+const PAY_LABEL_PHRASES: &[&str] = &[
+ "check out", "place order", "place your order", "complete order", "confirm order", "submit order", "send money",
+ "send payment", "make payment", "complete payment", "confirm payment", "authorize payment", "start subscription",
+ "start membership", "add funds", "top up", "book now", "reserve now", "rent now", "order now",
+];
+
+/// Hosts that take payments: a call to one of them that writes, or a click on one of their pages.
+const PAYMENT_HOSTS: &[&str] = &[
+ "stripe.com", "paypal.com", "squareup.com", "square.com", "wise.com", "transferwise.com", "coinbase.com",
+ "braintreegateway.com", "adyen.com", "revolut.com", "mollie.com", "paddle.com", "lemonsqueezy.com", "razorpay.com",
+ "gocardless.com", "klarna.com", "checkout.com", "authorize.net", "payoneer.com", "venmo.com", "cash.app",
+ "pay.google.com", "pay.amazon.com", "chargebee.com", "recurly.com",
+];
+
+/// Address path segments and first host labels that mean a checkout page.
+const CHECKOUT_SEGMENTS: &[&str] = &[
+ "checkout", "checkouts", "payment", "payments", "pay", "billing", "purchase", "buy", "subscribe", "donate",
+ "place-order", "placeorder", "order-review", "review-order",
+];
+
+/// Why this call is a payment, or `None`. `page_url` is the address kwnt's own browser shows now
+/// (from the browser, never from the bot); only used for kwnt's `browser_act`.
+pub fn reason(req: &ToolApprovalRequest, page_url: Option<&str>) -> Option<String> {
+ if req.builtin.is_some() {
+ return builtin_reason(&req.tool, &req.arguments);
+ }
+ if req.server == super::SELF_SERVER_NAME {
+ return self_reason(&req.tool, &req.arguments, page_url);
+ }
+ // Local shell commands reach the approver as execute_shell
+ if req.tool == "execute_shell" {
+ return req.arguments["command"].as_str().and_then(shell_reason);
+ }
+ mcp_reason(&req.server, &req.tool, &req.arguments)
+}
+
+/// claude's own tools: only Bash can pay (WebFetch only reads; file tools touch files).
+fn builtin_reason(tool: &str, input: &Value) -> Option<String> {
+ match tool {
+ "Bash" => input["command"].as_str().and_then(shell_reason),
+ _ => None,
+ }
+}
+
+/// kwnt's own tools: only `browser_act` can pay today. A new self tool with a money word in its
+/// name fails `self_tools_have_no_money_words` until it is classified here.
+fn self_reason(tool: &str, args: &Value, page_url: Option<&str>) -> Option<String> {
+ if tool != "browser_act" {
+ return None;
+ }
+ let text = args["text"].as_str().unwrap_or("");
+ match args["action"].as_str().unwrap_or("") {
+ "click_text" | "click" => {
+ if let Some(why) = pay_label(text) {
+ return Some(why);
+ }
+ page_url.and_then(checkout_page).map(|page| format!("a click on a checkout page ({page})"))
+ }
+ "type" => card_number(text).then(|| "typing what looks like a card number".to_string()),
+ "key" => {
+ let key = args["key"].as_str().unwrap_or("Enter");
+ let submits = matches!(key.to_ascii_lowercase().as_str(), "enter" | "return" | "numpadenter");
+ if submits {
+ page_url.and_then(checkout_page).map(|page| format!("Enter on a checkout page ({page})"))
+ } else {
+ None
+ }
+ }
+ _ => None,
+ }
+}
+
+/// An MCP tool (incl. Composio): by its name and server, the Composio slugs it runs, and for
+/// browser-type tools, the label it clicks or the card number it types.
+fn mcp_reason(server: &str, tool: &str, args: &Value) -> Option<String> {
+ let mut names = vec![tool.to_string()];
+ collect_slugs(args, &mut names, 0);
+ for name in &names {
+ if let Some(why) = name_reason(server, name) {
+ return Some(why);
+ }
+ }
+ let words = words(tool);
+ let has = |list: &[&str]| words.iter().any(|w| list.contains(&w.as_str()));
+ let mut texts = Vec::new();
+ collect_strings(args, &mut texts, 0);
+ if has(TYPE_WORDS) && texts.iter().any(|t| card_number(t)) {
+ return Some(format!("{tool} types what looks like a card number"));
+ }
+ if has(CLICK_WORDS) {
+ if let Some(why) = texts.iter().find_map(|t| pay_label(t)) {
+ return Some(format!("{tool}: {why}"));
+ }
+ }
+ // A shell an MCP server runs (a remote bash tool) is checked like Bash
+ if has(&["bash", "shell", "exec", "execute", "command", "terminal", "run"]) {
+ for key in ["command", "cmd", "script"] {
+ if let Some(why) = args[key].as_str().and_then(shell_reason) {
+ return Some(why);
+ }
+ }
+ }
+ None
+}
+
+/// A tool or slug name that pays: any write tool of a money-only app, or a money verb with a
+/// money noun. A name whose first action word only reads never pays.
+pub fn name_reason(server: &str, name: &str) -> Option<String> {
+ // `mcp__stripe__create_charge` → server stripe, tool create_charge
+ match name.strip_prefix("mcp__").and_then(|r| r.split_once("__")) {
+ Some((server, tool)) => name_words_reason(&words(server), &words(tool), name),
+ None => name_words_reason(&words(server), &words(name), name),
+ }
+}
+
+fn name_words_reason(server_words: &[String], words: &[String], name: &str) -> Option<String> {
+ let app = server_words
+ .iter()
+ .chain(words.first())
+ .find(|w| MONEY_APPS.contains(&w.as_str()))
+ .cloned();
+ // The action words: the name without its app prefix
+ let action: Vec<&str> = words
+ .iter()
+ .map(String::as_str)
+ .skip_while(|w| MONEY_APPS.contains(w) || ["composio", "mcp"].contains(w))
+ .collect();
+ if action.first().is_some_and(|w| READ_VERBS.contains(w)) {
+ return None;
+ }
+ if let Some(app) = app {
+ if !action.is_empty() {
+ return Some(format!("{name} changes something in {app}, a payment app"));
+ }
+ }
+ let has = |list: &[&str]| action.iter().any(|w| list.contains(w));
+ if has(PAY_WORDS) || (has(MOVE_VERBS) && has(MONEY_NOUNS)) || (has(ORDER_VERBS) && has(ORDER_NOUNS)) {
+ return Some(format!("{name} looks like a payment"));
+ }
+ None
+}
+
+/// Composio runs other tools by slug (`COMPOSIO_MULTI_EXECUTE_TOOL {tools: [{tool_slug}]}`).
+fn collect_slugs(v: &Value, out: &mut Vec<String>, depth: usize) {
+ if depth > 6 {
+ return;
+ }
+ match v {
+ Value::Object(map) => {
+ for (k, v) in map {
+ if matches!(k.as_str(), "tool_slug" | "slug" | "action" | "action_name" | "tool" | "tool_name") {
+ if let Some(s) = v.as_str() {
+ out.push(s.to_string());
+ }
+ }
+ collect_slugs(v, out, depth + 1);
+ }
+ }
+ Value::Array(list) => list.iter().for_each(|v| collect_slugs(v, out, depth + 1)),
+ _ => {}
+ }
+}
+
+fn collect_strings(v: &Value, out: &mut Vec<String>, depth: usize) {
+ if depth > 6 || out.len() > 200 {
+ return;
+ }
+ match v {
+ Value::String(s) => out.push(s.clone()),
+ Value::Number(n) => out.push(n.to_string()),
+ Value::Object(map) => map.values().for_each(|v| collect_strings(v, out, depth + 1)),
+ Value::Array(list) => list.iter().for_each(|v| collect_strings(v, out, depth + 1)),
+ _ => {}
+ }
+}
+
+/// Lowercase words of a name: `STRIPE_CreatePaymentIntent` → stripe, create, payment, intent.
+fn words(name: &str) -> Vec<String> {
+ let mut out = Vec::new();
+ let mut cur = String::new();
+ let mut prev_lower = false;
+ for c in name.chars() {
+ if !c.is_alphanumeric() {
+ if !cur.is_empty() {
+ out.push(std::mem::take(&mut cur));
+ }
+ prev_lower = false;
+ continue;
+ }
+ if c.is_uppercase() && prev_lower && !cur.is_empty() {
+ out.push(std::mem::take(&mut cur));
+ }
+ prev_lower = c.is_lowercase() || c.is_ascii_digit();
+ cur.extend(c.to_lowercase());
+ }
+ if !cur.is_empty() {
+ out.push(cur);
+ }
+ out
+}
+
+/// A button or link label that pays: a pay word or phrase, or a price.
+pub fn pay_label(label: &str) -> Option<String> {
+ let lower = label.to_lowercase();
+ if lower.chars().count() > 120 {
+ // Long text is a description, not a label: only phrases count
+ return PAY_LABEL_PHRASES.iter().find(|p| has_phrase(&lower, p)).map(|p| format!("a \"{p}\" button"));
+ }
+ let ws = words(&lower);
+ if let Some(w) = ws.iter().find(|w| PAY_LABEL_WORDS.contains(&w.as_str())) {
+ return Some(format!("a \"{w}\" button"));
+ }
+ if let Some(p) = PAY_LABEL_PHRASES.iter().find(|p| has_phrase(&lower, p)) {
+ return Some(format!("a \"{p}\" button"));
+ }
+ has_price(&lower).then(|| "a button with a price on it".to_string())
+}
+
+fn has_phrase(text: &str, phrase: &str) -> bool {
+ let text = format!(" {} ", words(text).join(" "));
+ text.contains(&format!(" {phrase} "))
+}
+
+/// `$12.99`, `€5`, `12,99 €`, `USD 10`, `10 eur`.
+fn has_price(text: &str) -> bool {
+ const SYMBOLS: &[char] = &['$', '€', '£', '¥', '₹', '₩', '₽', '₺', '₴', '₦', '₱', '฿'];
+ const CODES: &[&str] = &["usd", "eur", "gbp", "jpy", "chf", "cad", "aud", "inr", "pln", "uah", "sek", "nok", "dkk"];
+ let chars: Vec<char> = text.chars().collect();
+ for (i, c) in chars.iter().enumerate() {
+ if SYMBOLS.contains(c) {
+ let after = chars.get(i + 1..).unwrap_or(&[]).iter().find(|c| !c.is_whitespace());
+ let before = chars.get(..i).unwrap_or(&[]).iter().rev().find(|c| !c.is_whitespace());
+ if after.is_some_and(|c| c.is_ascii_digit()) || before.is_some_and(|c| c.is_ascii_digit()) {
+ return true;
+ }
+ }
+ }
+ let ws = words(text);
+ ws.windows(2).any(|w| {
+ (CODES.contains(&w[0].as_str()) && w[1].starts_with(|c: char| c.is_ascii_digit()))
+ || (CODES.contains(&w[1].as_str()) && w[0].chars().all(|c| c.is_ascii_digit()))
+ })
+}
+
+/// 13–19 digits (spaces or dashes between groups allowed) that pass the Luhn check.
+pub fn card_number(text: &str) -> bool {
+ let mut run = String::new();
+ let check = |run: &str| (13..=19).contains(&run.len()) && luhn(run);
+ let mut last_sep = false;
+ for c in text.chars() {
+ if c.is_ascii_digit() {
+ run.push(c);
+ last_sep = false;
+ } else if (c == ' ' || c == '-') && !run.is_empty() && !last_sep {
+ last_sep = true;
+ } else {
+ if check(&run) {
+ return true;
+ }
+ run.clear();
+ last_sep = false;
+ }
+ }
+ check(&run)
+}
+
+fn luhn(digits: &str) -> bool {
+ let mut sum = 0;
+ for (i, c) in digits.chars().rev().enumerate() {
+ let mut d = c.to_digit(10).unwrap_or(0);
+ if i % 2 == 1 {
+ d *= 2;
+ if d > 9 {
+ d -= 9;
+ }
+ }
+ sum += d;
+ }
+ sum % 10 == 0 && digits.chars().any(|c| c != '0')
+}
+
+/// Whether `url` is a checkout page; returns its host and path for the card.
+pub fn checkout_page(url: &str) -> Option<String> {
+ let rest = url.split_once("://").map(|(_, r)| r).unwrap_or(url);
+ let (host, path) = rest.split_once('/').unwrap_or((rest, ""));
+ let host = host.rsplit('@').next().unwrap_or(host).split(':').next().unwrap_or(host).to_lowercase();
+ let path = path.split(['?', '#']).next().unwrap_or("").to_lowercase();
+ let shown = || format!("{host}/{path}").trim_end_matches('/').to_string();
+ if payment_host(&host) {
+ return Some(shown());
+ }
+ let first_label = host.split('.').next().unwrap_or("");
+ if CHECKOUT_SEGMENTS.contains(&first_label) {
+ return Some(shown());
+ }
+ path.split('/').any(|seg| CHECKOUT_SEGMENTS.contains(&seg) || seg.starts_with("checkout")).then(shown)
+}
+
+fn payment_host(host: &str) -> bool {
+ let host = host.trim_end_matches('.');
+ PAYMENT_HOSTS.iter().any(|h| host == *h || host.ends_with(&format!(".{h}")))
+}
+
+/// Programs that send crypto, with the subcommands that send.
+const WALLETS: &[(&str, &[&str])] = &[
+ ("cast", &["send", "publish"]),
+ ("bitcoin-cli", &["sendtoaddress", "sendmany", "send", "sendall", "sendrawtransaction", "walletcreatefundedpsbt"]),
+ ("solana", &["transfer", "pay"]),
+ ("spl-token", &["transfer"]),
+ ("electrum", &["payto", "paytomany", "broadcast"]),
+ ("lncli", &["sendpayment", "payinvoice", "sendcoins", "sendmany", "sendtoroute"]),
+ ("lightning-cli", &["pay", "withdraw", "keysend", "xpay"]),
+ ("monero-wallet-cli", &["transfer", "sweep_all"]),
+ ("cardano-cli", &["submit"]),
+ ("near", &["send", "send-near"]),
+ ("aptos", &["transfer"]),
+ ("sui", &["pay", "pay-sui", "pay-all-sui", "transfer-sui"]),
+];
+
+/// `stripe` CLI words that change something.
+const STRIPE_WRITES: &[&str] = &[
+ "post", "delete", "create", "update", "capture", "confirm", "pay", "refund", "void", "finalize", "send", "trigger",
+ "fixtures", "cancel", "approve",
+];
+
+/// A shell command that pays: a write to a payment API host, a `stripe` CLI write, or a crypto
+/// wallet send. Commands that hide the host or method (variables, scripts) aren't caught.
+pub fn shell_reason(command: &str) -> Option<String> {
+ let tokens: Vec<String> = command
+ .split(|c: char| c.is_whitespace())
+ .map(|t| t.trim_matches(|c| c == '\'' || c == '"' || c == '`' || c == '(' || c == ')').to_string())
+ .filter(|t| !t.is_empty())
+ .collect();
+ let lower = command.to_lowercase();
+ if let Some(host) = payment_host_in(&lower) {
+ if writes(&tokens, &lower) {
+ return Some(format!("a request that writes to {host}, a payment service"));
+ }
+ }
+ for segment in command.split([';', '&', '|', '\n', '(', ')', '`']) {
+ let words: Vec<&str> = segment
+ .split_whitespace()
+ .map(|w| w.trim_matches(|c| c == '\'' || c == '"'))
+ .skip_while(|w| (w.contains('=') && !w.starts_with('-')) || matches!(*w, "sudo" | "env" | "command" | "exec" | "nohup" | "time" | "npx" | "-E"))
+ .collect();
+ let Some((program, args)) = words.split_first() else { continue };
+ let program = program.rsplit('/').next().unwrap_or(program).to_lowercase();
+ if program == "stripe" && args.iter().any(|a| STRIPE_WRITES.contains(&a.to_lowercase().as_str())) {
+ return Some("a stripe CLI command that changes something".into());
+ }
+ if let Some((_, subs)) = WALLETS.iter().find(|(p, _)| *p == program) {
+ if args.iter().any(|a| subs.contains(&a.to_lowercase().as_str())) {
+ return Some(format!("a {program} command that sends crypto"));
+ }
+ }
+ }
+ None
+}
+
+/// The first payment host named in a command.
+fn payment_host_in(lower: &str) -> Option<&'static str> {
+ lower
+ .split(|c: char| !(c.is_ascii_alphanumeric() || c == '.' || c == '-'))
+ .filter(|t| t.contains('.'))
+ .find_map(|t| {
+ let t = t.trim_matches('.');
+ PAYMENT_HOSTS.iter().find(|h| t == **h || t.ends_with(&format!(".{h}"))).copied()
+ })
+}
+
+/// Whether a request in this command writes (anything but a plain GET).
+fn writes(tokens: &[String], lower: &str) -> bool {
+ let methods = ["post", "put", "patch", "delete"];
+ for (i, t) in tokens.iter().enumerate() {
+ let tl = t.to_lowercase();
+ if (tl == "-x" || tl == "--request" || tl == "--method")
+ && tokens.get(i + 1).is_some_and(|m| methods.contains(&m.to_lowercase().as_str()))
+ {
+ return true;
+ }
+ if let Some(m) = tl.strip_prefix("-x").or_else(|| tl.strip_prefix("--request=")).or_else(|| tl.strip_prefix("--method=")) {
+ if methods.contains(&m) {
+ return true;
+ }
+ }
+ // curl's data and form flags make it a POST; wget's post flags; httpie's method word
+ if (t.starts_with("-d") && !t.starts_with("--"))
+ || tl.starts_with("--data")
+ || tl.starts_with("--json")
+ || t == "-F"
+ || tl.starts_with("--form")
+ || tl.starts_with("--post-")
+ || tl.starts_with("--body")
+ || ["POST", "PUT", "PATCH", "DELETE"].contains(&t.as_str())
+ {
+ return true;
+ }
+ }
+ // Code that posts (python requests, fetch with a method, …)
+ [".post(", ".put(", ".patch(", ".delete(", "method: 'post'", "method:'post'", "method: \"post\"", "method=\"post\"", "method='post'"]
+ .iter()
+ .any(|p| lower.contains(p))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn mcp(server: &str, tool: &str, args: Value) -> Option<String> {
+ mcp_reason(server, tool, &args)
+ }
+
+ #[test]
+ fn money_app_writes_and_money_names_pay() {
+ assert!(mcp("stripe", "create_payment_intent", json!({})).is_some());
+ assert!(mcp("stripe", "create_customer", json!({})).is_some(), "every write of a money-only app");
+ assert!(mcp("stripe", "list_charges", json!({})).is_none(), "reads don't pay");
+ assert!(mcp("stripe", "retrieve_balance", json!({})).is_none());
+ assert!(mcp("shop", "purchase_item", json!({})).is_some());
+ assert!(mcp("shop", "placeOrder", json!({})).is_some());
+ assert!(mcp("bank", "send_money", json!({})).is_some());
+ assert!(mcp("wallet", "transfer_funds", json!({})).is_some());
+ assert!(mcp("billing", "pay_invoice", json!({})).is_some());
+ assert!(mcp("gmail", "send_email", json!({})).is_none());
+ assert!(mcp("drive", "transfer_ownership", json!({})).is_none());
+ assert!(mcp("github", "create_issue", json!({})).is_none());
+ assert!(mcp("shop", "get_order", json!({})).is_none());
+ }
+
+ #[test]
+ fn composio_slugs_are_read_from_the_arguments() {
+ let multi = |slug: &str| json!({"tools": [{"tool_slug": "GMAIL_FETCH_EMAILS", "arguments": {}}, {"tool_slug": slug, "arguments": {"amount": 100}}]});
+ assert!(mcp("composio", "COMPOSIO_MULTI_EXECUTE_TOOL", multi("STRIPE_CREATE_PAYMENT_INTENT")).is_some());
+ assert!(mcp("composio", "COMPOSIO_MULTI_EXECUTE_TOOL", multi("PAYPAL_CREATE_ORDER")).is_some());
+ assert!(mcp("composio", "COMPOSIO_MULTI_EXECUTE_TOOL", multi("SQUARE_CREATE_PAYMENT")).is_some());
+ assert!(mcp("composio", "COMPOSIO_MULTI_EXECUTE_TOOL", multi("GMAIL_SEND_EMAIL")).is_none());
+ assert!(mcp("composio", "COMPOSIO_MULTI_EXECUTE_TOOL", multi("STRIPE_LIST_CHARGES")).is_none());
+ assert!(mcp("composio", "STRIPE_CREATE_REFUND", json!({})).is_some());
+ assert!(name_reason("", "mcp__stripe__create_charge").is_some());
+ }
+
+ #[test]
+ fn browser_mcp_tools_pay_by_label_or_card_number() {
+ assert!(mcp("playwright", "browser_click", json!({"element": "Place order button", "ref": "e12"})).is_some());
+ assert!(mcp("playwright", "browser_click", json!({"element": "Continue", "ref": "e3"})).is_none());
+ assert!(mcp("playwright", "browser_type", json!({"ref": "e5", "text": "4242 4242 4242 4242"})).is_some());
+ assert!(mcp("playwright", "browser_type", json!({"ref": "e5", "text": "hello"})).is_none());
+ // A long id elsewhere isn't a card number to type
+ assert!(mcp("discord", "get_message", json!({"id": "4242424242424242"})).is_none());
+ }
+
+ #[test]
+ fn kwnt_browser_act() {
+ let act = |a: Value, url: Option<&str>| self_reason("browser_act", &a, url);
+ for label in ["Pay now", "Place order", "Buy", "Subscribe", "Upgrade to Pro", "Complete purchase", "Pay €12,99", "Donate", "Check out"] {
+ assert!(act(json!({"action": "click_text", "text": label}), Some("https://example.com/")).is_some(), "{label}");
+ }
+ assert!(act(json!({"action": "click_text", "text": "Add to cart – $12.99"}), None).is_some(), "a price");
+ for label in ["Continue", "Next", "Sign in", "Payload docs", "Display", "Repay"] {
+ assert!(act(json!({"action": "click_text", "text": label}), Some("https://example.com/docs")).is_none(), "{label}");
+ }
+ // Any click or Enter on a checkout page
+ assert!(act(json!({"action": "click_text", "text": "Continue"}), Some("https://shop.example.com/checkout/step-2")).is_some());
+ assert!(act(json!({"action": "click_text", "text": "Next"}), Some("https://checkout.stripe.com/c/pay/cs_test")).is_some());
+ assert!(act(json!({"action": "key", "key": "Enter"}), Some("https://www.paypal.com/checkoutnow?token=x")).is_some());
+ assert!(act(json!({"action": "key", "key": "Tab"}), Some("https://shop.example.com/checkout")).is_none());
+ assert!(act(json!({"action": "key", "key": "Enter"}), Some("https://example.com/search")).is_none());
+ assert!(act(json!({"action": "scroll"}), Some("https://shop.example.com/checkout")).is_none());
+ // Typing a card number anywhere
+ assert!(act(json!({"action": "type", "text": "4111-1111-1111-1111"}), None).is_some());
+ assert!(act(json!({"action": "type", "text": "4111 1111 1111 1112"}), None).is_none(), "fails Luhn");
+ assert!(act(json!({"action": "type", "text": "+44 20 7946 0958"}), None).is_none());
+ assert!(self_reason("browser_open", &json!({"url": "https://checkout.stripe.com/x"}), None).is_none());
+ assert!(self_reason("memory_add", &json!({"text": "pay now"}), None).is_none());
+ }
+
+ #[test]
+ fn shell_commands() {
+ let pays = [
+ "curl -X POST https://api.stripe.com/v1/charges -u sk_test_x: -d amount=100",
+ "curl https://api.stripe.com/v1/payment_intents -d amount=2000 -d currency=usd",
+ "curl --request PATCH 'https://api-m.paypal.com/v2/checkout/orders/1'",
+ "curl -sS --json '{\"amount\":1}' https://api.wise.com/v1/transfers",
+ "wget --post-data='a=1' https://connect.squareup.com/v2/payments",
+ "http POST https://api.coinbase.com/v2/accounts/x/transactions to=abc amount=1",
+ "python3 -c \"import requests; requests.post('https://api.stripe.com/v1/charges', data={})\"",
+ "stripe charges create --amount 100 --currency usd",
+ "stripe post /v1/refunds -d charge=ch_1",
+ "cd x && sudo bitcoin-cli sendtoaddress bc1q 0.1",
+ "cast send 0xabc --value 1ether",
+ "solana transfer ABC 1",
+ ];
+ for c in pays {
+ assert!(shell_reason(c).is_some(), "{c}");
+ }
+ let free = [
+ "curl https://api.stripe.com/v1/balance -u sk_test_x:",
+ "curl -s https://stripe.com/docs/api",
+ "stripe charges list --limit 3",
+ "stripe get /v1/charges",
+ "stripe login",
+ "curl -X POST https://api.github.com/repos/x/issues -d '{}'",
+ "touch x",
+ "bitcoin-cli getbalance",
+ "cast call 0xabc 'balanceOf(address)'",
+ "git push",
+ ];
+ for c in free {
+ assert!(shell_reason(c).is_none(), "{c}");
+ }
+ }
+
+ #[test]
+ fn card_numbers_and_prices() {
+ assert!(card_number("4242424242424242"));
+ assert!(card_number("card: 5555 5555 5555 4444, exp 12/30"));
+ assert!(card_number("378282246310005"), "amex, 15 digits");
+ assert!(!card_number("4242424242424241"));
+ assert!(!card_number("123456789012"), "too short");
+ assert!(!card_number("0000000000000000"));
+ assert!(has_price("pay $5"));
+ assert!(has_price("12,99 €"));
+ assert!(has_price("usd 10"));
+ assert!(!has_price("version 2.1"));
+ }
+
+ #[test]
+ fn checkout_pages() {
+ assert!(checkout_page("https://shop.example.com/checkout").is_some());
+ assert!(checkout_page("https://www.amazon.com/gp/buy/spc/handlers/display.html").is_some());
+ assert!(checkout_page("https://pay.example.com/").is_some());
+ assert!(checkout_page("https://buy.stripe.com/test_123").is_some());
+ assert!(checkout_page("https://example.com/account/billing").is_some());
+ assert!(checkout_page("https://example.com/blog/checkout-tips?x=1").is_some(), "a checkout* segment, accepted noise");
+ assert!(checkout_page("https://example.com/docs/payments-overview").is_none());
+ assert!(checkout_page("https://news.example.com/").is_none());
+ assert!(checkout_page("https://example.com/?next=/checkout").is_none());
+ }
+}
diff --git a/src/mcp/session.rs b/src/mcp/session.rs
index e4a95fb8..87863508 100644
--- a/src/mcp/session.rs
+++ b/src/mcp/session.rs
@@ -250,6 +250,7 @@ impl McpToolSession {
arguments: arguments.clone(),
builtin: None,
smart: Some(read_only_verdict(t.tool.read_only)),
+ payment: None,
})
.await;
if !outcome.allowed() {
diff --git a/src/server/computer.rs b/src/server/computer.rs
index 5ce625ba..21f402ab 100644
--- a/src/server/computer.rs
+++ b/src/server/computer.rs
@@ -196,8 +196,13 @@ pub async fn approve_local_shell_in(
if let Some(v) = &verdict {
details["smart_reason"] = json!(v.reason());
}
+ // The payment floor (D8): a command that pays always asks, and "always allow" covers it once
+ let payment = crate::mcp::payment_floor::shell_reason(command);
+ if let Some(why) = &payment {
+ details["payment_reason"] = json!(why);
+ }
// "Always this session" under smart: per bot and conversation, like claude's tools
- let remembered = conversation.filter(|_| mode == SMART);
+ let remembered = conversation.filter(|_| mode == SMART && payment.is_none());
if crate::sandbox::credentials::call_touches_kwnt_secrets(&details["arguments"], Some(cwd)) {
tracing::warn!(target = %target_id, "refused a shell command that names kwnt's secret files");
let record = NewApproval {
@@ -216,7 +221,7 @@ pub async fn approve_local_shell_in(
return true;
}
}
- if mode == OFF || verdict.as_ref().is_some_and(|v| v.is_allowed()) {
+ if payment.is_none() && (mode == OFF || verdict.as_ref().is_some_and(|v| v.is_allowed())) {
if verdict.is_some() {
tracing::info!(target = %target_id, "ran a local command without a card: not risky");
}
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 143d4d5e..e0e04b3b 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -336,6 +336,9 @@ pub fn self_server(base_url: &str, token: &str) -> McpServer {
pub struct SelfToolsApprover {
pub inner: Arc<dyn ToolApprover>,
pub always_ask: bool,
+ /// The turn's own browser (state, sandbox target): the payment floor reads the page's real
+ /// address from it before a `browser_act`.
+ pub browser: Option<(AppState, String)>,
}
/// The agents' own tools that only read: free even in an always-ask turn.
@@ -364,7 +367,19 @@ impl ToolApprover for SelfToolsApprover {
self.decide(req).await.allowed()
}
- async fn decide(&self, req: ToolApprovalRequest) -> crate::mcp::ApprovalOutcome {
+ async fn decide(&self, mut req: ToolApprovalRequest) -> crate::mcp::ApprovalOutcome {
+ // The payment floor (D8): a click or key on a checkout page, a pay-type button or a typed
+ // card number gets a card in every mode. The address comes from the browser, not the bot.
+ if req.server == SELF_SERVER_NAME && req.tool == BROWSER_ACT {
+ let url = match &self.browser {
+ Some((state, target)) => page_url(state, target).await,
+ None => None,
+ };
+ if let Some(why) = crate::mcp::payment_floor::reason(&req, url.as_deref()) {
+ req.payment = Some(why);
+ return self.inner.decide(req).await;
+ }
+ }
if req.server == SELF_SERVER_NAME && (!self.always_ask || READ_ONLY_SELF_TOOLS.contains(&req.tool.as_str())) {
self.inner.note(&req, "allowed", None).await;
return crate::mcp::ApprovalOutcome::Allowed;
@@ -377,6 +392,13 @@ impl ToolApprover for SelfToolsApprover {
}
}
+/// The address the turn's browser shows now, without starting a browser.
+async fn page_url(state: &AppState, target: &str) -> Option<String> {
+ let ctrl = state.browser_controllers.lock().await.get(target).cloned()?;
+ let url = ctrl.current_url.lock().await.clone();
+ url
+}
+
fn tool_list(scope: &SelfScope, board: bool) -> Value {
let mut tools = memory_tools();
if let Some(list) = tools.as_array_mut() {
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index 59f32aea..0f76657b 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -180,7 +180,10 @@ impl BrokerApprover {
// Approvals the person switched off: run, and keep a record of what ran. A setting that
// can't be read asks, as before.
let mode = self.db.kwant_approvals(&req.kwant_id).await.ok();
- let off = !self.always_ask && mode.as_ref().is_some_and(|m| m.is_off());
+ // The payment floor (D8): a call that pays always gets a card, whatever the approvals,
+ // "Ask only when risky" or "always allow" say. Allowing it covers this one call.
+ let payment = req.payment.clone().or_else(|| mcp::payment_floor::reason(&req, None));
+ let off = payment.is_none() && !self.always_ask && mode.as_ref().is_some_and(|m| m.is_off());
// "Ask only when risky": what the caller made of this call; nothing known asks. A turn that
// always asks (it read outside text) still lets claude's plain read tools through.
let smart = mode
@@ -188,7 +191,8 @@ impl BrokerApprover {
.is_some_and(|m| m.is_smart())
.then(|| req.smart.clone())
.flatten()
- .filter(|_| !self.always_ask || (req.builtin.is_some() && matches!(req.tool.as_str(), "Read" | "Glob" | "Grep")));
+ .filter(|_| !self.always_ask || (req.builtin.is_some() && matches!(req.tool.as_str(), "Read" | "Glob" | "Grep")))
+ .filter(|_| payment.is_none());
let mut details = match &req.builtin {
Some(b) => json!({
"source": "claude_builtin",
@@ -211,6 +215,9 @@ impl BrokerApprover {
if let Some(verdict) = &smart {
details["smart_reason"] = json!(verdict.reason());
}
+ if let Some(why) = &payment {
+ details["payment_reason"] = json!(why);
+ }
let record = NewApproval {
turn_id: req.turn_id.clone(),
kwant_id: req.kwant_id.clone(),
@@ -234,7 +241,9 @@ impl BrokerApprover {
}
return (ApprovalOutcome::Allowed, "auto_allowed", None);
}
- if !off && !self.always_ask && self.broker.is_allowed_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await {
+ if payment.is_some() {
+ tracing::info!(kwant = %req.kwant_id, tool = %req.tool_name, reason = ?payment, "a payment: asking whatever the approvals say");
+ } else if !off && !self.always_ask && self.broker.is_allowed_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await {
return (ApprovalOutcome::Allowed, "allowed", None);
}
if off {
@@ -292,6 +301,8 @@ impl BrokerApprover {
super::activity::approval_settled(&req.turn_id, &ticket, settled);
let outcome = match decision {
Ok(Ok(ApprovalDecision::AllowOnce)) => ApprovalOutcome::Allowed,
+ // A payment's "always allow" covers this one call: nothing is remembered
+ Ok(Ok(ApprovalDecision::AlwaysAllowSession)) if payment.is_some() => ApprovalOutcome::Allowed,
Ok(Ok(ApprovalDecision::AlwaysAllowSession)) => {
self.broker.allow_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await;
ApprovalOutcome::Allowed
@@ -377,7 +388,8 @@ pub async fn resume_late_approval(state: &AppState, ticket_id: &str, decision: A
let channel_id = chat["channel_id"].as_str().map(str::to_string);
let conversation = thread_id.clone().or_else(|| channel_id.clone()).or_else(|| chat["direct_kwant_id"].as_str().map(str::to_string)).unwrap_or_else(|| kwant.id.clone());
state.broker.grant_once(&kwant.id, &conversation, &approval.tool_name, &arguments).await;
- if decision == ApprovalDecision::AlwaysAllowSession {
+ // A payment's "always allow" covers the one call (the payment floor, D8)
+ if decision == ApprovalDecision::AlwaysAllowSession && details.get("payment_reason").is_none() {
state.broker.allow_for_session(&kwant.id, &conversation, &approval.tool_name).await;
}
let depth = match &thread_id {
@@ -483,6 +495,7 @@ pub async fn prepare_turn_with_opts(
// Signed-in http servers get their (refreshed) access token as a secret header
super::mcp_oauth::authorize_servers(state, &mut servers).await;
let token = uuid::Uuid::new_v4().simple().to_string();
+ let browser = self_scope.as_ref().and_then(|s| s.sandbox_target.clone()).map(|t| (state.clone(), t));
let self_tools = self_scope.is_some() && !servers.iter().any(|s| s.name.eq_ignore_ascii_case(mcp::SELF_SERVER_NAME));
if self_tools {
servers.push(super::continuity::self_server(&local_base_url(state), &token));
@@ -508,7 +521,7 @@ pub async fn prepare_turn_with_opts(
let ctx = McpTurnContext {
servers,
approver: if self_tools {
- Arc::new(super::continuity::SelfToolsApprover { inner: broker_approver, always_ask: opts.always_ask })
+ Arc::new(super::continuity::SelfToolsApprover { inner: broker_approver, always_ask: opts.always_ask, browser })
} else {
broker_approver
},
@@ -555,6 +568,7 @@ fn noted_request(session: &PermissionSession, tool_name: &str, server: &str, too
arguments: input.clone(),
builtin,
smart: None,
+ payment: None,
}
}
@@ -632,6 +646,7 @@ async fn decide(session: &PermissionSession, args: &Value, smart: bool) -> Value
arguments: input.clone(),
builtin,
smart: verdict,
+ payment: None,
});
// Dropping the approval withdraws its card when the turn ends first
let outcome = tokio::select! {
diff --git a/src/server/missions/checkpoints.rs b/src/server/missions/checkpoints.rs
index 62e6d6b7..c9719090 100644
--- a/src/server/missions/checkpoints.rs
+++ b/src/server/missions/checkpoints.rs
@@ -1167,6 +1167,7 @@ mod tests {
arguments: args,
builtin: server.is_empty().then(|| crate::mcp::BuiltinCall { cwd: Some(cwd.into()), outside_folder: false }),
smart: None,
+ payment: None,
}
}
diff --git a/tests/approvals_off_test.rs b/tests/approvals_off_test.rs
index 584131e1..f86240b4 100644
--- a/tests/approvals_off_test.rs
+++ b/tests/approvals_off_test.rs
@@ -280,6 +280,7 @@ async fn an_always_ask_turn_asks_even_with_approvals_off() {
arguments: json!({"command": "touch y"}),
builtin: None,
smart: None,
+ payment: None,
};
put(&e, &format!("/api/kwants/{}/approvals", e.bot.id), "ask").await;
assert_eq!(approver.decide(req).await, want, "always_ask {always_ask}");
diff --git a/tests/continuity_test.rs b/tests/continuity_test.rs
index d8989f5e..20f449dc 100644
--- a/tests/continuity_test.rs
+++ b/tests/continuity_test.rs
@@ -604,6 +604,7 @@ async fn memory_search_finds_a_note_cut_from_the_prompt() {
let approver = continuity::SelfToolsApprover {
inner: std::sync::Arc::new(kwnt::mcp::FixedApprover(false)),
always_ask: true,
+ browser: None,
};
let req = |tool: &str| ToolApprovalRequest {
kwant_id: k1.id.clone(),
@@ -615,6 +616,7 @@ async fn memory_search_finds_a_note_cut_from_the_prompt() {
arguments: json!({}),
builtin: None,
smart: None,
+ payment: None,
};
assert!(kwnt::mcp::ToolApprover::approve(&approver, req("memory_search")).await);
assert!(!kwnt::mcp::ToolApprover::approve(&approver, req("memory_add")).await);
@@ -944,6 +946,7 @@ async fn self_tools_are_scoped_to_the_turn_and_kwant() {
arguments: json!({}),
builtin: None,
smart: None,
+ payment: None,
};
assert!(
ctx.approver.approve(approve(SELF_SERVER_NAME)).await,
diff --git a/tests/late_approval_test.rs b/tests/late_approval_test.rs
index 13525b15..85e6c8b5 100644
--- a/tests/late_approval_test.rs
+++ b/tests/late_approval_test.rs
@@ -35,6 +35,7 @@ fn request(env: &Env, args: Value) -> ToolApprovalRequest {
arguments: args,
builtin: None,
smart: None,
+ payment: None,
}
}
diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rs
index bd77eb2f..dc54b15b 100644
--- a/tests/mcp_runtime_test.rs
+++ b/tests/mcp_runtime_test.rs
@@ -78,6 +78,7 @@ fn request(tool: &str) -> ToolApprovalRequest {
arguments: json!({"text": "hi"}),
builtin: None,
smart: None,
+ payment: None,
}
}
diff --git a/tests/mission_checkpoints_test.rs b/tests/mission_checkpoints_test.rs
index f0fcfdec..03a83053 100644
--- a/tests/mission_checkpoints_test.rs
+++ b/tests/mission_checkpoints_test.rs
@@ -773,6 +773,7 @@ async fn write_as(e: &Env, bot: &Kwant, turn_id: &str, dir: &Path, rel: &str, bo
arguments: json!({"file_path": rel, "content": body}),
builtin: Some(kwnt::mcp::BuiltinCall { cwd: Some(dir.to_string_lossy().into_owned()), outside_folder: false }),
smart: None,
+ payment: None,
};
kwnt::server::missions::checkpoints::log_call(&e.state.db, &e.state.config.data_dir, &req, "allowed", None).await;
}
diff --git a/tests/payment_floor_test.rs b/tests/payment_floor_test.rs
new file mode 100644
index 00000000..6d79388d
--- /dev/null
+++ b/tests/payment_floor_test.rs
@@ -0,0 +1,327 @@
+//! The payment floor (Phase C D8): with approvals off everything runs without a card except a
+//! payment, which asks in every approval mode, even when "Ask only when risky" says it's safe or
+//! the person said "always allow". Allowing a payment covers that one call.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use chrono::Utc;
+use kwnt::{
+ broker::{ApprovalDecision, PermissionBroker},
+ config::Config,
+ db::{models::Kwant, spaces::SpaceId, Database},
+ drivers::events::RuntimeEvent,
+ mcp::{payment_floor, ApprovalOutcome, SmartVerdict, ToolApprovalRequest, ToolApprover, SELF_SERVER_NAME},
+ router::LayaRouter,
+ server::{
+ continuity::{SelfScope, SelfToolsApprover, TurnOrigin},
+ create_router, mcp_runtime,
+ turns::ActiveTurn,
+ AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::{sync::Arc, time::Duration};
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+const STRIPE_POST: &str = "curl -X POST https://api.stripe.com/v1/charges -u sk_test_x: -d amount=100 -d currency=usd";
+
+struct Env {
+ app: Router,
+ 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();
+ 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 { app: create_router(state.clone()), bot, general, state, _tmp: tmp }
+}
+
+async fn call(app: &Router, method: &str, uri: &str, auth: Option<&str>, body: Option<Value>) -> (StatusCode, Value) {
+ let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ if let Some(token) = auth {
+ req = req.header("authorization", format!("Bearer {token}"));
+ }
+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+async fn set_approvals(e: &Env, mode: &str) {
+ let uri = format!("/api/kwants/{}/approvals", e.bot.id);
+ let (s, v) = call(&e.app, "PUT", &uri, Some(e.state.api_token.reveal()), Some(json!({"approvals": mode}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+}
+
+/// A live turn of the bot in #general with its own tools; returns (turn id, token).
+async fn turn(e: &Env) -> (String, String, TempDir) {
+ let turn_id = uuid::Uuid::new_v4().to_string();
+ let folder = tempdir().unwrap();
+ let scope = SelfScope {
+ kwant_id: e.bot.id.clone(),
+ kwant_name: e.bot.name.clone(),
+ origin: Some(TurnOrigin { channel_id: Some(e.general.clone()), ..Default::default() }),
+ turn_id: Some(turn_id.clone()),
+ ..Default::default()
+ };
+ let (_, token) = mcp_runtime::prepare_turn_with_opts(
+ &e.state,
+ &e.bot,
+ Some(turn_id.clone()),
+ Some(folder.path().to_path_buf()),
+ Some(scope),
+ Default::default(),
+ )
+ .await
+ .unwrap();
+ e.state.turns.set_turn(ActiveTurn {
+ turn_id: turn_id.clone(),
+ kwant_id: e.bot.id.clone(),
+ context_id: e.general.clone(),
+ thread_id: None,
+ state: "running".into(),
+ since: Utc::now(),
+ purpose: None,
+ });
+ (turn_id, token, folder)
+}
+
+/// What claude's permission prompt gets for `tool {input}`: `Ok(behavior)` when kwnt answers
+/// without a card, `Err((card details, behavior after the card got `answer`))` when it shows one.
+async fn claude_asks(e: &Env, tool: &str, input: Value, answer: ApprovalDecision) -> Result<String, (Value, String)> {
+ let (turn_id, token, _folder) = turn(e).await;
+ let mut events = e.state.event_sender.subscribe();
+ let ask = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "approve",
+ "arguments": {"tool_name": tool, "input": input, "tool_use_id": "tu_1"}}});
+ let app = e.app.clone();
+ let path = format!("/api/mcp/permission/{token}");
+ let mut prompt = tokio::spawn(async move { call(&app, "POST", &path, None, Some(ask)).await });
+ let behavior = |v: &Value| {
+ let text = v["result"]["content"][0]["text"].as_str().unwrap();
+ serde_json::from_str::<Value>(text).unwrap()["behavior"].as_str().unwrap().to_string()
+ };
+ let answered = tokio::time::timeout(Duration::from_millis(1500), &mut prompt).await;
+ let card = loop {
+ match events.try_recv() {
+ Ok(RuntimeEvent::ApprovalRequired { id, details, .. }) => break Some((id, details)),
+ Ok(_) => continue,
+ Err(_) => break None,
+ }
+ };
+ let out = match (answered, card) {
+ (Ok(done), None) => Ok(behavior(&done.unwrap().1)),
+ (Err(_), Some((id, details))) => {
+ assert!(e.state.broker.resolve(&id, answer).await);
+ let (_, v) = prompt.await.unwrap();
+ Err((details, behavior(&v)))
+ }
+ (answered, card) => panic!("answered {} with card {card:?}", answered.is_ok()),
+ };
+ mcp_runtime::finish_turn(&e.state, &token).await;
+ e.state.turns.end_turn(&turn_id);
+ out
+}
+
+fn approver(e: &Env, timeout: Duration) -> mcp_runtime::BrokerApprover {
+ mcp_runtime::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: e.general.clone(),
+ chat: None,
+ always_ask: false,
+ }
+}
+
+fn request(e: &Env, server: &str, tool: &str, arguments: Value) -> ToolApprovalRequest {
+ ToolApprovalRequest {
+ kwant_id: e.bot.id.clone(),
+ kwant_name: e.bot.name.clone(),
+ turn_id: "t-pay".into(),
+ tool_name: if server.is_empty() { tool.to_string() } else { format!("mcp__{server}__{tool}") },
+ server: server.into(),
+ tool: tool.into(),
+ arguments,
+ builtin: None,
+ smart: None,
+ payment: None,
+ }
+}
+
+fn bash(e: &Env, command: &str) -> ToolApprovalRequest {
+ let mut req = request(e, "", "Bash", json!({"command": command}));
+ req.builtin = Some(kwnt::mcp::BuiltinCall { cwd: None, outside_folder: false });
+ req
+}
+
+#[tokio::test]
+async fn with_approvals_off_only_the_payment_gets_a_card_and_a_denial_stops_it() {
+ let e = setup().await;
+ set_approvals(&e, "off").await;
+
+ // Everything else runs without asking: a send, a delete, a GET to the payment API, a POST elsewhere
+ for command in [
+ "touch x",
+ "rm -rf build",
+ "curl https://api.stripe.com/v1/balance -u sk_test_x:",
+ "curl -X POST https://api.github.com/repos/o/r/issues -d '{}'",
+ ] {
+ let got = claude_asks(&e, "Bash", json!({"command": command}), ApprovalDecision::Deny).await;
+ assert_eq!(got, Ok("allow".to_string()), "{command}");
+ }
+
+ // The payment asks, and the person's Deny stops it
+ let Err((details, behavior)) = claude_asks(&e, "Bash", json!({"command": STRIPE_POST}), ApprovalDecision::Deny).await else {
+ panic!("a payment must show a card with approvals off");
+ };
+ assert_eq!(behavior, "deny");
+ assert!(details["payment_reason"].as_str().unwrap().contains("stripe.com"), "{details}");
+ let (_, rows) = call(&e.app, "GET", "/api/approvals", None, None).await;
+ let row = rows.as_array().unwrap().iter().find(|r| r["details"]["payment_reason"].is_string()).expect("the card is on record");
+ assert!(row["details"]["arguments"]["command"].as_str().unwrap().starts_with("curl -X POST"), "{row}");
+ assert_ne!(row["status"], "auto_allowed", "{row}");
+
+ // Allowing it lets it run
+ let got = claude_asks(&e, "Bash", json!({"command": STRIPE_POST}), ApprovalDecision::AllowOnce).await;
+ assert!(matches!(got, Err((_, ref b)) if b == "allow"), "{got:?}");
+}
+
+#[tokio::test]
+async fn smart_allow_and_always_allow_never_skip_a_payment() {
+ let e = setup().await;
+ let a = approver(&e, Duration::from_millis(200));
+
+ // "Ask only when risky" says it's safe: still a card
+ set_approvals(&e, "smart").await;
+ let mut req = bash(&e, STRIPE_POST);
+ req.smart = Some(SmartVerdict::Allow("looked safe".into()));
+ assert_eq!(a.decide(req).await, ApprovalOutcome::Unanswered);
+ let mut req = bash(&e, "touch x");
+ req.smart = Some(SmartVerdict::Allow("inside the folder".into()));
+ assert_eq!(a.decide(req).await, ApprovalOutcome::Allowed, "non-payments keep the smart shortcut");
+
+ // "Always allow" for Bash in this conversation: still a card, in ask and in off
+ e.state.broker.allow_for_session(&e.bot.id, &e.general, "Bash").await;
+ for mode in ["ask", "off"] {
+ set_approvals(&e, mode).await;
+ assert_eq!(a.decide(bash(&e, STRIPE_POST)).await, ApprovalOutcome::Unanswered, "{mode}");
+ assert_eq!(a.decide(bash(&e, "touch x")).await, ApprovalOutcome::Allowed, "{mode}");
+ }
+}
+
+#[tokio::test]
+async fn always_allow_on_a_payment_card_covers_that_one_call() {
+ let e = setup().await;
+ set_approvals(&e, "ask").await;
+ let mut events = e.state.event_sender.subscribe();
+ let a = Arc::new(approver(&e, Duration::from_secs(5)));
+ let pending = {
+ let (a, req) = (a.clone(), bash(&e, STRIPE_POST));
+ tokio::spawn(async move { a.decide(req).await })
+ };
+ let id = loop {
+ if let RuntimeEvent::ApprovalRequired { id, .. } = events.recv().await.unwrap() {
+ break id;
+ }
+ };
+ assert!(e.state.broker.resolve(&id, ApprovalDecision::AlwaysAllowSession).await);
+ assert_eq!(pending.await.unwrap(), ApprovalOutcome::Allowed);
+ assert!(!e.state.broker.is_allowed_for_session(&e.bot.id, &e.general, "Bash").await, "nothing is remembered");
+ let a = approver(&e, Duration::from_millis(200));
+ assert_eq!(a.decide(bash(&e, STRIPE_POST)).await, ApprovalOutcome::Unanswered, "the next payment asks again");
+}
+
+#[tokio::test]
+async fn a_payment_app_through_composio_asks_with_approvals_off() {
+ let e = setup().await;
+ set_approvals(&e, "off").await;
+ let a = approver(&e, Duration::from_millis(200));
+ let multi = |slug: &str| {
+ request(&e, "composio", "COMPOSIO_MULTI_EXECUTE_TOOL", json!({"tools": [{"tool_slug": slug, "arguments": {"amount": 500}}]}))
+ };
+ assert_eq!(a.decide(multi("STRIPE_CREATE_PAYMENT_INTENT")).await, ApprovalOutcome::Unanswered);
+ assert_eq!(a.decide(request(&e, "paypal", "create_order", json!({}))).await, ApprovalOutcome::Unanswered);
+ assert_eq!(a.decide(request(&e, "shop", "place_order", json!({}))).await, ApprovalOutcome::Unanswered);
+ // Sending, deleting and publishing run without asking
+ assert_eq!(a.decide(multi("GMAIL_SEND_EMAIL")).await, ApprovalOutcome::Allowed);
+ assert_eq!(a.decide(multi("GOOGLEDRIVE_DELETE_FILE")).await, ApprovalOutcome::Allowed);
+ assert_eq!(a.decide(request(&e, "wordpress", "publish_post", json!({}))).await, ApprovalOutcome::Allowed);
+ assert_eq!(a.decide(multi("STRIPE_LIST_CHARGES")).await, ApprovalOutcome::Allowed, "reads don't pay");
+
+ let (_, rows) = call(&e.app, "GET", "/api/approvals?status=waiting", None, None).await;
+ let reasons: Vec<&str> = rows.as_array().unwrap().iter().filter_map(|r| r["details"]["payment_reason"].as_str()).collect();
+ assert_eq!(reasons.len(), 3, "{rows}");
+}
+
+#[tokio::test]
+async fn kwnt_browser_pay_clicks_and_card_numbers_ask_with_approvals_off() {
+ let e = setup().await;
+ set_approvals(&e, "off").await;
+ let a = SelfToolsApprover { inner: Arc::new(approver(&e, Duration::from_millis(200))), always_ask: false, browser: None };
+ let act = |args: Value| request(&e, SELF_SERVER_NAME, "browser_act", args);
+ assert_eq!(a.decide(act(json!({"action": "click_text", "text": "Place order"}))).await, ApprovalOutcome::Unanswered);
+ assert_eq!(a.decide(act(json!({"action": "click_text", "text": "Pay $12.99"}))).await, ApprovalOutcome::Unanswered);
+ assert_eq!(a.decide(act(json!({"action": "type", "text": "4242 4242 4242 4242"}))).await, ApprovalOutcome::Unanswered);
+ assert_eq!(a.decide(act(json!({"action": "click_text", "text": "Continue"}))).await, ApprovalOutcome::Allowed);
+ assert_eq!(a.decide(act(json!({"action": "type", "text": "hello"}))).await, ApprovalOutcome::Allowed);
+ assert_eq!(a.decide(request(&e, SELF_SERVER_NAME, "memory_add", json!({"text": "pay now"}))).await, ApprovalOutcome::Allowed);
+}
+
+#[tokio::test]
+async fn a_local_shell_payment_waits_for_the_person_with_approvals_off() {
+ let e = setup().await;
+ set_approvals(&e, "off").await;
+ let folder = tempdir().unwrap();
+ let ran = tokio::time::timeout(
+ Duration::from_secs(3),
+ kwnt::server::computer::approve_local_shell(&e.state, &e.bot.id, "touch x", folder.path()),
+ )
+ .await
+ .expect("no card");
+ assert!(ran);
+ let waiting = tokio::time::timeout(
+ Duration::from_millis(300),
+ kwnt::server::computer::approve_local_shell(&e.state, &e.bot.id, STRIPE_POST, folder.path()),
+ )
+ .await;
+ assert!(waiting.is_err(), "a payment waits for the person");
+}
+
+/// kwnt's own tools don't pay. A new one whose name looks like paying must be classified in
+/// payment_floor.rs before it ships.
+#[tokio::test]
+async fn self_tools_have_no_money_words() {
+ let e = setup().await;
+ e.state.db.set_setting("mission_board", "true").await.unwrap();
+ let (turn_id, token, _f) = turn(&e).await;
+ let (_, v) = call(&e.app, "POST", "/api/mcp/self", Some(&token), Some(json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}))).await;
+ let names: Vec<&str> = v["result"]["tools"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap()).collect();
+ assert!(names.len() > 20, "{names:?}");
+ for name in names {
+ assert_eq!(payment_floor::name_reason("", name), None, "{name} looks like a payment: classify it in payment_floor.rs");
+ }
+ mcp_runtime::finish_turn(&e.state, &token).await;
+ e.state.turns.end_turn(&turn_id);
+}