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.

Bots keep "Good for" / "Not for" when created and copied

Lin (kwant bot)199fe189f920
diff --git a/docs/channel-routing.md b/docs/channel-routing.md
index a269371a..70fae371 100644
--- a/docs/channel-routing.md
+++ b/docs/channel-routing.md
@@ -31,11 +31,17 @@ Laya's titles-only guess is a tiebreaker only; it no longer picks a bot on its o
## covers / avoids
-`GET /api/kwants`, `GET /api/kwants/:id` and `PUT /api/kwants/:id` carry `covers: [string]` and
-`avoids: [string]` (at most 20 entries of 60 characters; trimmed, duplicates dropped ignoring
-case). On `PUT`, a list left out stays as it is and `[]` clears it. A covered entry counts double
-in scoring; an avoided entry keeps the bot out unless it is @mentioned. Empty lists change nothing.
-Only the Concierge gets defaults.
+`GET /api/kwants` (on every bot), `POST /api/kwants` and `PUT /api/kwants/:id` carry
+`covers: [string]` and `avoids: [string]` (at most 20 entries of 60 characters; trimmed,
+duplicates dropped ignoring case; a 400 `"covers: …"` / `"avoids: …"` refuses the whole request,
+and on create no bot is made). On `PUT`, a list left out stays as it is and `[]` clears it; on
+`POST` a list left out is empty. A covered entry counts double in scoring; an avoided entry keeps
+the bot out unless it is @mentioned. Empty lists change nothing. Only the Concierge gets defaults.
+
+A bot's export (`kwant.bundle/1`) carries `covers` and `avoids` when they aren't empty, and
+importing it restores them, so a copied bot is routed the same way. The import preview names them
+in a warning. An entry the app wouldn't keep (over 60 characters, or past 20) is dropped with a
+note in the preview rather than stopping the import, since the lists only steer routing.
## Asking
diff --git a/src/db/bot_actions.rs b/src/db/bot_actions.rs
index ff29f745..60ff74b7 100644
--- a/src/db/bot_actions.rs
+++ b/src/db/bot_actions.rs
@@ -261,7 +261,8 @@ impl Database {
}
/// Removes a kwant that [`Self::kwant_in_use`] cleared, with its memories, routines and
- /// their runs, MCP opt-outs and channel/team memberships, in one transaction.
+ /// their runs, MCP opt-outs, covers/avoids lists and channel/team memberships, in one
+ /// transaction.
pub async fn delete_unused_kwant(&self, id: &str) -> Result<bool, DbError> {
let mut tx = self.pool.begin().await?;
for sql in [
@@ -270,6 +271,7 @@ impl Database {
"DELETE FROM kwant_memories WHERE kwant_id = ?",
"DELETE FROM kwant_mcp_disabled WHERE kwant_id = ?",
"DELETE FROM kwant_mcp_servers WHERE kwant_id = ?",
+ "DELETE FROM kwant_scope WHERE kwant_id = ?",
] {
sqlx::query(sql).bind(id).execute(&mut *tx).await?;
}
diff --git a/src/db/imports.rs b/src/db/imports.rs
index 6787fd60..f5231540 100644
--- a/src/db/imports.rs
+++ b/src/db/imports.rs
@@ -210,6 +210,14 @@ impl Database {
.bind(bot.browser_block_private_network)
.execute(&mut *tx)
.await?;
+ if !bot.covers.is_empty() || !bot.avoids.is_empty() {
+ sqlx::query("INSERT INTO kwant_scope (kwant_id, covers, avoids) VALUES (?, ?, ?)")
+ .bind(&id)
+ .bind(serde_json::to_string(&bot.covers)?)
+ .bind(serde_json::to_string(&bot.avoids)?)
+ .execute(&mut *tx)
+ .await?;
+ }
// No tools: opted out of every MCP server the space has now.
sqlx::query("INSERT OR IGNORE INTO kwant_mcp_disabled (kwant_id, server_id) SELECT ?, id FROM mcp_servers WHERE space_id = ?")
.bind(&id)
@@ -361,6 +369,7 @@ impl Database {
"DELETE FROM kwant_memories WHERE kwant_id = ?",
"DELETE FROM kwant_mcp_disabled WHERE kwant_id = ?",
"DELETE FROM kwant_mcp_servers WHERE kwant_id = ?",
+ "DELETE FROM kwant_scope WHERE kwant_id = ?",
] {
sqlx::query(sql).bind(&k.id).execute(&mut *tx).await?;
}
@@ -455,6 +464,7 @@ impl Database {
.collect();
let tool_hints = self.list_active_mcp_servers_for_kwant(&k.id).await?.into_iter().map(|s| s.name).collect();
let sites = self.browser_sites(&k.id).await?;
+ let scope = self.get_scope(&k.id).await?;
Ok(BotSpec {
ref_: k.name.clone(),
name: k.name.clone(),
@@ -470,6 +480,8 @@ impl Database {
browser_allowed_sites: sites.browser_allowed_sites,
browser_blocked_sites: sites.browser_blocked_sites,
browser_block_private_network: sites.browser_block_private_network,
+ covers: scope.covers,
+ avoids: scope.avoids,
..BotSpec::default()
})
}
diff --git a/src/import/mod.rs b/src/import/mod.rs
index 415b0122..f755eac6 100644
--- a/src/import/mod.rs
+++ b/src/import/mod.rs
@@ -11,6 +11,7 @@ pub mod prompts;
pub mod scrub;
use crate::db::continuity::{clean_memory_text, MAX_INSTRUCTIONS_CHARS, MAX_MEMORIES_PER_KWANT, MAX_MEMORY_CHARS};
+use crate::db::routing::{MAX_SCOPE_ENTRIES, MAX_SCOPE_ENTRY_CHARS};
use crate::db::skills::{clean_skill_name, clean_skill_text, MAX_PENDING_PER_KWANT, MAX_SKILL_DESCRIPTION_CHARS};
use crate::routines::Schedule;
use crate::sandbox::site_guard;
@@ -132,6 +133,12 @@ pub struct BotSpec {
pub browser_blocked_sites: Vec<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub browser_block_private_network: bool,
+ /// What the bot is for and not for ("Good for" / "Not for"; see [`crate::db::routing::Scope`]),
+ /// kept so a copied bot is routed the same way in channels.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub covers: Vec<String>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub avoids: Vec<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
@@ -509,6 +516,40 @@ fn site_limits(bot: &BotSpec) -> Option<String> {
(!parts.is_empty()).then(|| parts.join("; "))
}
+/// A bot's covers/avoids lists in the app's words, or `None` when both are empty.
+fn scope_words(bot: &BotSpec) -> Option<String> {
+ let mut parts = Vec::new();
+ if !bot.covers.is_empty() {
+ parts.push(format!("Good for: {}.", bot.covers.join(", ")));
+ }
+ if !bot.avoids.is_empty() {
+ parts.push(format!("Not for: {}.", bot.avoids.join(", ")));
+ }
+ (!parts.is_empty()).then(|| parts.join(" "))
+}
+
+/// A covers or avoids list as `PUT /api/kwants/:id` keeps it (trimmed, no blanks or repeats
+/// ignoring case), with hidden characters and extra spaces removed. An entry that's too long or
+/// past the cap is left out with a note instead of stopping the import: the lists only steer
+/// routing.
+fn tidy_scope(list: &[String], label: &str, who: Option<&str>, dropped: &mut Vec<Notice>) -> Vec<String> {
+ let mut out: Vec<String> = Vec::new();
+ for raw in list {
+ let entry = one_line(raw, usize::MAX);
+ if entry.is_empty() || out.iter().any(|o| o.eq_ignore_ascii_case(&entry)) {
+ continue;
+ }
+ if entry.chars().count() > MAX_SCOPE_ENTRY_CHARS {
+ dropped.push(Notice::new(who, format!("{label} entry over {MAX_SCOPE_ENTRY_CHARS} characters: {}…", cut(&entry, MAX_SCOPE_ENTRY_CHARS))));
+ } else if out.len() == MAX_SCOPE_ENTRIES {
+ dropped.push(Notice::new(who, format!("{label} entry (over the {MAX_SCOPE_ENTRIES}-entry limit): {entry}")));
+ } else {
+ out.push(entry);
+ }
+ }
+ out
+}
+
/// Checks and tidies `bundle` for a space whose bots are called `existing` (any case). Pure: the
/// same input always gives the same result, so apply re-runs it on what the preview returned.
pub fn normalize(mut bundle: Bundle, existing: &[String]) -> Checked {
@@ -616,6 +657,11 @@ pub fn normalize(mut bundle: Bundle, existing: &[String]) -> Checked {
if let Some(limits) = site_limits(bot) {
warnings.push(Notice::new(who, format!("Its browser is limited: {limits}. Change this in the bot's settings after importing.")));
}
+ bot.covers = tidy_scope(&bot.covers, "\"Good for\"", who, &mut dropped);
+ bot.avoids = tidy_scope(&bot.avoids, "\"Not for\"", who, &mut dropped);
+ if let Some(scope) = scope_words(bot) {
+ warnings.push(Notice::new(who, format!("{scope} Channels use this to pick who answers; change it in the bot's settings after importing.")));
+ }
if !bot.starters.is_empty() {
dropped.push(Notice::new(who, format!("{} conversation starter(s): kwant has no place for them yet.", bot.starters.len())));
}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 7c495c55..65d131f5 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -169,6 +169,8 @@ pub struct CreateKwantRequest {
binding: ProfileBinding,
#[serde(flatten)]
browser: BrowserSitesUpdate,
+ #[serde(flatten)]
+ scope: ScopeUpdate,
}
#[derive(Debug, Deserialize)]
@@ -179,14 +181,34 @@ pub struct UpdateKwantRequest {
binding: ProfileBinding,
#[serde(flatten)]
browser: BrowserSitesUpdate,
- /// Left out: the list stays as it is. `[]` clears it.
- #[serde(default)]
+ #[serde(flatten)]
+ scope: ScopeUpdate,
+}
+
+type SiteList = Option<Vec<String>>;
+type ScopeList = Option<Vec<String>>;
+
+/// What the bot is for and not for ("Good for" / "Not for" in the app). Left out: the list stays
+/// as it is. `[]` clears it.
+#[derive(Debug, Default, Deserialize)]
+pub struct ScopeUpdate {
covers: Option<Vec<String>>,
- #[serde(default)]
avoids: Option<Vec<String>>,
}
-type SiteList = Option<Vec<String>>;
+impl ScopeUpdate {
+ /// The lists cleaned, or the 400 naming the list that's too long.
+ #[allow(clippy::result_large_err)]
+ fn cleaned(&self) -> Result<(ScopeList, ScopeList), Response> {
+ let clean = |list: &ScopeList, field: &str| {
+ list.as_deref()
+ .map(crate::db::routing::clean_scope_list)
+ .transpose()
+ .map_err(|e| api_error(StatusCode::BAD_REQUEST, format!("{field}: {e}")))
+ };
+ Ok((clean(&self.covers, "covers")?, clean(&self.avoids, "avoids")?))
+ }
+}
/// Which sites the bot's browser may open; a field left out stays as it is.
#[derive(Debug, Default, Deserialize)]
@@ -272,6 +294,7 @@ pub async fn create_kwant(
return Err(api_error(StatusCode::BAD_REQUEST, &msg));
}
let (allowed_sites, blocked_sites) = payload.browser.normalized()?;
+ let (covers, avoids) = payload.scope.cleaned()?;
validate_kwant_name(&state, &space, &mut payload.base.name, None).await?;
check_binding(&state, &space, &payload.binding, &payload.base.preferred_model)
.await
@@ -285,6 +308,9 @@ pub async fn create_kwant(
.set_browser_sites(&kwant.id, allowed_sites.as_deref(), blocked_sites.as_deref(), payload.browser.browser_block_private_network)
.await
.map_err(|e| db_error(&e, ""))?;
+ if covers.iter().chain(avoids.iter()).any(|list| !list.is_empty()) {
+ state.db.set_scope(&kwant.id, covers.as_deref(), avoids.as_deref()).await.map_err(|e| db_error(&e, ""))?;
+ }
ensure_general(&state, &space, &kwant.id).await;
kwant_view_json(&state, &kwant.id).await.map_err(IntoResponse::into_response)
}
@@ -342,8 +368,7 @@ pub async fn update_kwant(
check_binding(&state, &space, &payload.binding, &payload.base.preferred_model)
.await
.map_err(IntoResponse::into_response)?;
- let covers = payload.covers.as_deref().map(crate::db::routing::clean_scope_list).transpose().map_err(|e| api_error(StatusCode::BAD_REQUEST, format!("covers: {e}")))?;
- let avoids = payload.avoids.as_deref().map(crate::db::routing::clean_scope_list).transpose().map_err(|e| api_error(StatusCode::BAD_REQUEST, format!("avoids: {e}")))?;
+ let (covers, avoids) = payload.scope.cleaned()?;
let clash = format!("a bot called {} already exists in this space", payload.base.name);
match state.db.update_kwant(&id, &payload.base).await {
Ok(Some(_)) => {}
diff --git a/tests/import_test.rs b/tests/import_test.rs
index 7542bbd9..1f703d80 100644
--- a/tests/import_test.rs
+++ b/tests/import_test.rs
@@ -97,7 +97,7 @@ async fn row_counts(tmp: &TempDir) -> Vec<(String, i64)> {
let url = format!("sqlite://{}?mode=ro", tmp.path().join("kwnt.db").display());
let pool = sqlx::SqlitePool::connect(&url).await.unwrap();
let mut out = Vec::new();
- for t in ["kwants", "skills", "routines", "kwant_memories", "teams", "channels", "kwant_mcp_disabled", "imports", "attachments"] {
+ for t in ["kwants", "skills", "routines", "kwant_memories", "teams", "channels", "kwant_mcp_disabled", "imports", "attachments", "kwant_scope"] {
let (n,): (i64,) = sqlx::query_as(&format!("SELECT COUNT(*) FROM {t}")).fetch_one(&pool).await.unwrap();
out.push((t.to_string(), n));
}
@@ -810,3 +810,91 @@ async fn browser_site_rules_survive_create_export_and_import() {
assert_eq!(status, StatusCode::BAD_REQUEST, "{v}");
assert_eq!(e.state.db.list_kwants(&SpaceId::new(b.clone())).await.unwrap().len(), 1);
}
+
+/// A bot's "Good for" / "Not for" lists (covers/avoids) survive being created with them, exported
+/// and imported (kwant's copy of a bot); create refuses a list PUT would refuse, and import drops
+/// such an entry with a note instead of stopping. Undo removes the copy's lists with it.
+#[tokio::test]
+async fn covers_and_avoids_survive_create_export_and_import() {
+ let e = setup().await;
+ let a = new_space(&e, "Source").await;
+ let b = new_space(&e, "Copy").await;
+ let bot = |name: &str, scope: Value| {
+ let mut v = json!({"name": name, "title": "Food guide", "persona_prompt": "Finds places to eat.", "avatar_sprite": "default",
+ "driver_type": "api", "preferred_model": "auto"});
+ v.as_object_mut().unwrap().extend(scope.as_object().unwrap().clone());
+ v
+ };
+ let lists = |v: &Value| json!({"covers": v["covers"], "avoids": v["avoids"]});
+ let listed = |all: &Value, id: &str| all.as_array().unwrap().iter().find(|k| k["id"] == id).cloned().unwrap_or(Value::Null);
+ let want = json!({"covers": ["Restaurants", "street food"], "avoids": ["legal advice"]});
+
+ // Create: cleaned like PUT (trimmed, repeats dropped ignoring case)
+ let (status, made) = json_call(&e.app, "POST", &format!("/api/kwants?space={a}"),
+ bot("Foodie", json!({"covers": [" Restaurants ", "street food", "restaurants", ""], "avoids": ["legal advice"]}))).await;
+ assert_eq!(status, StatusCode::OK, "{made}");
+ assert_eq!(lists(&made), want);
+ let id = made["id"].as_str().unwrap().to_string();
+ let (_, all) = get(&e.app, &format!("/api/kwants?space={a}")).await;
+ assert_eq!(lists(&listed(&all, &id)), want, "{all}");
+
+ // A list PUT would refuse is a 400 naming it, and no bot is made
+ let too_many: Vec<String> = (0..21).map(|i| format!("topic {i}")).collect();
+ let (status, err) = json_call(&e.app, "POST", &format!("/api/kwants?space={a}"), bot("Many", json!({"covers": too_many}))).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{err}");
+ assert!(err.to_string().contains("covers: at most 20 entries"), "{err}");
+ let (status, err) = json_call(&e.app, "POST", &format!("/api/kwants?space={a}"), bot("Long", json!({"avoids": ["x".repeat(61)]}))).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{err}");
+ assert!(err.to_string().contains("avoids: each entry is at most 60 characters"), "{err}");
+ assert_eq!(e.state.db.list_kwants(&SpaceId::new(a.clone())).await.unwrap().len(), 1);
+
+ // A bot made without them has empty lists, no row, and its export carries neither field
+ let (status, plain) = json_call(&e.app, "POST", &format!("/api/kwants?space={a}"), bot("Plain", json!({"covers": [], "avoids": []}))).await;
+ assert_eq!(status, StatusCode::OK, "{plain}");
+ assert_eq!(lists(&plain), json!({"covers": [], "avoids": []}));
+ let plain_id = plain["id"].as_str().unwrap();
+ let (_, plain_out) = get(&e.app, &format!("/api/kwants/{plain_id}/export?space={a}")).await;
+ let keys = plain_out["bots"][0].as_object().unwrap();
+ assert!(!keys.contains_key("covers") && !keys.contains_key("avoids"), "{plain_out}");
+ assert!(e.state.db.scopes_for(&[plain_id.to_string()]).await.unwrap().is_empty(), "no row for empty lists");
+
+ // Export → import into another space: the copy has the same lists, and the preview says so
+ let (status, out) = get(&e.app, &format!("/api/kwants/{id}/export?space={a}")).await;
+ assert_eq!(status, StatusCode::OK, "{out}");
+ assert_eq!(lists(&out["bots"][0]), want);
+ let before = row_counts(&e.tmp).await;
+ let (status, p) = send(&e.app, "POST", &format!("/api/import/preview?space={b}&filename=bot.kwant.json"), "application/octet-stream", out.to_string().into_bytes()).await;
+ assert_eq!(status, StatusCode::OK, "{p}");
+ assert_eq!(row_counts(&e.tmp).await, before, "preview writes nothing");
+ assert!(p["warnings"].to_string().contains("Good for: Restaurants, street food. Not for: legal advice. Channels use this to pick who answers"), "{p}");
+ let (status, v) = apply(&e.app, &b, &p["bundle"], &[]).await;
+ assert_eq!(status, StatusCode::CREATED, "{v}");
+ let copy = v["import"]["created"]["kwants"][0]["id"].as_str().unwrap().to_string();
+ let (_, all) = get(&e.app, &format!("/api/kwants?space={b}")).await;
+ assert_eq!(lists(&listed(&all, &copy)), want, "{all}");
+
+ // Undo takes the copy's lists with it
+ let import_id = v["import"]["id"].as_str().unwrap();
+ let (status, undone) = undo_call(&e, &format!("/api/imports/{import_id}/undo?space={b}"), Value::Null).await;
+ assert_eq!(status, StatusCode::OK, "{undone}");
+ assert!(e.state.db.scopes_for(std::slice::from_ref(&copy)).await.unwrap().is_empty(), "undo leaves no lists behind");
+
+ // An entry the app wouldn't keep is dropped with a note; the rest import
+ let mut odd = out.clone();
+ let mut covers: Vec<String> = vec!["y".repeat(61), "Bistro\u{200B}s".into()];
+ covers.extend((0..21).map(|i| format!("topic {i}")));
+ odd["bots"][0]["covers"] = json!(covers);
+ let (status, p) = send(&e.app, "POST", &format!("/api/import/preview?space={b}&filename=bot.kwant.json"), "application/octet-stream", odd.to_string().into_bytes()).await;
+ assert_eq!(status, StatusCode::OK, "{p}");
+ assert_eq!(p["problems"], json!([]), "{p}");
+ let dropped = p["dropped"].to_string();
+ assert!(dropped.contains("\\\"Good for\\\" entry over 60 characters"), "{dropped}");
+ assert!(dropped.contains("\\\"Good for\\\" entry (over the 20-entry limit): topic 19") && dropped.contains("topic 20"), "{dropped}");
+ let kept = p["bundle"]["bots"][0]["covers"].as_array().unwrap();
+ assert_eq!((kept.len(), kept[0].as_str()), (20, Some("Bistros")), "{p}");
+ let (status, v) = apply(&e.app, &b, &p["bundle"], &[]).await;
+ assert_eq!(status, StatusCode::CREATED, "{v}");
+ let copy = v["import"]["created"]["kwants"][0]["id"].as_str().unwrap();
+ let scope = e.state.db.get_scope(copy).await.unwrap();
+ assert_eq!((scope.covers.len(), scope.avoids.clone()), (20, vec!["legal advice".to_string()]));
+}