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.

Merge smart-approvals (80b7675)

Lin (kwant bot)15ce17cb7c08
diff --cc src/db/approval_modes.rs
index 5bb4573c,f654167d..c303ac2e
--- a/src/db/approval_modes.rs
+++ b/src/db/approval_modes.rs
@@@ -148,80 -166,6 +169,79 @@@ impl Database
.await?)
}
+ /// A card nobody answered before its turn's wait ran out: it stays open as `waiting`, with
+ /// the chat (`{"channel_id"|"thread_id"|"direct_kwant_id": …}`) a late Allow resumes in.
+ /// False when the ticket was no longer pending.
+ pub async fn park_approval(&self, id: &str, chat: &serde_json::Value) -> Result<bool, DbError> {
+ let done = sqlx::query("UPDATE approvals SET status = 'waiting', resume = ? WHERE id = ? AND status = 'pending'")
+ .bind(chat.to_string())
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(done.rows_affected() == 1)
+ }
+
+ /// Answers a `waiting` card once: sets `status` and returns the ticket with its chat. `None`
+ /// when it isn't waiting (answered, or never parked) or is older than [`WAITING_APPROVAL_HOURS`],
+ /// which is then marked `expired`. Two answers at once: only one gets the ticket.
+ pub async fn claim_waiting_approval(
+ &self,
+ id: &str,
+ status: &str,
+ ) -> Result<Option<(super::models::Approval, serde_json::Value)>, DbError> {
+ let window = format!("-{WAITING_APPROVAL_HOURS} hours");
+ sqlx::query("UPDATE approvals SET status = 'expired' WHERE id = ? AND status = 'waiting' AND created_at <= datetime('now', ?)")
+ .bind(id)
+ .bind(&window)
+ .execute(&self.pool)
+ .await?;
+ let done = sqlx::query("UPDATE approvals SET status = ? WHERE id = ? AND status = 'waiting'")
+ .bind(status)
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ if done.rows_affected() != 1 {
+ return Ok(None);
+ }
+ let resume: Option<(Option<String>,)> =
+ sqlx::query_as("SELECT resume FROM approvals WHERE id = ?").bind(id).fetch_optional(&self.pool).await?;
+ let chat = resume
+ .and_then(|r| r.0)
+ .and_then(|r| serde_json::from_str(&r).ok())
+ .unwrap_or(serde_json::Value::Null);
+ Ok(self.get_approval(id).await?.map(|a| (a, chat)))
+ }
+
+ /// Cards still `waiting` for a late answer (younger than [`WAITING_APPROVAL_HOURS`]), with
+ /// the chat each one resumes in, newest first.
+ pub async fn away_waiting_approvals(&self) -> Result<Vec<super::away::AwayRow>, DbError> {
+ let window = format!("-{WAITING_APPROVAL_HOURS} hours");
+ Ok(sqlx::query_as(
+ "SELECT 'approval' AS kind, a.id, a.kwant_id, k.name AS kwant_name, a.tool_name AS title, a.status,
+ a.parameters AS body, a.created_at AS at,
+ json_extract(a.resume, '$.thread_id') AS thread_id,
+ json_extract(a.resume, '$.channel_id') AS channel_id,
+ json_extract(a.resume, '$.direct_kwant_id') AS direct_kwant_id, NULL AS choices
+ FROM approvals a LEFT JOIN kwants k ON k.id = a.kwant_id
+ WHERE a.status = 'waiting' AND a.created_at > datetime('now', ?)
+ ORDER BY a.created_at DESC, a.rowid DESC",
+ )
+ .bind(window)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// Moves a card's `created_at` back `hours` (tests of the waiting window).
+ #[doc(hidden)]
+ pub async fn backdate_approval_for_test(&self, id: &str, hours: i64) -> Result<(), DbError> {
+ sqlx::query("UPDATE approvals SET created_at = datetime('now', ?) WHERE id = ?")
+ .bind(format!("-{hours} hours"))
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
- /// Records a call that ran without a card because approvals were off.
/// Records a call kwnt refused on its own (it named kwnt's secret files), as `denied`.
pub async fn save_refused(&self, input: &super::models::NewApproval) -> Result<String, DbError> {
let id = uuid::Uuid::new_v4().to_string();
diff --cc src/drivers/cli.rs
index 991647df,ea2b7468..f0a4740b
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@@ -1243,87 -1101,9 +1250,87 @@@ mod tests
use super::*;
use crate::db::models::{Kwant, Message};
+ fn kinds(events: &[RuntimeEvent]) -> Vec<String> {
+ events
+ .iter()
+ .map(|e| match e {
+ RuntimeEvent::ToolCallPending { id, name, .. } => format!("start {id} {name}"),
+ RuntimeEvent::ToolCallCompleted { id, result } => format!("end {id} {}", result["status"].as_str().unwrap_or("")),
+ RuntimeEvent::Progress => "progress".into(),
+ other => format!("{other:?}"),
+ })
+ .collect()
+ }
+
+ #[test]
+ fn claude_stream_reports_tool_runs_and_keeps_the_result() {
+ let t0 = Instant::now();
+ let mut s = ClaudeStream::default();
+ assert_eq!(kinds(&s.line(r#"{"type":"system","subtype":"init"}"#, t0)), ["progress"]);
+ let call = r#"{"type":"assistant","message":{"content":[{"type":"text","text":"ok"},{"type":"tool_use","id":"tu_1","name":"Bash","input":{"command":"sleep 600"}}]}}"#;
+ assert_eq!(kinds(&s.line(call, t0)), ["start tu_1 Bash"]);
+ // The same message again (claude repeats content across partial and whole messages)
+ assert!(kinds(&s.line(call, t0 + Duration::from_secs(5))).iter().all(|k| k == "progress"));
+ let done = r#"{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"tu_1","is_error":true,"content":"denied"}]}}"#;
+ assert_eq!(kinds(&s.line(done, t0)), ["end tu_1 error"]);
+ // A result for a call never started, or one already finished, is not reported
+ assert!(!kinds(&s.line(done, t0 + Duration::from_secs(9))).iter().any(|k| k.starts_with("end")));
+ let result = r#"{"type":"result","is_error":false,"num_turns":2,"result":"all done","usage":{"input_tokens":3,"output_tokens":4}}"#;
+ s.line(result, t0);
+ let parsed = ClaudeResult::parse(&s.into_stdout()).unwrap();
+ assert_eq!(parsed.result, "all done");
+ assert_eq!(parsed.tokens(), Some(7));
+ }
+
+ #[test]
+ fn claude_stream_progress_is_sent_at_most_once_a_second() {
+ let t0 = Instant::now();
+ let mut s = ClaudeStream::default();
+ let delta = r#"{"type":"stream_event","event":{"type":"content_block_delta"}}"#;
+ assert_eq!(s.line(delta, t0).len(), 1);
+ assert!(s.line(delta, t0 + Duration::from_millis(300)).is_empty());
+ assert!(s.line(delta, t0 + Duration::from_millis(900)).is_empty());
+ assert_eq!(s.line(delta, t0 + Duration::from_millis(1100)).len(), 1);
+ }
+
+ #[test]
+ fn claude_stream_shows_long_tool_input_truncated_and_keeps_plain_output() {
+ let mut s = ClaudeStream::default();
+ let big = "x".repeat(10_000);
+ let call = serde_json::json!({"type":"assistant","message":{"content":[{"type":"tool_use","id":"w","name":"Write","input":{"content": big}}]}});
+ let events = s.line(&call.to_string(), Instant::now());
+ let RuntimeEvent::ToolCallPending { args, .. } = &events[0] else { panic!("{events:?}") };
+ assert!(args.as_str().is_some_and(|a| a.len() < 2100 && a.ends_with("[truncated]")), "{args}");
+
+ // An older claude that prints plain text: the text is the reply
+ let mut old = ClaudeStream::default();
+ old.line("hello", Instant::now());
+ old.line("world", Instant::now());
+ assert_eq!(old.into_stdout(), "hello\nworld\n");
+ }
+
+ #[tokio::test]
+ async fn claude_stream_reader_splits_lines_across_reads_and_skips_huge_ones() {
+ let (tx, mut rx) = mpsc::channel(64);
+ let mut input = Vec::new();
+ input.extend_from_slice(br#"{"type":"assistant","message":{"content":[{"type":"tool_use","id":"a","name":"Read","input":{}}]}}"#);
+ input.push(b'\n');
+ input.extend(std::iter::repeat_n(b'y', CLAUDE_LINE_MAX + 10));
+ input.push(b'\n');
+ input.extend_from_slice(br#"{"type":"result","result":"fine"}"#);
+ let out = read_claude_stream(&input[..], &tx).await;
+ drop(tx);
+ assert_eq!(ClaudeResult::parse(&out).unwrap().result, "fine");
+ let mut got = Vec::new();
+ while let Some(e) = rx.recv().await {
+ got.push(e);
+ }
+ assert_eq!(kinds(&got)[0], "start a Read");
+ }
+
#[test]
- fn grok_may_fetch_pages_and_edit_only_inside_the_folder() {
- assert_eq!(grok_builtin_rules(None), ["--allow", "WebFetch"]);
+ fn grok_may_edit_only_inside_the_folder_and_never_fetches_on_its_own() {
+ assert!(grok_builtin_rules(None).is_empty());
let tmp = tempfile::tempdir().unwrap();
let real = tmp.path().canonicalize().unwrap().display().to_string();
let rules = grok_builtin_rules(Some(tmp.path()));
diff --cc src/mcp/session.rs
index aaa11ba2,3fe4b06a..e4a95fb8
--- a/src/mcp/session.rs
+++ b/src/mcp/session.rs
@@@ -243,10 -249,11 +249,11 @@@ impl McpToolSession
tool: t.tool.name.clone(),
arguments: arguments.clone(),
builtin: None,
+ smart: Some(read_only_verdict(t.tool.read_only)),
})
.await;
- if !approved {
- ("denied", "The user denied this tool call.".to_string())
+ if !outcome.allowed() {
+ (outcome.record_status(), outcome.refusal_text().to_string())
} else {
match client.call_tool(&t.tool.name, arguments.clone()).await {
Ok(r) if r.is_error => ("error", r.text),
diff --cc src/server/mcp_runtime.rs
index 5b8c4eb4,5f579b9c..0cc9c281
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@@ -157,14 -150,13 +157,23 @@@ impl Drop for TicketGuard
#[async_trait]
impl ToolApprover for BrokerApprover {
async fn approve(&self, req: ToolApprovalRequest) -> bool {
+ self.decide(req).await.allowed()
+ }
+
+ 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.always_ask && self.db.kwant_approvals(&req.kwant_id).await.is_ok_and(|m| m.is_off());
- let details = match &req.builtin {
+ let mode = self.db.kwant_approvals(&req.kwant_id).await.ok();
- let off = mode.as_ref().is_some_and(|m| m.is_off());
- // "Ask only when risky": what the caller made of this call; nothing known asks
- let smart = mode.as_ref().is_some_and(|m| m.is_smart()).then(|| req.smart.clone()).flatten();
++ let off = !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
++ .as_ref()
++ .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")));
+ let mut details = match &req.builtin {
Some(b) => json!({
"source": "claude_builtin",
"tool": req.tool,
@@@ -197,10 -192,17 +209,17 @@@
if let Err(e) = self.db.save_refused(&record).await {
tracing::warn!(error = %e, "could not record a refused call");
}
- return false;
+ return ApprovalOutcome::Denied;
}
+ if let Some(mcp::SmartVerdict::Allow(why)) = &smart {
+ tracing::info!(kwant = %req.kwant_id, tool = %req.tool_name, reason = %why, "ran without a card: not risky");
+ if let Err(e) = self.db.save_auto_allowed(&record).await {
+ tracing::warn!(error = %e, "could not record a call that ran without a card");
+ }
- return true;
++ return ApprovalOutcome::Allowed;
+ }
- if !off && self.broker.is_allowed_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await {
- return true;
+ 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 {
if let Err(e) = self.db.save_auto_allowed(&record).await {
@@@ -531,10 -443,11 +581,11 @@@ async fn decide(session: &PermissionSes
tool: tool.to_string(),
arguments: input.clone(),
builtin,
+ smart: verdict,
});
// Dropping the approval withdraws its card when the turn ends first
- let allowed = tokio::select! {
- allowed = approval => allowed,
+ let outcome = tokio::select! {
+ outcome = approval => outcome,
_ = session.ended.cancelled() => {
session.ctx.record(cancelled_record(&tool_use_id, tool_name, server, tool, &input));
return json!({"behavior": "deny", "message": "The turn ended before the user answered."});