Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Approvals switch: the person can turn every approval off, per space or per bot
Lin (kwant bot)13fc3173d87f
diff --git a/src/db/approval_modes.rs b/src/db/approval_modes.rsnew file mode 100644index 00000000..e66ac5f0--- /dev/null+++ b/src/db/approval_modes.rs@@ -0,0 +1,149 @@+//! Whether bots ask before their tools run. The person sets it for a space (`ask` or `off`) and+//! may override it per bot (`ask` or `off`; no row inherits the space). Bots never change it.+//! Kept in its own table, outside exports, so an imported bundle can't switch approvals off.++use super::{spaces::SpaceId, Database, DbError};+use chrono::Utc;++/// The default for a space with no row, and for a bot with no override.+pub const ASK: &str = "ask";+pub const OFF: &str = "off";++/// A bot's setting as the person chose it: `inherit` follows its space.+pub const INHERIT: &str = "inherit";++/// What `approvals` resolves to for one bot.+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub struct ApprovalMode {+ /// The space's value: `ask` or `off`.+ pub space: String,+ /// The bot's own choice: `inherit`, `ask` or `off`.+ pub bot: String,+ /// The bot's override, else the space's: `ask` or `off`.+ pub effective: String,+}++impl ApprovalMode {+ pub fn is_off(&self) -> bool {+ self.effective == OFF+ }+}++/// `ask` or `off`; anything else is not a mode.+pub fn valid_mode(mode: &str) -> bool {+ matches!(mode, ASK | OFF)+}++impl Database {+ pub(super) async fn migrate_approval_modes(&self) -> Result<(), DbError> {+ sqlx::query(+ "CREATE TABLE IF NOT EXISTS approval_modes (+ scope TEXT NOT NULL CHECK (scope IN ('space', 'kwant')),+ id TEXT NOT NULL,+ mode TEXT NOT NULL CHECK (mode IN ('ask', 'off')),+ updated_at TIMESTAMP NOT NULL,+ PRIMARY KEY (scope, id)+ )",+ )+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ async fn approval_mode_row(&self, scope: &str, id: &str) -> Result<Option<String>, DbError> {+ let row: Option<(String,)> = sqlx::query_as("SELECT mode FROM approval_modes WHERE scope = ? AND id = ?")+ .bind(scope)+ .bind(id)+ .fetch_optional(&self.pool)+ .await?;+ Ok(row.map(|r| r.0))+ }++ /// The space's approvals: `ask` (the default) or `off`.+ pub async fn space_approvals(&self, space: &SpaceId) -> Result<String, DbError> {+ Ok(self.approval_mode_row("space", space.as_str()).await?.unwrap_or_else(|| ASK.into()))+ }++ pub async fn set_space_approvals(&self, space: &SpaceId, mode: &str) -> Result<(), DbError> {+ sqlx::query(+ "INSERT INTO approval_modes (scope, id, mode, updated_at) VALUES ('space', ?, ?, ?)+ ON CONFLICT(scope, id) DO UPDATE SET mode = excluded.mode, updated_at = excluded.updated_at",+ )+ .bind(space.as_str())+ .bind(mode)+ .bind(Utc::now())+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// Sets a bot's override; `inherit` removes it.+ pub async fn set_kwant_approvals(&self, kwant_id: &str, mode: &str) -> Result<(), DbError> {+ if mode == INHERIT {+ sqlx::query("DELETE FROM approval_modes WHERE scope = 'kwant' AND id = ?").bind(kwant_id).execute(&self.pool).await?;+ return Ok(());+ }+ sqlx::query(+ "INSERT INTO approval_modes (scope, id, mode, updated_at) VALUES ('kwant', ?, ?, ?)+ ON CONFLICT(scope, id) DO UPDATE SET mode = excluded.mode, updated_at = excluded.updated_at",+ )+ .bind(kwant_id)+ .bind(mode)+ .bind(Utc::now())+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// A bot's approvals in `space`: its override, else the space's.+ pub async fn kwant_approvals_in(&self, space: &SpaceId, kwant_id: &str) -> Result<ApprovalMode, DbError> {+ let space_mode = self.space_approvals(space).await?;+ let bot = self.approval_mode_row("kwant", kwant_id).await?;+ let effective = bot.clone().unwrap_or_else(|| space_mode.clone());+ Ok(ApprovalMode { space: space_mode, bot: bot.unwrap_or_else(|| INHERIT.into()), effective })+ }++ /// A bot's approvals, in the space it lives in. An unknown bot asks.+ pub async fn kwant_approvals(&self, kwant_id: &str) -> Result<ApprovalMode, DbError> {+ match self.space_of_kwant(kwant_id).await? {+ Some(space) => self.kwant_approvals_in(&space, kwant_id).await,+ None => Ok(ApprovalMode { space: ASK.into(), bot: INHERIT.into(), effective: ASK.into() }),+ }+ }++ /// The approvals rows of a space's bots, newest first (max 200), optionally of one status+ /// (`auto_allowed` lists what ran while approvals were off) or one bot.+ pub async fn list_approvals(+ &self,+ space: &SpaceId,+ status: Option<&str>,+ kwant_id: Option<&str>,+ ) -> Result<Vec<super::models::Approval>, DbError> {+ Ok(sqlx::query_as::<_, super::models::Approval>(+ "SELECT a.* FROM approvals a JOIN kwants k ON k.id = a.kwant_id+ WHERE k.space_id = ?1 AND (?2 IS NULL OR a.status = ?2) AND (?3 IS NULL OR a.kwant_id = ?3)+ ORDER BY a.created_at DESC, a.rowid DESC LIMIT 200",+ )+ .bind(space.as_str())+ .bind(status)+ .bind(kwant_id)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Records a call that ran without a card because approvals were off.+ pub async fn save_auto_allowed(&self, input: &super::models::NewApproval) -> Result<String, DbError> {+ let id = uuid::Uuid::new_v4().to_string();+ sqlx::query(+ "INSERT INTO approvals (id, turn_id, kwant_id, tool_name, parameters, status) VALUES (?, ?, ?, ?, ?, 'auto_allowed')",+ )+ .bind(&id)+ .bind(&input.turn_id)+ .bind(&input.kwant_id)+ .bind(&input.tool_name)+ .bind(serde_json::to_string(&input.parameters)?)+ .execute(&self.pool)+ .await?;+ Ok(id)+ }+}diff --git a/src/db/bot_actions.rs b/src/db/bot_actions.rsindex 3c4b82d7..f9768836 100644--- a/src/db/bot_actions.rs+++ b/src/db/bot_actions.rs@@ -337,6 +337,7 @@ impl Database {"DELETE FROM threads WHERE kwant_id = ?1","DELETE FROM questions WHERE kwant_id = ?1 OR direct_kwant_id = ?1","DELETE FROM approvals WHERE kwant_id = ?1",+ "DELETE FROM approval_modes WHERE scope = 'kwant' AND id = ?1","DELETE FROM skills WHERE kwant_id = ?1","DELETE FROM mcp_suggestions WHERE kwant_id = ?1 OR direct_kwant_id = ?1","DELETE FROM hire_proposals WHERE kwant_id = ?1 OR direct_kwant_id = ?1",diff --git a/src/db/mod.rs b/src/db/mod.rsindex 53f76ddf..6ed14b8a 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -13,6 +13,7 @@ pub mod mcp_suggestions;pub mod bot_actions;pub mod hires;pub mod imports;+pub mod approval_modes;/// What a space's #general says about itself.pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";@@ -144,6 +145,7 @@ impl Database {db.migrate_bot_actions().await?;db.migrate_hires().await?;db.migrate_imports().await?;+ db.migrate_approval_modes().await?;}db.pool.close().await;diff --git a/src/server/approval_modes.rs b/src/server/approval_modes.rsnew file mode 100644index 00000000..0732a23e--- /dev/null+++ b/src/server/approval_modes.rs@@ -0,0 +1,182 @@+//! The person's approvals switch: `ask` (an approval card before a bot's tool runs) or `off`+//! (it runs, and is recorded as `auto_allowed`). Set per space, with a per-bot override. Only+//! the person changes it: a request carrying a bot's turn token is refused, and bots' own tools+//! refuse an `approvals` field.++use super::{+ spaces::{active_space, Scope},+ AppState,+};+use crate::db::{+ approval_modes::{valid_mode, ApprovalMode, INHERIT},+ spaces::SpaceId,+};+use axum::{+ extract::{Path, Query, State},+ http::{HeaderMap, StatusCode},+ response::{IntoResponse, Response},+ Json,+};+use serde::Deserialize;+use serde_json::{json, Value};++fn error(status: StatusCode, message: &str) -> Response {+ (status, Json(json!({"error": message}))).into_response()+}++fn internal() -> Response {+ StatusCode::INTERNAL_SERVER_ERROR.into_response()+}++const REFUSAL: &str = "only the person changes approvals";++#[derive(Deserialize)]+pub struct ModeBody {+ pub approvals: String,+}++/// A bot's setting as the API shows it, next to its other fields.+pub fn mode_json(m: &ApprovalMode) -> Value {+ json!({"approvals": m.bot, "approvals_effective": m.effective})+}++#[allow(clippy::result_large_err)]+async fn space_json(state: &AppState, space: &SpaceId) -> Result<Value, Response> {+ let mode = state.db.space_approvals(space).await.map_err(|_| internal())?;+ let kwants = state.db.list_kwants(space).await.map_err(|_| internal())?;+ let mut bots = Vec::with_capacity(kwants.len());+ for k in kwants {+ let m = state.db.kwant_approvals_in(space, &k.id).await.map_err(|_| internal())?;+ let mut item = mode_json(&m);+ item["kwant_id"] = json!(k.id);+ bots.push(item);+ }+ Ok(json!({"space_id": space.as_str(), "approvals": mode, "bots": bots}))+}++/// `GET /api/spaces/:id/approvals`: `{space_id, approvals: "ask"|"off", bots: [{kwant_id,+/// approvals: "inherit"|"ask"|"off", approvals_effective: "ask"|"off"}]}`.+pub async fn get_space(State(state): State<AppState>, Path(id): Path<String>) -> Response {+ let space = SpaceId::new(&id);+ match state.db.get_space(&space).await {+ Ok(Some(_)) => {}+ Ok(None) => return error(StatusCode::NOT_FOUND, "no such space"),+ Err(_) => return internal(),+ }+ match space_json(&state, &space).await {+ Ok(v) => Json(v).into_response(),+ Err(r) => r,+ }+}++/// `PUT /api/spaces/:id/approvals {approvals: "ask"|"off"}`: the person only.+pub async fn put_space(+ State(state): State<AppState>,+ headers: HeaderMap,+ Path(id): Path<String>,+ Json(body): Json<ModeBody>,+) -> Response {+ if let Err(r) = super::mcp_suggest::refuse_agent_tokens(&state, &headers, REFUSAL).await {+ return r;+ }+ let space = match active_space(&state, &id).await {+ Ok(s) => s,+ Err(r) => return r,+ };+ let mode = body.approvals.trim();+ if !valid_mode(mode) {+ return error(StatusCode::BAD_REQUEST, "approvals must be \"ask\" or \"off\"");+ }+ if state.db.set_space_approvals(&space, mode).await.is_err() {+ return internal();+ }+ tracing::info!(space = %space, approvals = mode, "the person set the space's approvals");+ match space_json(&state, &space).await {+ Ok(v) => Json(v).into_response(),+ Err(r) => r,+ }+}++#[allow(clippy::result_large_err)]+async fn kwant_json(state: &AppState, id: &str) -> Result<Value, Response> {+ let Some(space) = state.db.space_of_kwant(id).await.map_err(|_| internal())? else {+ return Err(error(StatusCode::NOT_FOUND, "no such bot"));+ };+ let m = state.db.kwant_approvals_in(&space, id).await.map_err(|_| internal())?;+ let mut v = mode_json(&m);+ v["kwant_id"] = json!(id);+ v["space_approvals"] = json!(m.space);+ Ok(v)+}++/// `GET /api/kwants/:id/approvals`: `{kwant_id, approvals: "inherit"|"ask"|"off",+/// approvals_effective, space_approvals}`.+pub async fn get_kwant(State(state): State<AppState>, Path(id): Path<String>) -> Response {+ match kwant_json(&state, &id).await {+ Ok(v) => Json(v).into_response(),+ Err(r) => r,+ }+}++/// `PUT /api/kwants/:id/approvals {approvals: "inherit"|"ask"|"off"}`: the person only.+pub async fn put_kwant(+ State(state): State<AppState>,+ headers: HeaderMap,+ Path(id): Path<String>,+ Json(body): Json<ModeBody>,+) -> Response {+ if let Err(r) = super::mcp_suggest::refuse_agent_tokens(&state, &headers, REFUSAL).await {+ return r;+ }+ let mode = body.approvals.trim();+ if !(valid_mode(mode) || mode == INHERIT) {+ return error(StatusCode::BAD_REQUEST, "approvals must be \"inherit\", \"ask\" or \"off\"");+ }+ match state.db.space_of_kwant(&id).await {+ Ok(Some(_)) => {}+ Ok(None) => return error(StatusCode::NOT_FOUND, "no such bot"),+ Err(_) => return internal(),+ }+ if state.db.set_kwant_approvals(&id, mode).await.is_err() {+ return internal();+ }+ tracing::info!(kwant = %id, approvals = mode, "the person set a bot's approvals");+ match kwant_json(&state, &id).await {+ Ok(v) => Json(v).into_response(),+ Err(r) => r,+ }+}++#[derive(Deserialize)]+pub struct ListQuery {+ pub status: Option<String>,+ pub kwant_id: Option<String>,+}++/// `GET /api/approvals?space=&status=&kwant_id=`: the space's approval records, newest first+/// (max 200). `status=auto_allowed` lists what ran while approvals were off. Arguments are+/// masked as in `/api/away`.+pub async fn list(State(state): State<AppState>, Scope(space): Scope, Query(q): Query<ListQuery>) -> Response {+ let status = q.status.filter(|s| !s.is_empty());+ let kwant = q.kwant_id.filter(|k| !k.is_empty());+ let rows = match state.db.list_approvals(&space, status.as_deref(), kwant.as_deref()).await {+ Ok(r) => r,+ Err(_) => return internal(),+ };+ let out: Vec<Value> = rows+ .into_iter()+ .map(|a| {+ let details = serde_json::from_str(&a.parameters).unwrap_or(Value::Null);+ json!({+ "id": a.id,+ "turn_id": a.turn_id,+ "kwant_id": a.kwant_id,+ "tool_name": a.tool_name,+ "status": a.status,+ "created_at": a.created_at,+ "details": super::away::masked_details(details),+ })+ })+ .collect();+ Json(out).into_response()+}diff --git a/src/server/away.rs b/src/server/away.rsindex edeb4342..c4eb29f2 100644--- a/src/server/away.rs+++ b/src/server/away.rs@@ -85,7 +85,7 @@ fn mask_words(text: &str) -> String {/// An approval's stored details in the live `approval_required` event's shape. The tool's/// `arguments` get the summary's masking (sensitive-named fields, credentials, key-like words),/// as the feed never carries secrets; the rest (source, tool, ids, cwd) is kwnt's own.-fn masked_details(details: Value) -> Value {+pub(super) fn masked_details(details: Value) -> Value {let mut details = details;if let Some(args) = details.get_mut("arguments") {*args = masked_arguments(args);diff --git a/src/server/bot_actions.rs b/src/server/bot_actions.rsindex a8e95f0b..28fc87c6 100644--- a/src/server/bot_actions.rs+++ b/src/server/bot_actions.rs@@ -272,6 +272,7 @@ const ENGINES: &str = "Engines and their sign-in are the person's. Ask them to sor App settings.";const AUTH: &str = "How people sign in to kwnt is the person's alone; ask them to change it on the computer kwnt runs on.";const APPROVALS: &str = "Approvals and questions are answered by the person, never by a bot: ask them to answer the card in the chat.";+const APPROVALS_MODE: &str = "Whether bots ask before their tools run is the person's choice alone: only they can change it, in the app.";const COMPUTER: &str = "Where bots browse and run commands is the person's choice: ask them in App settings → Computer for browsing and commands.";const AGENT_TOOLS: &str = "Refused: you can't switch bots' own tools on or off. Only the person can: tell them to open App settings \(the gear at the bottom of the space rail, or Space settings → App settings) and flip the \"Bots can use their own tools\" switch.";@@ -1098,7 +1099,7 @@ pub(super) async fn record_quiet(state: &AppState, new: &NewBotAction) -> Resultimpl Ctx<'_> {async fn bot_create(&self, args: &Value) -> ToolResult {- if let Some(r) = refuse_extra(args, &["mcp_env", "env", "headers", "api_key", "password", "token"]) {+ if let Some(r) = refuse_extra(args, &["mcp_env", "env", "headers", "api_key", "password", "token", "approvals"]) {return r;}let model = arg(args, "model").unwrap_or("auto").to_string();@@ -1133,7 +1134,7 @@ impl Ctx<'_> {}async fn bot_update(&self, args: &Value) -> ToolResult {- if let Some(r) = refuse_extra(args, &["mcp_env", "env", "headers", "api_key", "password", "token"]) {+ if let Some(r) = refuse_extra(args, &["mcp_env", "env", "headers", "api_key", "password", "token", "approvals"]) {return r;}let target = match self.bot(arg(args, "bot")).await {@@ -1347,6 +1348,9 @@ impl Ctx<'_> {if args.get("archived").is_some() {return fail("Use space_archive to ask the person to archive the space.");}+ if let Some(r) = refuse_extra(args, &["approvals"]) {+ return r;+ }let before = self.space_json(&self.space).await;let mut body = json!({});for k in ["name", "icon"] {@@ -1499,6 +1503,7 @@ fn refuse_extra(args: &Value, keys: &[&str]) -> Option<ToolResult> {let found = keys.iter().find(|k| args.get(**k).is_some())?;let why = match *found {"mcp_env" | "env" | "headers" => MCP,+ "approvals" => APPROVALS_MODE,_ => SECRETS,};Some(fail(format!("Nothing was changed: {found} is not something you can set. {why}")))diff --git a/src/server/computer.rs b/src/server/computer.rsindex 962fdaf9..9ca3de94 100644--- a/src/server/computer.rs+++ b/src/server/computer.rs@@ -149,6 +149,19 @@ pub async fn put_window(Ok(Json(view(&state).await))}+/// Whether the person switched approvals off for the bot or team a local command runs for: a+/// bot's own setting, else the space of the bot or team. Anything else (or an unreadable+/// setting) asks.+async fn local_shell_approvals_off(state: &AppState, target_id: &str) -> bool {+ if let Ok(Some(_)) = state.db.space_of_kwant(target_id).await {+ return state.db.kwant_approvals(target_id).await.is_ok_and(|m| m.is_off());+ }+ match state.db.space_of_team(target_id).await {+ Ok(Some(space)) => state.db.space_approvals(&space).await.is_ok_and(|m| m == crate::db::approval_modes::OFF),+ _ => false,+ }+}+/// Asks the person before a shell command runs on their own computer. Every command asks:/// "always allow" is honoured for this one command only, never remembered.pub async fn approve_local_shell(@@ -163,6 +176,18 @@ pub async fn approve_local_shell("arguments": {"command": command, "cwd": cwd.to_string_lossy()},"kwant_id": target_id,});+ if local_shell_approvals_off(state, target_id).await {+ let record = NewApproval {+ turn_id: String::new(),+ kwant_id: target_id.to_string(),+ tool_name: "execute_shell".into(),+ parameters: details,+ };+ if let Err(e) = state.db.save_auto_allowed(&record).await {+ tracing::warn!(error = %e, "could not record a command that ran with approvals off");+ }+ return true;+ }let ticket = match state.db.save_approval(&NewApproval {diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rsindex 3998feb0..4e8d37a4 100644--- a/src/server/mcp_runtime.rs+++ b/src/server/mcp_runtime.rs@@ -150,7 +150,10 @@ impl Drop for TicketGuard {#[async_trait]impl ToolApprover for BrokerApprover {async fn approve(&self, req: ToolApprovalRequest) -> bool {- if self.broker.is_allowed_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await {+ // Approvals the person switched off: run, and keep a record of what ran. A setting that+ // can't be read asks, as before.+ let off = self.db.kwant_approvals(&req.kwant_id).await.is_ok_and(|m| m.is_off());+ if !off && self.broker.is_allowed_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await {return true;}let details = match &req.builtin {@@ -172,14 +175,21 @@ impl ToolApprover for BrokerApprover {"kwant_name": req.kwant_name,}),};+ let record = NewApproval {+ turn_id: req.turn_id.clone(),+ kwant_id: req.kwant_id.clone(),+ tool_name: req.tool_name.clone(),+ parameters: details.clone(),+ };+ if off {+ if let Err(e) = self.db.save_auto_allowed(&record).await {+ tracing::warn!(error = %e, "could not record a call that ran with approvals off");+ }+ return true;+ }let ticket = match self.db- .save_approval(&NewApproval {- turn_id: req.turn_id.clone(),- kwant_id: req.kwant_id.clone(),- tool_name: req.tool_name.clone(),- parameters: details.clone(),- })+ .save_approval(&record).await{Ok(a) => a.id,diff --git a/src/server/mod.rs b/src/server/mod.rsindex f1ad6da3..a7f0bb4f 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -24,6 +24,7 @@ pub mod mcp_suggest;pub mod bot_actions;pub mod hires;pub mod import_routes;+pub mod approval_modes;use crate::broker::PermissionBroker;use crate::config::Config;@@ -171,7 +172,10 @@ pub fn create_router(state: AppState) -> Router {).route("/api/chat/send", post(routes::send_chat)).route("/api/chat/cancel", post(routes::cancel_chat))+ .route("/api/approvals", get(approval_modes::list)).route("/api/approvals/:id/resolve", post(routes::resolve_approval))+ .route("/api/spaces/:id/approvals", get(approval_modes::get_space).put(approval_modes::put_space))+ .route("/api/kwants/:id/approvals", get(approval_modes::get_kwant).put(approval_modes::put_kwant)).route("/api/settings", get(routes::get_settings).post(routes::save_settings)).route("/api/settings/computer", get(computer::get_computer).put(computer::put_computer)).route("/api/settings/computer/window", put(computer::put_window))diff --git a/src/server/routes.rs b/src/server/routes.rsindex bf29ffc8..61648dea 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -84,6 +84,13 @@ pub async fn list_kwants(let runs_on = super::profile_turn::runs_on(&state, &v.kwant).await;let mut item = serde_json::to_value(&v).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;item["runs_on"] = runs_on;+ let mode = state+ .db+ .kwant_approvals_in(&space, &v.kwant.id)+ .await+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;+ item["approvals"] = json!(mode.bot);+ item["approvals_effective"] = json!(mode.effective);out.push(item);}Ok(Json(out))diff --git a/src/server/spaces.rs b/src/server/spaces.rsindex 2c863e84..9ec1e0ea 100644--- a/src/server/spaces.rs+++ b/src/server/spaces.rs@@ -203,6 +203,7 @@ pub async fn view(state: &AppState, s: Space) -> Result<Value, DbError> {let ready = super::profile_turn::ready_accounts(state, &id).await;let unread = super::away::unread_total(state, &id).await?;let general = state.db.general_channel(&id).await?.map(|c| c.id);+ let approvals = state.db.space_approvals(&id).await?;Ok(json!({"id": s.id,"name": s.name,@@ -215,6 +216,7 @@ pub async fn view(state: &AppState, s: Space) -> Result<Value, DbError> {"general_channel_id": general,"counts": { "bots": bots, "ready_accounts": ready, "unread": unread },"paused_routines": paused,+ "approvals": approvals,}))}diff --git a/tests/approvals_off_test.rs b/tests/approvals_off_test.rsnew file mode 100644index 00000000..b4e0f3f2--- /dev/null+++ b/tests/approvals_off_test.rs@@ -0,0 +1,351 @@+//! The person's approvals switch: `ask` (the default) shows an approval card before a bot's tool+//! runs; `off` runs it and records it as `auto_allowed`. Set per space, overridden per bot, and+//! never changed by a bot.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use chrono::Utc;+use kwnt::{+ broker::{ApprovalDecision, PermissionBroker},+ config::Config,+ db::{+ models::{Kwant, NewKwant},+ spaces::SpaceId,+ Database,+ },+ drivers::events::RuntimeEvent,+ router::LayaRouter,+ server::{+ continuity::{SelfScope, TurnOrigin},+ create_router, mcp_runtime,+ turns::ActiveTurn,+ AppState,+ },+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::time::Duration;+use tempfile::{tempdir, TempDir};+use tower::ServiceExt;++struct Env {+ app: Router,+ state: AppState,+ bot: Kwant,+ other: 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 kwants = state.db.list_kwants(&space).await.unwrap();+ 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: kwants[0].clone(), other: kwants[1].clone(), 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 get(e: &Env, uri: &str) -> Value {+ let (s, v) = call(&e.app, "GET", uri, None, None).await;+ assert_eq!(s, StatusCode::OK, "{uri}: {v}");+ v+}++async fn put(e: &Env, uri: &str, approvals: &str) -> Value {+ let (s, v) = call(&e.app, "PUT", uri, None, Some(json!({"approvals": approvals}))).await;+ assert_eq!(s, StatusCode::OK, "{uri}: {v}");+ v+}++/// A live turn of `bot` in the general channel with its own tools; returns its token.+async fn turn(e: &Env, bot: &Kwant) -> (String, String, TempDir) {+ let turn_id = uuid::Uuid::new_v4().to_string();+ let folder = tempdir().unwrap();+ let scope = SelfScope {+ kwant_id: bot.id.clone(),+ kwant_name: 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_self(&e.state, bot, Some(turn_id.clone()), Some(folder.path().to_path_buf()), Some(scope))+ .await+ .unwrap();+ e.state.turns.set_turn(ActiveTurn {+ turn_id: turn_id.clone(),+ kwant_id: bot.id.clone(),+ context_id: e.general.clone(),+ thread_id: None,+ state: "running".into(),+ since: Utc::now(),+ });+ (turn_id, token, folder)+}++/// What claude's permission prompt gets back for `Bash {command}`: `Some(allowed)` when kwnt+/// answers without a card, `None` when it shows one (the card is then denied, to end the wait).+async fn ask_bash(e: &Env, bot: &Kwant, command: &str) -> Option<bool> {+ let (turn_id, token, _folder) = turn(e, bot).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": "Bash", "input": {"command": command}, "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 answered = tokio::time::timeout(Duration::from_millis(1500), &mut prompt).await;+ let carded = loop {+ match events.try_recv() {+ Ok(RuntimeEvent::ApprovalRequired { id, .. }) => break Some(id),+ Ok(_) => continue,+ Err(_) => break None,+ }+ };+ let outcome = match (answered, carded) {+ (Ok(done), None) => {+ let (status, v) = done.unwrap();+ assert_eq!(status, StatusCode::OK, "{v}");+ Some(v["result"]["content"][0]["text"].as_str().unwrap().contains(r#""behavior":"allow""#))+ }+ (Err(_), Some(id)) => {+ assert!(e.state.broker.resolve(&id, ApprovalDecision::Deny).await);+ prompt.await.unwrap();+ None+ }+ (answered, carded) => panic!("answered {} with card {carded:?}", answered.is_ok()),+ };+ mcp_runtime::finish_turn(&e.state, &token).await;+ e.state.turns.end_turn(&turn_id);+ outcome+}++async fn self_tool(e: &Env, token: &str, name: &str, args: Value) -> (String, bool) {+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}});+ let (status, v) = call(&e.app, "POST", "/api/mcp/self", Some(token), Some(rpc)).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ (+ v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string(),+ v["result"]["isError"].as_bool().unwrap_or(false),+ )+}++fn bot_in<'a>(list: &'a Value, id: &str) -> &'a Value {+ list.as_array().unwrap().iter().find(|b| b["id"] == id || b["kwant_id"] == id).expect("bot listed")+}++#[tokio::test]+async fn approvals_ask_by_default() {+ let e = setup().await;+ let space = get(&e, "/api/spaces/spc_default/approvals").await;+ assert_eq!(space["approvals"], "ask");+ assert_eq!(bot_in(&space["bots"], &e.bot.id)["approvals"], "inherit");+ assert_eq!(bot_in(&space["bots"], &e.bot.id)["approvals_effective"], "ask");+ assert_eq!(get(&e, "/api/spaces/spc_default").await["approvals"], "ask");+ let kwants = get(&e, "/api/kwants?space=spc_default").await;+ assert_eq!(bot_in(&kwants, &e.bot.id)["approvals"], "inherit");+ assert_eq!(bot_in(&kwants, &e.bot.id)["approvals_effective"], "ask");++ assert_eq!(ask_bash(&e, &e.bot, "touch x").await, None, "Bash asks by default");+ assert!(get(&e, "/api/approvals?status=auto_allowed").await.as_array().unwrap().is_empty());+}++#[tokio::test]+async fn space_off_runs_bash_without_a_card_and_records_it() {+ let e = setup().await;+ let v = put(&e, "/api/spaces/spc_default/approvals", "off").await;+ assert_eq!(v["approvals"], "off");+ assert_eq!(bot_in(&v["bots"], &e.bot.id)["approvals_effective"], "off");+ assert_eq!(get(&e, "/api/spaces").await[0]["approvals"], "off");+ assert_eq!(get(&e, &format!("/api/kwants/{}/approvals", e.bot.id)).await["approvals_effective"], "off");++ assert_eq!(ask_bash(&e, &e.bot, "touch x").await, Some(true));+ // A write outside the folder and an unknown tool run too: there is no floor+ let (turn_id, token, _f) = turn(&e, &e.bot).await;+ for (tool, input) in [("Write", json!({"file_path": "/etc/kwnt-test", "content": "x"})), ("SomeNewTool", json!({}))] {+ let ask = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "approve",+ "arguments": {"tool_name": tool, "input": input, "tool_use_id": "tu_2"}}});+ let (s, v) = tokio::time::timeout(+ Duration::from_secs(3),+ call(&e.app, "POST", &format!("/api/mcp/permission/{token}"), None, Some(ask)),+ )+ .await+ .expect("answered without a card");+ assert_eq!(s, StatusCode::OK);+ assert!(v["result"]["content"][0]["text"].as_str().unwrap().contains(r#""behavior":"allow""#), "{tool}: {v}");+ }+ mcp_runtime::finish_turn(&e.state, &token).await;+ e.state.turns.end_turn(&turn_id);++ // Nothing waits, and every call is on record+ let away = get(&e, "/api/away").await;+ assert!(away["waiting"].as_array().unwrap().iter().all(|i| i["kind"] != "approval"), "{away}");+ let ran = get(&e, "/api/approvals?space=spc_default&status=auto_allowed").await;+ let ran = ran.as_array().unwrap();+ assert_eq!(ran.len(), 3, "{ran:?}");+ let bash = ran.iter().find(|r| r["tool_name"] == "Bash").unwrap();+ assert_eq!(bash["status"], "auto_allowed");+ assert_eq!(bash["kwant_id"], e.bot.id);+ assert_eq!(bash["details"]["arguments"]["command"], "touch x");+ assert_eq!(bash["details"]["source"], "claude_builtin");+ let write = ran.iter().find(|r| r["tool_name"] == "Write").unwrap();+ assert_eq!(write["details"]["outside_folder"], true);++ // Back on: it asks again+ put(&e, "/api/spaces/spc_default/approvals", "ask").await;+ assert_eq!(ask_bash(&e, &e.bot, "touch y").await, None);+}++#[tokio::test]+async fn a_bot_override_beats_the_space_both_ways() {+ let e = setup().await;+ put(&e, "/api/spaces/spc_default/approvals", "off").await;+ let v = put(&e, &format!("/api/kwants/{}/approvals", e.bot.id), "ask").await;+ assert_eq!(v["approvals"], "ask");+ assert_eq!(v["approvals_effective"], "ask");+ assert_eq!(v["space_approvals"], "off");+ assert_eq!(ask_bash(&e, &e.bot, "touch x").await, None, "the bot's ask beats the space's off");+ assert_eq!(ask_bash(&e, &e.other, "touch x").await, Some(true), "other bots follow the space");++ put(&e, "/api/spaces/spc_default/approvals", "ask").await;+ put(&e, &format!("/api/kwants/{}/approvals", e.bot.id), "off").await;+ assert_eq!(ask_bash(&e, &e.bot, "touch x").await, Some(true), "the bot's off beats the space's ask");+ assert_eq!(ask_bash(&e, &e.other, "touch x").await, None);+ let kwants = get(&e, "/api/kwants").await;+ assert_eq!(bot_in(&kwants, &e.bot.id)["approvals"], "off");+ assert_eq!(bot_in(&kwants, &e.other.id)["approvals_effective"], "ask");++ let v = put(&e, &format!("/api/kwants/{}/approvals", e.bot.id), "inherit").await;+ assert_eq!(v["approvals"], "inherit");+ assert_eq!(v["approvals_effective"], "ask");+ assert_eq!(ask_bash(&e, &e.bot, "touch x").await, None);+}++#[tokio::test]+async fn only_the_person_changes_approvals() {+ let e = setup().await;+ let (turn_id, token, _f) = turn(&e, &e.bot).await;++ // The app API refuses a bot's turn token+ for uri in ["/api/spaces/spc_default/approvals".to_string(), format!("/api/kwants/{}/approvals", e.bot.id)] {+ let (s, v) = call(&e.app, "PUT", &uri, Some(&token), Some(json!({"approvals": "off"}))).await;+ assert_eq!(s, StatusCode::FORBIDDEN, "{uri}: {v}");+ }+ // The bot's own tools refuse it+ let (text, err) = self_tool(&e, &token, "settings_update", json!({"settings": {"approvals": "off"}})).await;+ assert!(err, "{text}");+ let (text, err) = self_tool(&e, &token, "bot_update", json!({"bot": e.bot.id, "approvals": "off"})).await;+ assert!(err && text.contains("approvals"), "{text}");+ let (text, err) = self_tool(&e, &token, "bot_create", json!({"name": "Free", "title": "t", "instructions": "i", "approvals": "off"})).await;+ assert!(err && text.contains("approvals"), "{text}");+ let (text, err) = self_tool(&e, &token, "space_update", json!({"name": "X", "approvals": "off"})).await;+ assert!(err && text.contains("approvals"), "{text}");+ mcp_runtime::finish_turn(&e.state, &token).await;+ e.state.turns.end_turn(&turn_id);++ assert_eq!(get(&e, "/api/spaces/spc_default/approvals").await["approvals"], "ask");+ assert_eq!(get(&e, &format!("/api/kwants/{}/approvals", e.bot.id)).await["approvals"], "inherit");+ assert_eq!(ask_bash(&e, &e.bot, "touch x").await, None);+}++#[tokio::test]+async fn bad_values_unknown_rows_and_other_spaces() {+ let e = setup().await;+ let (s, _) = call(&e.app, "PUT", "/api/spaces/spc_default/approvals", None, Some(json!({"approvals": "never"}))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+ let (s, _) = call(&e.app, "PUT", "/api/spaces/spc_default/approvals", None, Some(json!({"approvals": "inherit"}))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "a space has no inherit");+ let (s, _) = call(&e.app, "PUT", &format!("/api/kwants/{}/approvals", e.bot.id), None, Some(json!({"approvals": "maybe"}))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+ let (s, _) = call(&e.app, "PUT", "/api/kwants/nope/approvals", None, Some(json!({"approvals": "off"}))).await;+ assert_eq!(s, StatusCode::NOT_FOUND);+ let (s, _) = call(&e.app, "PUT", "/api/spaces/nope/approvals", None, Some(json!({"approvals": "off"}))).await;+ assert_eq!(s, StatusCode::NOT_FOUND);++ // Another space has its own switch, and its bots follow it+ let other = e+ .state+ .db+ .create_space(&kwnt::db::spaces::NewSpace { name: "Lab".into(), icon: "🧪".into(), color: None, this_machine_enabled: true })+ .await+ .unwrap();+ let lab = SpaceId::new(&other.id);+ let lab_bot = e+ .state+ .db+ .create_kwant(+ &lab,+ &NewKwant {+ name: "Labby".into(),+ title: "t".into(),+ persona_prompt: "p".into(),+ soul: String::new(),+ avatar_sprite: "architect".into(),+ driver_type: "api".into(),+ preferred_model: "auto".into(),+ },+ )+ .await+ .unwrap();+ put(&e, &format!("/api/spaces/{}/approvals", other.id), "off").await;+ assert_eq!(get(&e, "/api/spaces/spc_default/approvals").await["approvals"], "ask");+ assert_eq!(get(&e, &format!("/api/kwants/{}/approvals", lab_bot.id)).await["approvals_effective"], "off");+ assert_eq!(get(&e, &format!("/api/kwants/{}/approvals", e.bot.id)).await["approvals_effective"], "ask");+ // A bot named with the wrong space is not found there+ let (s, _) = call(&e.app, "PUT", &format!("/api/kwants/{}/approvals?space=spc_default", lab_bot.id), None, Some(json!({"approvals": "ask"}))).await;+ assert_eq!(s, StatusCode::NOT_FOUND);+ // The record list stays in its space+ assert_eq!(ask_bash(&e, &lab_bot, "touch x").await, Some(true));+ assert_eq!(get(&e, &format!("/api/approvals?space={}", other.id)).await.as_array().unwrap().len(), 1);+ assert!(get(&e, "/api/approvals?space=spc_default").await.as_array().unwrap().is_empty());+}++#[tokio::test]+async fn a_local_command_runs_without_a_card_when_off() {+ let e = setup().await;+ let folder = tempdir().unwrap();+ put(&e, &format!("/api/kwants/{}/approvals", e.bot.id), "off").await;+ 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 rows = get(&e, "/api/approvals?status=auto_allowed").await;+ assert_eq!(rows[0]["tool_name"], "execute_shell");+ assert_eq!(rows[0]["details"]["arguments"]["command"], "touch x");++ // Asking still waits for the card+ put(&e, &format!("/api/kwants/{}/approvals", e.bot.id), "inherit").await;+ let waiting = tokio::time::timeout(+ Duration::from_millis(300),+ kwnt::server::computer::approve_local_shell(&e.state, &e.bot.id, "touch y", folder.path()),+ )+ .await;+ assert!(waiting.is_err(), "it should wait for the person");+}diff --git a/tests/spaces_migration_test.rs b/tests/spaces_migration_test.rsindex 4b035c7b..6848d084 100644--- a/tests/spaces_migration_test.rs+++ b/tests/spaces_migration_test.rs@@ -66,7 +66,7 @@ async fn legacy(dir: &Path) -> SqlitePool {/// from the Custom API change), without `space_id`, as quoted text.async fn snapshot(pool: &SqlitePool) -> BTreeMap<String, Vec<String>> {let tables: Vec<(String,)> = sqlx::query_as(- "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT IN ('spaces', 'llm_profile_endpoints', 'mcp_suggestions', 'bot_actions', 'hire_proposals', 'hire_policies', 'imports') ORDER BY name",+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT IN ('spaces', 'llm_profile_endpoints', 'mcp_suggestions', 'bot_actions', 'hire_proposals', 'hire_policies', 'imports', 'approval_modes') ORDER BY name",).fetch_all(pool).await