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.

Review follow-ups: redact saved turn errors, exact dedupe, cap bot_create

Lin (kwant bot)7e771f1e696b
diff --git a/src/db/hires.rs b/src/db/hires.rs
index a9cfc278..9457e663 100644
--- a/src/db/hires.rs
+++ b/src/db/hires.rs
@@ -17,7 +17,8 @@ pub const HIRE_STATUSES: [&str; 5] = ["pending", "accepted", "auto_accepted", "d
/// Proposals one turn may make.
pub const MAX_PROPOSALS_PER_TURN: i64 = 1;
-/// Bots "always accept" may create in a space in 24 hours; past it, proposals ask again.
+/// Bots "always accept" and `bot_create` may make in a space in 24 hours; past it, the person
+/// confirms each new bot on a card.
pub const AUTO_HIRES_PER_DAY: i64 = 3;
#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
@@ -224,13 +225,17 @@ impl Database {
Ok(n)
}
- /// Bots the space's policy created in the last 24 hours (undone ones count too).
+ /// Bots made in the space in the last 24 hours without the person confirming a card: hires
+ /// "always accept" took, plus bots a bot made itself with `bot_create` (undone ones count too).
pub async fn auto_hires_today(&self, space: &SpaceId) -> Result<i64, DbError> {
+ let since = Utc::now() - Duration::hours(24);
let (n,): (i64,) = sqlx::query_as(
- "SELECT COUNT(*) FROM hire_proposals WHERE space_id = ? AND auto = 1 AND resolved_at > ?",
+ "SELECT (SELECT COUNT(*) FROM hire_proposals WHERE space_id = ?1 AND auto = 1 AND resolved_at > ?2)
+ + (SELECT COUNT(*) FROM bot_actions WHERE space_id = ?1 AND action = 'bot_create'
+ AND status IN ('applied', 'confirmed', 'undone') AND created_at > ?2)",
)
.bind(space.as_str())
- .bind(Utc::now() - Duration::hours(24))
+ .bind(since)
.fetch_one(&self.pool)
.await?;
Ok(n)
diff --git a/src/drivers/activity.rs b/src/drivers/activity.rs
index 50850f14..e2bd9104 100644
--- a/src/drivers/activity.rs
+++ b/src/drivers/activity.rs
@@ -297,6 +297,35 @@ pub fn redact(text: &str, secrets: &[String]) -> String {
out
}
+/// Replaces home folders in text shown to other people and bots with `~`: this computer's home
+/// and anything shaped like `/home/<name>` or `/Users/<name>`, so a username doesn't leak.
+pub fn hide_home_paths(text: &str) -> String {
+ let mut text = text.to_string();
+ // A home elsewhere (`/root`, `/var/lib/kwant`); only whole folders, so `/rooted` stays
+ if let Some(home) = dirs::home_dir().and_then(|h| h.to_str().map(|h| h.trim_end_matches('/').to_string())) {
+ if home.len() > 1 {
+ text = text.replace(&format!("{home}/"), "~/");
+ }
+ }
+ let mut out = String::with_capacity(text.len());
+ let mut rest = text.as_str();
+ while let Some((at, len)) = ["/home/", "/Users/"].iter().filter_map(|p| rest.find(p).map(|i| (i, p.len()))).min() {
+ let name_len = rest[at + len..].find(|c: char| c == '/' || c.is_whitespace() || "\"'`)]>:,;".contains(c)).unwrap_or(rest.len() - at - len);
+ // `/home/` on its own (or inside a longer word like `/x/home/`) isn't someone's home
+ let starts_path = at == 0 || !rest[..at].ends_with(|c: char| c.is_alphanumeric() || "_-.".contains(c));
+ if name_len == 0 || !starts_path {
+ out.push_str(&rest[..at + len]);
+ rest = &rest[at + len..];
+ continue;
+ }
+ out.push_str(&rest[..at]);
+ out.push('~');
+ rest = &rest[at + len + name_len..];
+ }
+ out.push_str(rest);
+ out
+}
+
fn arg<'a>(args: &'a Value, keys: &[&str]) -> Option<&'a str> {
keys.iter().find_map(|k| args.get(*k).and_then(Value::as_str)).filter(|s| !s.trim().is_empty())
}
@@ -510,6 +539,17 @@ mod tests {
assert!(s[0].detail.as_ref().unwrap().chars().count() <= MAX_DETAIL);
}
+ #[test]
+ fn home_folders_are_hidden() {
+ assert_eq!(
+ hide_home_paths("open /home/oleks/.kwnt/data.db failed; see /Users/Oleks Smith/x and /home/ann"),
+ "open ~/.kwnt/data.db failed; see ~ Smith/x and ~"
+ );
+ // Not a home: a bare `/home/`, or `home` inside another path
+ assert_eq!(hide_home_paths("/home/ and /srv/home/app"), "/home/ and /srv/home/app");
+ assert_eq!(hide_home_paths("no paths here"), "no paths here");
+ }
+
#[test]
fn redaction_hides_secrets_in_titles_and_details() {
let mut log = ActivityLog::with_secrets(vec!["s3cr3t-value-123".into()]);
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index 12d5afc4..e66236cd 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -83,17 +83,25 @@ pub struct Teammate {
pub title: String,
}
-/// Models only know their training cutoff, so every turn is told the real date and how to use it.
/// Drops the newest history message when it is the person's message this turn answers: callers
/// save it before reading history and then pass it again as the prompt, so the model saw it twice.
+/// The prompt must be that message exactly, or it plus a block kwant appends itself, so a routine
+/// prompt that merely begins with the person's last words keeps that line.
pub fn drop_current_message(history: &mut Vec<crate::db::models::Message>, prompt: &str) {
let Some(last) = history.last() else { return };
let text = last.text.trim();
- if last.sender_role == "user" && !text.is_empty() && prompt.trim_start().starts_with(text) {
+ let is_current = !text.is_empty()
+ && prompt.trim_start().strip_prefix(text).is_some_and(|rest| {
+ rest.trim().is_empty() || KWANT_PROMPT_SUFFIXES.iter().any(|s| rest.starts_with(s))
+ });
+ if last.sender_role == "user" && is_current {
history.pop();
}
}
+/// Blocks kwant adds after the person's own words in a turn's prompt (attachments, routing note).
+const KWANT_PROMPT_SUFFIXES: [&str; 2] = ["\n\n[Attached files]", "\n\n(kwant routing note:"];
+
/// Frames text another bot wrote, wherever it reaches a bot (history, handoffs, delegated tasks
/// and their results), so it is never mistaken for the person's own words or authority.
/// The frame's markers can't be forged from inside: any "[Message from" / "[End of message" in the
@@ -615,9 +623,12 @@ mod tests {
#[test]
fn the_current_message_is_not_repeated_in_history() {
let mut h = vec![said("user", "hi"), said("kwant", "hello"), said("user", "plan my week")];
- drop_current_message(&mut h, "plan my week\n\n[Files attached: a.pdf]");
+ drop_current_message(&mut h, "plan my week\n\n[Attached files]\n- a.pdf");
assert_eq!(h.iter().map(|m| m.text.as_str()).collect::<Vec<_>>(), ["hi", "hello"]);
- // Only the newest, only the person's, only when the prompt starts with it
+ let mut h = vec![said("user", "plan my week ")];
+ drop_current_message(&mut h, " plan my week\n");
+ assert!(h.is_empty());
+ // Only the newest, only the person's, only when the prompt is exactly it
for (last, prompt) in [("kwant", "hello again"), ("user", "something else")] {
let mut h = vec![said("user", "hi"), said(last, "hello")];
if last == "user" {
@@ -626,6 +637,12 @@ mod tests {
drop_current_message(&mut h, prompt);
assert_eq!(h.len(), 2, "{last} {prompt}");
}
+ // A routine whose prompt only begins with the person's last words keeps that line
+ for prompt in ["plan my week and email it", "plan my week\n\nThen send the summary."] {
+ let mut h = vec![said("user", "plan my week")];
+ drop_current_message(&mut h, prompt);
+ assert_eq!(h.len(), 1, "{prompt}");
+ }
let mut h = vec![said("user", " ")];
drop_current_message(&mut h, "anything");
assert_eq!(h.len(), 1);
diff --git a/src/server/activity.rs b/src/server/activity.rs
index 26079b14..43c792c9 100644
--- a/src/server/activity.rs
+++ b/src/server/activity.rs
@@ -54,6 +54,11 @@ impl TurnActivity {
self.with_log(|log| log.add_secrets(secrets));
}
+ /// Masks the turn's secrets, credentials and home folders in text saved for others to read.
+ pub fn redact(&self, text: &str) -> String {
+ crate::drivers::activity::hide_home_paths(&self.with_log(|log| log.redact(text)))
+ }
+
pub fn observe(&self, event: &RuntimeEvent) {
let steps = self.with_log(|log| log.observe(event));
self.send(steps);
diff --git a/src/server/bot_actions.rs b/src/server/bot_actions.rs
index 75ed02e2..d43bd21e 100644
--- a/src/server/bot_actions.rs
+++ b/src/server/bot_actions.rs
@@ -1124,6 +1124,15 @@ impl Ctx<'_> {
if let Some(why) = super::hires::create_clash(self.state, &self.space, name, title).await {
return fail(format!("Nothing was created. {why}"));
}
+ // requested_by_person is only this bot's word, so it shares the daily cap on bots made
+ // without a card; past it, the person confirms the bot themselves
+ let cap = crate::db::hires::AUTO_HIRES_PER_DAY;
+ if self.state.db.auto_hires_today(&self.space).await.unwrap_or(i64::MAX) >= cap {
+ return fail(format!(
+ "Nothing was created: {cap} bots were already made without a card in the last 24 hours. \
+ Use propose_hire (requested_by_person true) so the person confirms this one on a card."
+ ));
+ }
let spec = json!({
"name": name,
"title": title,
diff --git a/src/server/routes.rs b/src/server/routes.rs
index ed609eeb..3b05a3ad 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -598,6 +598,18 @@ async fn get_configured_endpoint(db: &crate::db::Database, target_model: &str) -
}
}
+/// Longest driver error kept in a saved `turn_failed` message, in bytes.
+const MAX_SAVED_ERROR_BYTES: usize = 600;
+
+/// The chat message saved when a turn fails. Other bots read it as history, so the turn's secrets,
+/// credentials and home folders are masked and a long error is clipped.
+fn turn_failed_text(name: &str, why: &str, activity: &super::activity::TurnActivity) -> String {
+ let shown = scrub_urls(&activity.redact(why));
+ let clipped = truncate_chars(&shown, MAX_SAVED_ERROR_BYTES);
+ let ellipsis = if clipped.len() < shown.len() { "…" } else { "" };
+ format!("⚠️ [{name}] Couldn't finish this reply: {clipped}{ellipsis}")
+}
+
/// Truncates to at most `max` bytes without splitting a UTF-8 character.
pub(super) fn truncate_chars(text: &str, max: usize) -> &str {
if text.len() <= max {
@@ -2192,7 +2204,7 @@ async fn run_kwant_turn_inner(
// Saved like a reply, so the failure is still there after a reload (the live error event isn't)
let msg = NewMessage {
reasoning_content: with_notices(opts.label.clone()),
- ..scope.message("kwant", &target_kwant.name, format!("⚠️ [{}] Couldn't finish this reply: {why}", target_kwant.name))
+ ..scope.message("kwant", &target_kwant.name, turn_failed_text(&target_kwant.name, &why, &event_broadcast.activity))
};
scope.save(&msg, super::activity::with_activity(Some(json!({"kind": "turn_failed"})), activity)).await;
if let Some(e) = driver_error {
@@ -3722,7 +3734,33 @@ pub async fn execute_tool(
#[cfg(test)]
mod tests {
- use super::scrub_urls;
+ use super::{scrub_urls, turn_failed_text};
+
+ #[test]
+ fn a_saved_turn_failure_hides_secrets_and_home_folders() {
+ let tag = crate::drivers::events::TurnTag {
+ turn_id: "t-fail".into(),
+ kwant_id: "k".into(),
+ context_id: "c".into(),
+ thread_id: None,
+ };
+ let activity = super::super::activity::TurnActivity::start(tokio::sync::broadcast::channel(4).0, tag);
+ activity.add_secrets(vec!["hunter2-mcp-value".into()]);
+ let why = format!(
+ "the claude driver failed: 401 key sk-ant-api03-ABCDEFGHIJKLMNOPQRSTUVWX for /home/oleks/.kwnt/secrets.json \
+ (env hunter2-mcp-value) {}",
+ "x".repeat(2000)
+ );
+ let text = turn_failed_text("Lin", &why, &activity);
+ assert!(text.starts_with("⚠️ [Lin] Couldn't finish this reply: the claude driver failed: 401 key"), "{text}");
+ for leak in ["sk-ant-api03-ABCDEF", "/home/oleks", "hunter2-mcp-value"] {
+ assert!(!text.contains(leak), "{leak} in {text}");
+ }
+ assert!(text.contains("~/.kwnt/secrets.json"), "{text}");
+ assert!(text.ends_with('…') && text.len() < 700, "{} bytes", text.len());
+ // A short error is kept whole
+ assert!(!turn_failed_text("Lin", "the turn ended without a reply", &activity).ends_with('…'));
+ }
#[test]
fn failure_reasons_drop_url_credentials() {
diff --git a/tests/hires_test.rs b/tests/hires_test.rs
index 3212b197..8f698a00 100644
--- a/tests/hires_test.rs
+++ b/tests/hires_test.rs
@@ -566,3 +566,32 @@ async fn bot_create_obeys_the_hire_policy_and_turned_down_kinds() {
assert!(!err, "{text}");
assert!(bot_named(&e, "spc_default", "Gardener").await.is_some());
}
+
+/// `requested_by_person` is only the bot's word, so bots it makes share the daily cap with
+/// "always accept"; past it, the person confirms the next bot on a card.
+#[tokio::test]
+async fn bot_create_counts_against_the_daily_auto_hire_cap() {
+ let e = setup().await;
+ let create = |name: &str, role: &str| {
+ json!({"name": name, "title": role, "instructions": format!("You are {name}."), "requested_by_person": true})
+ };
+ for (i, (name, role)) in [("Taxman", "Tax advisor"), ("Coach", "Fitness coach"), ("Gardener", "Garden designer")].iter().enumerate() {
+ let token = turn(&e, &format!("t-cap{i}")).await;
+ let (text, err) = tool(&e, &token, "bot_create", create(name, role)).await;
+ assert!(!err, "{name}: {text}");
+ }
+ let (_, p) = call(&e.app, "GET", "/api/spaces/spc_default/hire-policy", None, None).await;
+ assert_eq!(p["auto_hires_last_24h"], 3, "{p}");
+
+ // The fourth in 24 hours isn't created; the bot is pointed at a card
+ let token = turn(&e, "t-cap3").await;
+ let (text, err) = tool(&e, &token, "bot_create", create("Painter", "Portrait painter")).await;
+ assert!(err && text.contains("without a card") && text.contains("propose_hire"), "{text}");
+ assert!(bot_named(&e, "spc_default", "Painter").await.is_none());
+
+ // And "always accept" can't add more on top: its next hire asks the person too
+ let (_, _) = call(&e.app, "PUT", "/api/spaces/spc_default/hire-policy", None, Some(json!({"policy": "auto"}))).await;
+ let text = ok(&e, &token, specialist("Painter", "Portrait painter")).await;
+ assert!(text.contains("Nothing is created"), "{text}");
+ assert_eq!(latest(&e).await["status"], "pending");
+}