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.

Loose ends owner: its turns ask before anything with side effects, even with approvals off

Lin (kwant bot)fcd7a35a947e
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 82c62b28..52630e73 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -236,10 +236,29 @@ pub fn self_server(base_url: &str, token: &str) -> McpServer {
}
/// Lets calls to the agents' own tools through without a card; everything else goes to `inner`.
+/// With `always_ask`, only the self tools that just read go through; the rest ask too.
pub struct SelfToolsApprover {
pub inner: Arc<dyn ToolApprover>,
+ pub always_ask: bool,
}
+/// The agents' own tools that only read: free even in an always-ask turn.
+const READ_ONLY_SELF_TOOLS: &[&str] = &[
+ "search_history",
+ "delegation_status",
+ "routine_list",
+ "bot_list",
+ "settings_get",
+ "space_get",
+ "space_list",
+ "channel_list",
+ "hire_status",
+ "list_attachments",
+ "read_attachment",
+ "mcp_search",
+ "skill_get",
+];
+
#[async_trait]
impl ToolApprover for SelfToolsApprover {
async fn approve(&self, req: ToolApprovalRequest) -> bool {
@@ -247,7 +266,7 @@ impl ToolApprover for SelfToolsApprover {
}
async fn decide(&self, req: ToolApprovalRequest) -> crate::mcp::ApprovalOutcome {
- if req.server == SELF_SERVER_NAME {
+ if req.server == SELF_SERVER_NAME && (!self.always_ask || READ_ONLY_SELF_TOOLS.contains(&req.tool.as_str())) {
return crate::mcp::ApprovalOutcome::Allowed;
}
self.inner.decide(req).await
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index 72171571..5fbb3f78 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -292,7 +292,7 @@ async fn run(state: AppState, job: super::turns::JobGuard, d: Delegation, lead:
opts.retried = retried;
opts.delegation_id = Some(d.id.clone());
let outcome = try_kwant_turn(&scope, &specialist, prompt, opts).await;
- let outcome = continue_once_if_capped(&scope, &specialist, outcome).await;
+ let outcome = continue_once_if_capped(&scope, &specialist, outcome, false).await;
let outcome = match outcome {
Err(_) if job.token.is_cancelled() => Err("stopped".to_string()),
other => other,
diff --git a/src/server/loose_ends_owner.rs b/src/server/loose_ends_owner.rs
index 3fd38bc8..18ae8235 100644
--- a/src/server/loose_ends_owner.rs
+++ b/src/server/loose_ends_owner.rs
@@ -240,10 +240,10 @@ async fn start(state: &AppState, space: &SpaceId, events: &[(Event, Vec<CaseRow>
let id = kwant.id.clone();
tokio::spawn(async move {
let _job = job;
- let mut opts = TurnOpts::default();
- opts.label = Some("Loose ends: prepare drafts and next steps".into());
+ // Nobody asked for this turn: anything that could change something asks, approvals off or not
+ let opts = TurnOpts::always_asking("Loose ends: prepare drafts and next steps");
let reply = try_kwant_turn(&scope, &kwant, text, opts).await;
- let _ = continue_once_if_capped(&scope, &kwant, reply).await;
+ let _ = continue_once_if_capped(&scope, &kwant, reply, true).await;
});
Some(id)
}
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index 5d6f4e7a..5b8c4eb4 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -125,6 +125,10 @@ pub struct BrokerApprover {
/// The chat a card left unanswered resumes in after a late Allow (see [`turn_chat`]);
/// `None` resumes in the bot's direct chat.
pub chat: Option<Value>,
+ /// Ask even when the bot's approvals are off, and don't use "always allow" answers: for
+ /// turns kwnt starts on its own that nobody asked for (the loose-ends owner). A call the
+ /// person allowed on a card (late Allow) still runs once.
+ pub always_ask: bool,
}
/// Withdraws the ticket if the waiting turn is cancelled (its future dropped) mid-wait.
@@ -159,7 +163,7 @@ impl ToolApprover for BrokerApprover {
async fn decide(&self, req: ToolApprovalRequest) -> ApprovalOutcome {
// 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());
+ let off = !self.always_ask && self.db.kwant_approvals(&req.kwant_id).await.is_ok_and(|m| m.is_off());
let details = match &req.builtin {
Some(b) => json!({
"source": "claude_builtin",
@@ -195,7 +199,7 @@ impl ToolApprover for BrokerApprover {
}
return ApprovalOutcome::Denied;
}
- if !off && self.broker.is_allowed_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await {
+ if !off && !self.always_ask && self.broker.is_allowed_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await {
return ApprovalOutcome::Allowed;
}
if off {
@@ -405,6 +409,9 @@ pub struct TurnApprovalOpts {
/// The turn's (agent, effort): a card it leaves unanswered resumes on the same ones after a
/// late Allow.
pub routed: Option<(String, String)>,
+ /// Every call that could change something asks, approvals off or not (see
+ /// [`BrokerApprover::always_ask`]).
+ pub always_ask: bool,
}
/// [`prepare_turn_with_self`] with [`TurnApprovalOpts`].
@@ -450,11 +457,12 @@ pub async fn prepare_turn_with_opts(
timeout: APPROVAL_TIMEOUT,
conversation: turn_conversation(state, &turn_id),
chat,
+ always_ask: opts.always_ask,
});
let ctx = McpTurnContext {
servers,
approver: if self_tools {
- Arc::new(super::continuity::SelfToolsApprover { inner: broker_approver })
+ Arc::new(super::continuity::SelfToolsApprover { inner: broker_approver, always_ask: opts.always_ask })
} else {
broker_approver
},
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 8920d645..90bedb29 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -821,7 +821,7 @@ pub(super) async fn run_routine_turn(
let job = state.turns.start_job([context_key.clone()]);
let scope = scope_for(state, kwant, channel_id, thread_id, &job, 0).await?;
let reply = try_kwant_turn(&scope, kwant, prompt.clone(), TurnOpts::default()).await;
- let reply = continue_once_if_capped(&scope, kwant, reply).await;
+ let reply = continue_once_if_capped(&scope, kwant, reply, false).await;
match reply {
Ok(text) => {
let reply_id = state
@@ -849,7 +849,13 @@ This is your one automatic continuation: pick up where you left off, finish the
/// For turns nobody is watching (routines, delegations): a turn that stopped at the model-call
/// cap gets one more turn to finish, never more. Returns both replies joined, so a delegation's
/// result has all of it. A turn that didn't hit the cap, or failed, is returned as it is.
-pub(super) async fn continue_once_if_capped(scope: &TurnScope, kwant: &Kwant, first: Result<String, String>) -> Result<String, String> {
+/// `always_ask` carries [`TurnOpts::always_ask`] over to the continuation.
+pub(super) async fn continue_once_if_capped(
+ scope: &TurnScope,
+ kwant: &Kwant,
+ first: Result<String, String>,
+ always_ask: bool,
+) -> Result<String, String> {
let Ok(text) = &first else {
return first;
};
@@ -857,7 +863,11 @@ pub(super) async fn continue_once_if_capped(scope: &TurnScope, kwant: &Kwant, fi
return first;
}
tracing::info!(kwant = %kwant.id, "turn hit the model-call cap: one automatic continuation");
- let opts = TurnOpts { label: Some("Automatic continuation (once): the last turn ran out of model calls".into()), ..Default::default() };
+ let opts = TurnOpts {
+ label: Some("Automatic continuation (once): the last turn ran out of model calls".into()),
+ always_ask,
+ ..Default::default()
+ };
match try_kwant_turn(scope, kwant, CONTINUE_PROMPT.to_string(), opts).await {
Ok(more) => Ok(format!("{}\n\n{more}", text.trim_end())),
Err(_) => first,
@@ -1248,6 +1258,9 @@ pub(super) struct TurnOpts {
/// (agent, effort) to run on instead of asking Laya: a turn resumed after a late Allow
/// keeps those of the turn that asked.
routed: Option<(String, String)>,
+ /// Every call that could change something asks the person, even with approvals off (an
+ /// owner turn kwnt starts on its own; see [`super::loose_ends_owner`]).
+ pub(super) always_ask: bool,
}
impl TurnOpts {
@@ -1256,6 +1269,12 @@ impl TurnOpts {
let routed = agent.zip(effort).map(|(a, e)| (a.to_string(), e.to_string()));
TurnOpts { routed, ..Default::default() }
}
+
+ /// Options for a turn nobody asked for, saved under `label`: every call that could change
+ /// something asks (see [`TurnOpts::always_ask`]).
+ pub(super) fn always_asking(label: &str) -> Self {
+ TurnOpts { label: Some(label.to_string()), always_ask: true, ..Default::default() }
+ }
}
/// Runs one kwant turn: picks model/effort, syncs the bot browser, streams the reply and saves it.
@@ -1649,6 +1668,7 @@ async fn run_kwant_turn_inner(
});
let card_opts = super::mcp_runtime::TurnApprovalOpts {
routed: Some((target_model.clone(), effort_level.clone())),
+ always_ask: opts.always_ask,
};
let mcp_turn = super::mcp_runtime::prepare_turn_with_opts(
state,
diff --git a/tests/approvals_off_test.rs b/tests/approvals_off_test.rs
index 10b40ea0..355f681a 100644
--- a/tests/approvals_off_test.rs
+++ b/tests/approvals_off_test.rs
@@ -26,6 +26,7 @@ use kwnt::{
},
tools::ToolRunner,
};
+use kwnt::mcp::{ApprovalOutcome, ToolApprovalRequest, ToolApprover};
use serde_json::{json, Value};
use std::time::Duration;
use tempfile::{tempdir, TempDir};
@@ -83,6 +84,11 @@ async fn put(e: &Env, uri: &str, approvals: &str) -> Value {
/// 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) {
+ turn_with(e, bot, false).await
+}
+
+/// [`turn`]; `always_ask` makes it a turn like the loose-ends owner's.
+async fn turn_with(e: &Env, bot: &Kwant, always_ask: bool) -> (String, String, TempDir) {
let turn_id = uuid::Uuid::new_v4().to_string();
let folder = tempdir().unwrap();
let scope = SelfScope {
@@ -92,8 +98,9 @@ async fn turn(e: &Env, bot: &Kwant) -> (String, String, TempDir) {
turn_id: Some(turn_id.clone()),
..Default::default()
};
+ let opts = mcp_runtime::TurnApprovalOpts { always_ask, ..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))
+ mcp_runtime::prepare_turn_with_opts(&e.state, bot, Some(turn_id.clone()), Some(folder.path().to_path_buf()), Some(scope), opts)
.await
.unwrap();
e.state.turns.set_turn(ActiveTurn {
@@ -110,10 +117,15 @@ async fn turn(e: &Env, bot: &Kwant) -> (String, String, TempDir) {
/// 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;
+ ask_tool(e, bot, "Bash", json!({"command": command}), false).await
+}
+
+/// [`ask_bash`] for any tool, in a turn that may be `always_ask`.
+async fn ask_tool(e: &Env, bot: &Kwant, tool: &str, input: Value, always_ask: bool) -> Option<bool> {
+ let (turn_id, token, _folder) = turn_with(e, bot, always_ask).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"}}});
+ "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 });
@@ -220,6 +232,55 @@ async fn space_off_runs_bash_without_a_card_and_records_it() {
assert_eq!(ask_bash(&e, &e.bot, "touch y").await, None);
}
+/// The loose-ends owner's turn (nobody asked for it) asks before anything that could change
+/// something, even with approvals off; tools that only read still run.
+#[tokio::test]
+async fn an_always_ask_turn_asks_even_with_approvals_off() {
+ let e = setup().await;
+ put(&e, "/api/spaces/spc_default/approvals", "off").await;
+ put(&e, &format!("/api/kwants/{}/approvals", e.bot.id), "off").await;
+ assert_eq!(ask_tool(&e, &e.bot, "Bash", json!({"command": "touch x"}), false).await, Some(true), "an ordinary turn runs it");
+
+ let self_tool = |name: &str| format!("mcp__{}__{name}", kwnt::mcp::SELF_SERVER_NAME);
+ for (tool, input) in [
+ ("Bash".to_string(), json!({"command": "touch x"})),
+ ("Write".to_string(), json!({"file_path": "/tmp/kwnt-owner-test", "content": "x"})),
+ (self_tool("routine_create"), json!({"name": "r", "instructions": "x", "schedule": {"type": "daily", "time": "09:00"}})),
+ (self_tool("delegate"), json!({"to": "Other", "task": "send it"})),
+ (self_tool("memory_add"), json!({"text": "x"})),
+ ] {
+ assert_eq!(ask_tool(&e, &e.bot, &tool, input, true).await, None, "{tool} must ask in an owner turn");
+ }
+ for tool in ["search_history", "routine_list", "delegation_status"] {
+ assert_eq!(ask_tool(&e, &e.bot, &self_tool(tool), json!({}), true).await, Some(true), "{tool} only reads");
+ }
+ // "Always allow" for the conversation doesn't carry into an owner turn either
+ e.state.broker.allow_for_session(&e.bot.id, &e.general, "Bash").await;
+ for (always_ask, want) in [(false, ApprovalOutcome::Allowed), (true, ApprovalOutcome::Unanswered)] {
+ let approver = mcp_runtime::BrokerApprover {
+ db: e.state.db.clone(),
+ broker: e.state.broker.clone(),
+ events: e.state.event_sender.clone(),
+ timeout: Duration::from_millis(200),
+ conversation: e.general.clone(),
+ chat: None,
+ always_ask,
+ };
+ let req = ToolApprovalRequest {
+ kwant_id: e.bot.id.clone(),
+ kwant_name: e.bot.name.clone(),
+ turn_id: "t-owner".into(),
+ tool_name: "Bash".into(),
+ server: String::new(),
+ tool: "Bash".into(),
+ arguments: json!({"command": "touch y"}),
+ builtin: None,
+ };
+ put(&e, &format!("/api/kwants/{}/approvals", e.bot.id), "ask").await;
+ assert_eq!(approver.decide(req).await, want, "always_ask {always_ask}");
+ }
+}
+
#[tokio::test]
async fn a_bot_override_beats_the_space_both_ways() {
let e = setup().await;
diff --git a/tests/late_approval_test.rs b/tests/late_approval_test.rs
index 436d1cfa..0f0270bb 100644
--- a/tests/late_approval_test.rs
+++ b/tests/late_approval_test.rs
@@ -19,6 +19,7 @@ fn approver(env: &Env, timeout: Duration) -> Arc<BrokerApprover> {
timeout,
conversation: env.a.clone(),
chat: Some(json!({"direct_kwant_id": env.a})),
+ always_ask: false,
})
}
@@ -96,6 +97,7 @@ async fn a_grant_runs_once_only_in_its_own_conversation() {
timeout: Duration::from_millis(200),
conversation: "some-other-thread".into(),
chat: Some(json!({"thread_id": "some-other-thread"})),
+ always_ask: false,
};
assert_eq!(elsewhere.decide(request(&env, args.clone())).await, ApprovalOutcome::Unanswered);
// Its own conversation can, once (a new description is fine), and only that call
diff --git a/tests/mcp_gateway_test.rs b/tests/mcp_gateway_test.rs
index af45a676..14e49d6b 100644
--- a/tests/mcp_gateway_test.rs
+++ b/tests/mcp_gateway_test.rs
@@ -183,6 +183,7 @@ async fn gateway_calls_wait_for_the_approval_card() {
timeout: Duration::from_secs(10),
conversation: "conv-test".into(),
chat: None,
+ always_ask: false,
});
register(&state, "card-tok", approver).await;
let mut events = state.event_sender.subscribe();
@@ -241,6 +242,7 @@ async fn ending_the_turn_cancels_a_call_waiting_for_its_card() {
timeout: Duration::from_secs(300),
conversation: "conv-test".into(),
chat: None,
+ always_ask: false,
});
let marker = format!("KWNT_TEST_MARK_{}", uuid::Uuid::new_v4().simple());
let mut server = echo_server();
diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rs
index 3f21e453..2052af00 100644
--- a/tests/mcp_runtime_test.rs
+++ b/tests/mcp_runtime_test.rs
@@ -107,6 +107,7 @@ fn approver(state: &AppState, timeout: Duration) -> Arc<BrokerApprover> {
timeout,
conversation: "conv-test".into(),
chat: None,
+ always_ask: false,
})
}