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.

Spaces S2b: chat/send space guard, ask_user race, "bot" wording

Lin (kwant bot)6dd9b98ebc1a
diff --git a/src/db/continuity.rs b/src/db/continuity.rs
index 99997453..b3dc3ebd 100644
--- a/src/db/continuity.rs
+++ b/src/db/continuity.rs
@@ -60,7 +60,7 @@ impl std::fmt::Display for MemoryError {
),
MemoryError::TooMany => write!(
f,
- "this agent already has {MAX_MEMORIES_PER_KWANT} memories; remove one first"
+ "this bot already has {MAX_MEMORIES_PER_KWANT} memories; remove one first"
),
MemoryError::NotFound => write!(f, "no such memory"),
MemoryError::Db(_) => write!(f, "database error"),
@@ -448,7 +448,7 @@ impl Database {
/// The kwant (and channel, when set) a routine runs as must share a space.
async fn routine_space(&self, input: &NewRoutine) -> Result<SpaceId, DbError> {
- let other = || DbError::OtherSpace("the agent and channel must be in the same space".into());
+ let other = || DbError::OtherSpace("the bot and channel must be in the same space".into());
let space = self.space_of_kwant(&input.kwant_id).await?.ok_or_else(other)?;
if let Some(channel) = &input.channel_id {
if self.space_of_channel(channel).await?.as_ref() != Some(&space) {
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 3f795666..3c66c760 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -9,6 +9,11 @@ pub mod skills;
pub mod away;
pub mod spaces;
+/// What a space's #general says about itself.
+pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";
+/// Default's #general description before the "kwant bots" wording; replaced only if unchanged.
+const OLD_GENERAL_DESCRIPTION: &str = "Main collaboration hub for all agents";
+
use models::*;
use spaces::SpaceId;
use sqlx::{sqlite::SqlitePoolOptions, Pool, Sqlite};
@@ -169,7 +174,7 @@ impl Database {
if let Some(lead) = kwants.first() {
let chan = NewChannel {
name: "general".into(),
- description: Some("Main collaboration hub for all agents".into()),
+ description: Some(GENERAL_DESCRIPTION.into()),
lead_kwant_id: lead.id.clone(),
member_kwants: kwants.iter().map(|k| k.id.clone()).collect(),
routing_mode: "auto".into(),
@@ -177,6 +182,12 @@ impl Database {
self.create_channel(&space, &chan).await?;
}
} else {
+ // The old seeded #general text, if nobody edited it
+ let _ = sqlx::query("UPDATE channels SET description = ? WHERE name = 'general' AND description = ?")
+ .bind(GENERAL_DESCRIPTION)
+ .bind(OLD_GENERAL_DESCRIPTION)
+ .execute(&self.pool)
+ .await;
// Smoothly migrate any legacy starter names and prompts
let _ = sqlx::query("UPDATE kwants SET name = 'Architect', title = 'Systems Architect', avatar_sprite = 'architect', persona_prompt = 'You are the Architect, an expert in deep systems architecture, software design, and complex multi-file engineering. You give structured, thorough, and highly insightful technical advice.' WHERE name IN ('CyberMage', 'Architect') AND persona_prompt LIKE '%CyberMage%'").execute(&self.pool).await;
let _ = sqlx::query("UPDATE kwants SET name = 'TechLead', title = 'Staff Engineer & Prototyper', avatar_sprite = 'tech_lead', persona_prompt = 'You are the Tech Lead, a sharp, pragmatic engineer who excels in fast reasoning, rapid prototyping, and clear technical communication.' WHERE name IN ('PixelNinja', 'TechLead') AND persona_prompt LIKE '%PixelNinja%'").execute(&self.pool).await;
@@ -339,7 +350,7 @@ impl Database {
if self.kwants_in_space(space, &ids).await? {
Ok(())
} else {
- Err(DbError::OtherSpace("every lead and member must be a kwant in this space".into()))
+ Err(DbError::OtherSpace("every lead and member must be a bot in this space".into()))
}
}
@@ -358,38 +369,8 @@ impl Database {
/// [`Self::insert_message`] into a thread and/or with kwnt's own `meta`.
pub async fn insert_message_with(&self, input: &NewMessage, extra: &MessageExtra) -> Result<Message, DbError> {
- let id = Uuid::new_v4().to_string();
- let tools_json = input
- .tool_calls
- .as_ref()
- .map(serde_json::to_string)
- .transpose()?;
-
- sqlx::query(
- r#"
- INSERT INTO messages (id, channel_id, direct_kwant_id, sender_role, sender_id, text, reasoning_content, tool_calls, tokens_used, thread_id, meta)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- "#,
- )
- .bind(&id)
- .bind(&input.channel_id)
- .bind(&input.direct_kwant_id)
- .bind(&input.sender_role)
- .bind(&input.sender_id)
- .bind(&input.text)
- .bind(&input.reasoning_content)
- .bind(&tools_json)
- .bind(input.tokens_used)
- .bind(&extra.thread_id)
- .bind(extra.meta.as_ref().map(|m| m.to_string()))
- .execute(&self.pool)
- .await?;
-
- let row = sqlx::query_as::<_, Message>("SELECT * FROM messages WHERE id = ?")
- .bind(&id)
- .fetch_one(&self.pool)
- .await?;
- Ok(row)
+ let mut conn = self.pool.acquire().await?;
+ insert_message_on(&mut conn, input, extra).await
}
pub async fn list_messages(&self, channel_or_kwant_id: &str, limit: i64) -> Result<Vec<Message>, DbError> {
@@ -847,3 +828,41 @@ impl Database {
}
}
+/// Inserts one message on `conn`, so it can be part of a caller's transaction.
+pub(crate) async fn insert_message_on(
+ conn: &mut sqlx::SqliteConnection,
+ input: &NewMessage,
+ extra: &MessageExtra,
+) -> Result<Message, DbError> {
+ let id = Uuid::new_v4().to_string();
+ let tools_json = input
+ .tool_calls
+ .as_ref()
+ .map(serde_json::to_string)
+ .transpose()?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO messages (id, channel_id, direct_kwant_id, sender_role, sender_id, text, reasoning_content, tool_calls, tokens_used, thread_id, meta)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ "#,
+ )
+ .bind(&id)
+ .bind(&input.channel_id)
+ .bind(&input.direct_kwant_id)
+ .bind(&input.sender_role)
+ .bind(&input.sender_id)
+ .bind(&input.text)
+ .bind(&input.reasoning_content)
+ .bind(&tools_json)
+ .bind(input.tokens_used)
+ .bind(&extra.thread_id)
+ .bind(extra.meta.as_ref().map(|m| m.to_string()))
+ .execute(&mut *conn)
+ .await?;
+
+ Ok(sqlx::query_as::<_, Message>("SELECT * FROM messages WHERE id = ?")
+ .bind(&id)
+ .fetch_one(&mut *conn)
+ .await?)
+}
diff --git a/src/db/questions.rs b/src/db/questions.rs
index 169f815f..7517783f 100644
--- a/src/db/questions.rs
+++ b/src/db/questions.rs
@@ -1,6 +1,7 @@
//! Questions an agent asked the user mid-turn (`ask_user`): a question, 2–5 choices, and always a
//! free-text answer. A question is `open` until answered, dismissed or its turn is stopped.
+use super::models::{Message, MessageExtra, NewMessage};
use super::{Database, DbError};
use chrono::{DateTime, Utc};
use serde::Serialize;
@@ -151,17 +152,27 @@ impl Database {
question: &str,
choices: &[String],
) -> Result<Question, QuestionError> {
- let open: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM questions WHERE kwant_id = ? AND status = 'open'")
- .bind(&place.kwant_id)
- .fetch_one(&self.pool)
- .await?;
- if open >= MAX_OPEN_PER_KWANT {
- return Err(QuestionError::TooManyOpen);
- }
+ let (q, _) = self.create_question_with_card(place, question, choices, |_| None).await?;
+ Ok(q)
+ }
+
+ /// Saves a question together with the chat message that shows it (built by `card` from the
+ /// new question), in one transaction: nobody can see the question before its card exists.
+ pub async fn create_question_with_card(
+ &self,
+ place: &QuestionPlace,
+ question: &str,
+ choices: &[String],
+ card: impl FnOnce(&Question) -> Option<(NewMessage, MessageExtra)>,
+ ) -> Result<(Question, Option<Message>), QuestionError> {
+ // The first statement writes, so the transaction takes SQLite's write lock up front
+ // (waiting on busy_timeout) instead of failing to upgrade a read lock under load
+ let mut tx = self.pool.begin().await?;
let id = Uuid::new_v4().to_string();
- sqlx::query(
+ let inserted = sqlx::query(
"INSERT INTO questions (id, kwant_id, channel_id, direct_kwant_id, thread_id, turn_id, question, choices, status, created_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'open', ?)",
+ SELECT ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?
+ WHERE (SELECT COUNT(*) FROM questions WHERE kwant_id = ? AND status = 'open') < ?",
)
.bind(&id)
.bind(&place.kwant_id)
@@ -172,9 +183,24 @@ impl Database {
.bind(question)
.bind(serde_json::to_string(choices).unwrap_or_else(|_| "[]".into()))
.bind(Utc::now())
- .execute(&self.pool)
+ .bind(&place.kwant_id)
+ .bind(MAX_OPEN_PER_KWANT)
+ .execute(&mut *tx)
.await?;
- self.get_question(&id).await?.ok_or(QuestionError::Db)
+ if inserted.rows_affected() == 0 {
+ return Err(QuestionError::TooManyOpen);
+ }
+ let get = "SELECT * FROM questions WHERE id = ?";
+ let mut q = sqlx::query_as::<_, Question>(get).bind(&id).fetch_one(&mut *tx).await?;
+ let mut message = None;
+ if let Some((msg, extra)) = card(&q) {
+ let saved = super::insert_message_on(&mut tx, &msg, &extra).await?;
+ sqlx::query("UPDATE questions SET message_id = ? WHERE id = ?").bind(&saved.id).bind(&id).execute(&mut *tx).await?;
+ q = sqlx::query_as::<_, Question>(get).bind(&id).fetch_one(&mut *tx).await?;
+ message = Some(saved);
+ }
+ tx.commit().await?;
+ Ok((q, message))
}
pub async fn get_question(&self, id: &str) -> Result<Option<Question>, DbError> {
@@ -184,11 +210,6 @@ impl Database {
.await?)
}
- pub async fn set_question_message(&self, id: &str, message_id: &str) -> Result<(), DbError> {
- sqlx::query("UPDATE questions SET message_id = ? WHERE id = ?").bind(message_id).bind(id).execute(&self.pool).await?;
- Ok(())
- }
-
/// Questions, newest first: by status and/or chat (channel, thread or direct-chat kwant id).
/// Newest first, at most 100; `space` keeps the questions of that space's kwants (all when `None`).
pub async fn list_questions(
diff --git a/src/db/skills.rs b/src/db/skills.rs
index 9918a000..b755105c 100644
--- a/src/db/skills.rs
+++ b/src/db/skills.rs
@@ -326,7 +326,7 @@ impl Database {
async fn check_skill_owner(&self, space: &SpaceId, kwant_id: Option<&str>) -> Result<(), SkillError> {
match kwant_id {
Some(id) if !self.kwants_in_space(space, &[id]).await? => {
- Err(SkillError::Invalid("that agent is in another space".into()))
+ Err(SkillError::Invalid("that bot is in another space".into()))
}
_ => Ok(()),
}
diff --git a/src/main.rs b/src/main.rs
index 86a47c95..25537ff1 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -14,7 +14,7 @@ use std::path::PathBuf;
use tokio_util::sync::CancellationToken;
#[derive(Parser, Debug)]
-#[command(name = "kwnt", author, version, about = "Kwants: Multi-Agent AI Platform in Rust")]
+#[command(name = "kwnt", author, version, about = "kwant bots: your team of AI bots")]
pub struct Cli {
#[command(subcommand)]
pub command: Option<Commands>,
@@ -162,7 +162,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
"Starting Kwant..."
);
println!(
- "⚡ Kwant: your team of super-intelligent bots (kwants), listening at http://{}",
+ "⚡ kwant bots: your team of super-intelligent bots, listening at http://{}",
addr
);
if !is_loopback_bind(&config.host) {
@@ -195,7 +195,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Some(Commands::McpEchoServer) => unreachable!("handled before config loading"),
Some(Commands::McpOauthMockServer { .. }) => unreachable!("handled before config loading"),
None => {
- println!("⚡ Kwant: your team of super-intelligent bots (kwants)");
+ println!("⚡ kwant bots: your team of super-intelligent bots");
println!("Run `kwnt serve` to start the server, or `kwnt --help` for options.");
}
}
@@ -243,7 +243,7 @@ fn print_status(config: &Config) {
format!("{} (absent)", config_path.display())
};
- println!("Kwant");
+ println!("kwant bots");
println!(" host {}", config.host);
println!(" port {}", config.port);
println!(" data dir {}", config.data_dir.display());
@@ -266,7 +266,7 @@ async fn print_agents(config: &Config) -> Result<(), Box<dyn std::error::Error>>
"NAME", "TITLE", "DRIVER"
);
if kwants.is_empty() {
- println!("(no agents)");
+ println!("(no bots)");
return Ok(());
}
for kwant in kwants {
diff --git a/src/router/team.rs b/src/router/team.rs
index ee45e124..0b227218 100644
--- a/src/router/team.rs
+++ b/src/router/team.rs
@@ -263,7 +263,7 @@ pub fn heuristic_pick_kwant<'a>(
Some((
lead,
format!(
- "No agent here lists skills matching this request, so {} ({}) is taking it as channel lead",
+ "No bot here lists skills matching this request, so {} ({}) is taking it as channel lead",
lead.name, lead.title
),
))
diff --git a/src/server/away.rs b/src/server/away.rs
index 1976546b..14565a60 100644
--- a/src/server/away.rs
+++ b/src/server/away.rs
@@ -155,7 +155,7 @@ fn item(row: AwayRow) -> Value {
"kind": row.kind,
"id": row.id,
"kwant_id": row.kwant_id,
- "kwant_name": row.kwant_name.unwrap_or_else(|| "An agent".into()),
+ "kwant_name": row.kwant_name.unwrap_or_else(|| "A bot".into()),
"title": title,
"summary": summary,
"status": row.status,
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 56ab834e..4c67498c 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -959,7 +959,7 @@ async fn kwant_name(state: &AppState, id: &str) -> String {
.ok()
.flatten()
.map(|k| k.name)
- .unwrap_or_else(|| "An agent".into())
+ .unwrap_or_else(|| "A bot".into())
}
async fn place(state: &AppState, context_id: Option<&str>) -> (Option<String>, String) {
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index 50c0c954..47bd4ee7 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -110,7 +110,7 @@ fn meta(kind: &str, d: &Delegation, specialist: &str) -> Value {
}
async fn name_of(state: &AppState, id: &str) -> String {
- state.db.get_kwant(id).await.ok().flatten().map(|k| k.name).unwrap_or_else(|| "An agent".into())
+ state.db.get_kwant(id).await.ok().flatten().map(|k| k.name).unwrap_or_else(|| "A bot".into())
}
// Starting
@@ -141,7 +141,7 @@ pub struct StartRequest {
pub async fn start(state: &AppState, req: StartRequest) -> Result<Delegation, (StatusCode, String)> {
let bad = |m: &str| Err((StatusCode::BAD_REQUEST, m.to_string()));
if req.lead.id == req.specialist.id {
- return bad("An agent can't delegate to itself.");
+ return bad("A bot can't delegate to itself.");
}
let task = req.task.trim();
if task.is_empty() {
@@ -471,7 +471,7 @@ async fn thread_view(state: &AppState, t: &Thread) -> Value {
pub async fn list_threads(State(state): State<AppState>, Path(kwant_id): Path<String>, Query(q): Query<ThreadsQuery>) -> Response {
match state.db.get_kwant(&kwant_id).await {
Ok(Some(_)) => {}
- Ok(None) => return error(StatusCode::NOT_FOUND, "agent not found"),
+ Ok(None) => return error(StatusCode::NOT_FOUND, "bot not found"),
Err(_) => return internal(),
}
let archived = matches!(q.include_archived.as_deref(), Some("1" | "true"));
@@ -497,7 +497,7 @@ pub async fn create_thread(
) -> Response {
match state.db.get_kwant(&kwant_id).await {
Ok(Some(_)) => {}
- Ok(None) => return error(StatusCode::NOT_FOUND, "agent not found"),
+ Ok(None) => return error(StatusCode::NOT_FOUND, "bot not found"),
Err(_) => return internal(),
}
let title = body.and_then(|b| b.0.title).filter(|t| !t.trim().is_empty()).unwrap_or_else(|| "New conversation".into());
@@ -576,7 +576,7 @@ pub struct DelegatePayload {
pub async fn create_delegation(State(state): State<AppState>, Json(p): Json<DelegatePayload>) -> Response {
let (lead, specialist) = match (state.db.get_kwant(&p.lead_kwant_id).await, state.db.get_kwant(&p.specialist_kwant_id).await) {
(Ok(Some(l)), Ok(Some(s))) => (l, s),
- (Ok(_), Ok(_)) => return error(StatusCode::NOT_FOUND, "agent not found"),
+ (Ok(_), Ok(_)) => return error(StatusCode::NOT_FOUND, "bot not found"),
_ => return internal(),
};
let origin_depth = match &p.thread_id {
@@ -643,7 +643,7 @@ pub async fn tool_delegate(state: &AppState, scope: &super::continuity::SelfScop
let to = args["to"].as_str().map(str::trim).unwrap_or("").trim_start_matches('@');
let task = args["task"].as_str().unwrap_or("").to_string();
let Some(lead) = state.db.get_kwant(&scope.kwant_id).await.ok().flatten() else {
- return ("Unknown agent.".into(), true);
+ return ("Unknown bot.".into(), true);
};
// Only the lead's own space, even when the chat has no member list
let kwants = state.db.list_kwants(&SpaceId::new(&lead.space_id)).await.unwrap_or_default();
@@ -654,7 +654,7 @@ pub async fn tool_delegate(state: &AppState, scope: &super::continuity::SelfScop
};
let Some(specialist) = kwants.iter().find(|k| k.id == to || k.name.eq_ignore_ascii_case(to)).cloned() else {
let names: Vec<&str> = pool.iter().map(|k| k.name.as_str()).collect();
- return (format!("No agent named '{to}'. You can delegate to: {}.", names.join(", ")), true);
+ return (format!("No bot named '{to}'. You can delegate to: {}.", names.join(", ")), true);
};
let req = StartRequest {
lead,
diff --git a/src/server/mcp_routes.rs b/src/server/mcp_routes.rs
index 1a2e303e..bb45b1c2 100644
--- a/src/server/mcp_routes.rs
+++ b/src/server/mcp_routes.rs
@@ -173,7 +173,7 @@ pub async fn test_server(State(state): State<AppState>, Path(id): Path<String>)
pub async fn get_kwant_servers(State(state): State<AppState>, Path(kwant_id): Path<String>) -> ApiResult<Value> {
if state.db.get_kwant(&kwant_id).await.map_err(db_err)?.is_none() {
- return Err(err(StatusCode::NOT_FOUND, "kwant not found"));
+ return Err(err(StatusCode::NOT_FOUND, "bot not found"));
}
let ids = state.db.get_kwant_mcp_server_ids(&kwant_id).await.map_err(db_err)?;
Ok(Json(json!({ "server_ids": ids })))
@@ -190,7 +190,7 @@ pub async fn set_kwant_servers(
Json(body): Json<AssignServers>,
) -> ApiResult<Value> {
let Some(space) = state.db.space_of_kwant(&kwant_id).await.map_err(db_err)? else {
- return Err(err(StatusCode::NOT_FOUND, "kwant not found"));
+ return Err(err(StatusCode::NOT_FOUND, "bot not found"));
};
// Only servers in the kwant's own space can be assigned to it
let known: Vec<String> = state.db.list_mcp_servers(&space).await.map_err(db_err)?.into_iter().map(|s| s.id).collect();
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index 44a87992..9d4e297e 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -327,7 +327,7 @@ async fn decide(session: &PermissionSession, args: &Value) -> Value {
let target = mcp::split_tool_name(tool_name)
.filter(|(server, _)| session.ctx.servers.iter().any(|s| s.name == *server));
let Some((server, tool)) = target else {
- return json!({"behavior": "deny", "message": format!("{tool_name} is not available to this kwant.")});
+ return json!({"behavior": "deny", "message": format!("{tool_name} is not available to this bot.")});
};
let approval = session.ctx.approver.approve(ToolApprovalRequest {
kwant_id: session.kwant_id.clone(),
diff --git a/src/server/questions.rs b/src/server/questions.rs
index 1937990d..5a65ed47 100644
--- a/src/server/questions.rs
+++ b/src/server/questions.rs
@@ -185,20 +185,41 @@ pub async fn tool_ask(state: &AppState, scope: &SelfScope, args: &Value) -> (Str
thread_id: origin.thread_id.clone(),
turn_id: scope.turn_id.clone(),
};
- let mut q = match state.db.create_question(&place, &question, &choices).await {
- Ok(q) => q,
- Err(QuestionError::Db) => return ("Could not save the question.".into(), true),
- Err(e) => return (e.to_string(), true),
- };
- // Waiting before the card exists, so a very fast answer can't miss the turn
+ // The question, its card and the waiter appear together: the waiter is registered inside the
+ // transaction, so neither a list poll nor a very fast answer can see one without the others.
+ // The text keeps the choices readable in history and for older clients; the card uses meta
let hub = &state.questions;
- let mut rx = hub.register(&q.id);
+ let mut waiter = None;
+ let created = state
+ .db
+ .create_question_with_card(&place, &question, &choices, |q| {
+ waiter = Some((q.id.clone(), hub.register(&q.id)));
+ let text = format!("{}\n\nChoices: {}", q.question, choices.join(" · "));
+ let (msg, extra) = place_message(q, "kwant", &scope.kwant_id, text);
+ Some((msg, MessageExtra { meta: Some(card_meta(q)), ..extra }))
+ })
+ .await;
+ let (q, card) = match created {
+ Ok(v) => v,
+ Err(e) => {
+ if let Some((id, _)) = waiter {
+ hub.take(&id);
+ }
+ return match e {
+ QuestionError::Db => ("Could not save the question.".into(), true),
+ e => (e.to_string(), true),
+ };
+ }
+ };
+ let Some((_, mut rx)) = waiter else {
+ return ("Could not save the question.".into(), true);
+ };
let _guard = WaiterGuard { hub, id: q.id.clone() };
- // The text keeps the choices readable in history and for older clients; the card uses meta
- let text = format!("{}\n\nChoices: {}", q.question, choices.join(" · "));
- if let Some(mid) = save_message(state, &q, "kwant", &scope.kwant_id, text, card_meta(&q)).await {
- let _ = state.db.set_question_message(&q.id, &mid).await;
- q.message_id = Some(mid);
+ if let Some(card) = card {
+ if let Some(t) = &q.thread_id {
+ let _ = state.db.touch_thread(t).await;
+ }
+ let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&card).unwrap_or(Value::Null) });
}
changed(state, &q).await;
notify(
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 45e292d4..c868e4c4 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -199,7 +199,7 @@ async fn ensure_general(state: &AppState, space: &SpaceId, lead: &str) {
}
let general = NewChannel {
name: "general".into(),
- description: Some("Everyone in this space. Laya picks who answers.".into()),
+ description: Some(crate::db::GENERAL_DESCRIPTION.into()),
lead_kwant_id: lead.to_string(),
member_kwants: vec![lead.to_string()],
routing_mode: "auto".into(),
@@ -542,7 +542,7 @@ pub(super) async fn scope_for(
) -> Result<TurnScope, String> {
// Teammates, the team and its folder all come from the kwant's own space
let space = SpaceId::new(&kwant.space_id);
- let all_kwants = state.db.list_kwants(&space).await.map_err(|_| "could not load agents".to_string())?;
+ let all_kwants = state.db.list_kwants(&space).await.map_err(|_| "could not load the bots".to_string())?;
let channel = match &channel_id {
Some(id) => Some(
state.db.get_channel(id).await.ok().flatten().ok_or_else(|| "the chat's channel no longer exists".to_string())?,
@@ -674,7 +674,7 @@ pub(super) async fn run_routine_turn(
Ok(reply_id)
}
Err(_) if job.token.is_cancelled() => Err("stopped by the user".into()),
- Err(why) => Err(format!("the agent's turn failed: {why}")),
+ Err(why) => Err(format!("the bot's turn failed: {why}")),
}
}
@@ -1622,7 +1622,31 @@ async fn chat_space(state: &AppState, payload: &SendChatPayload) -> Result<Space
pub async fn send_chat(
State(state): State<AppState>,
- Json(mut payload): Json<SendChatPayload>,
+ axum::extract::RawQuery(query): axum::extract::RawQuery,
+ Json(payload): Json<SendChatPayload>,
+) -> axum::response::Response {
+ use super::spaces::RowKind;
+ // An explicit ?space= must match every row the body names (a thread overrides the others)
+ let rows: Vec<(RowKind, Option<&str>)> = match payload.thread_id.as_deref() {
+ Some(t) => vec![(RowKind::Thread, Some(t))],
+ None => vec![
+ (RowKind::Channel, payload.channel_id.as_deref()),
+ (RowKind::Kwant, payload.kwant_id.as_deref()),
+ (RowKind::Team, payload.team_id.as_deref()),
+ ],
+ };
+ if let Err(r) = super::spaces::ids_guard(&state, query.as_deref(), &rows).await {
+ return r;
+ }
+ match send_chat_inner(state, payload).await {
+ Ok(json) => json.into_response(),
+ Err(status) => status.into_response(),
+ }
+}
+
+async fn send_chat_inner(
+ state: AppState,
+ mut payload: SendChatPayload,
) -> Result<Json<serde_json::Value>, StatusCode> {
let uploads = super::attachments::check_uploads(&state, &payload.attachment_ids).await?;
if let Some(thread_id) = payload.thread_id.clone() {
diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs
index ff64c15d..9e181b46 100644
--- a/src/server/scheduler.rs
+++ b/src/server/scheduler.rs
@@ -205,7 +205,7 @@ pub async fn create(
let explicit = super::spaces::space_param(uri.query()).is_some();
match state.db.space_of_kwant(&input.kwant_id).await {
Ok(Some(of)) if of == space || !explicit => {}
- Ok(_) => return error(StatusCode::BAD_REQUEST, "the agent is in another space"),
+ Ok(_) => return error(StatusCode::BAD_REQUEST, "the bot is in another space"),
Err(_) => return internal(),
}
match state.db.create_routine(&input).await {
@@ -393,12 +393,12 @@ async fn execute(state: &AppState, routine: &RoutineRow) -> Result<Option<String
.db
.get_kwant(&routine.kwant_id)
.await
- .map_err(|_| "could not load the agent".to_string())?
- .ok_or_else(|| "the routine's agent no longer exists".to_string())?;
+ .map_err(|_| "could not load the bot".to_string())?
+ .ok_or_else(|| "the routine's bot no longer exists".to_string())?;
// The API never makes a routine across spaces, but a row edited by hand must not run one
// space's bot in another space's chat
if kwant.space_id != routine.space_id {
- return Err("the routine's agent is in another space, so it was not run".into());
+ return Err("the routine's bot is in another space, so it was not run".into());
}
if state.db.space_archived(&crate::db::spaces::SpaceId::new(&routine.space_id)).await.unwrap_or(true) {
return Err("the routine's space is archived, so it was not run".into());
diff --git a/src/server/skills.rs b/src/server/skills.rs
index 6826544e..82b76603 100644
--- a/src/server/skills.rs
+++ b/src/server/skills.rs
@@ -344,7 +344,7 @@ pub async fn create(
if let (true, Some(Some(owner))) = (super::spaces::space_param(uri.query()).is_some(), &p.kwant_id) {
match state.db.space_of_kwant(owner).await {
Ok(Some(of)) if of == scope.0 => {}
- Ok(_) => return error(StatusCode::BAD_REQUEST, "that agent is in another space"),
+ Ok(_) => return error(StatusCode::BAD_REQUEST, "that bot is in another space"),
Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
}
}
diff --git a/src/server/spaces.rs b/src/server/spaces.rs
index 78363242..2c863e84 100644
--- a/src/server/spaces.rs
+++ b/src/server/spaces.rs
@@ -173,6 +173,25 @@ pub async fn row_guard(
next.run(req).await
}
+/// For a body that names rows instead of a path (`POST /api/chat/send`): with an explicit
+/// `?space=`, every named row that exists must live in that space, else 404 as in [`row_guard`].
+/// Unknown rows pass, so the handler answers as it always did; without `?space=` nothing is checked.
+pub async fn ids_guard(state: &AppState, query: Option<&str>, rows: &[(RowKind, Option<&str>)]) -> Result<(), Response> {
+ let Some(want) = space_param(query) else {
+ return Ok(());
+ };
+ let want = active_space(state, &want).await?;
+ for (kind, id) in rows {
+ let Some(id) = id else { continue };
+ match space_of_row(state, *kind, id).await {
+ Ok(Some(space)) if space != want => return Err(error(StatusCode::NOT_FOUND, "that isn't in this space")),
+ Ok(_) => {}
+ Err(_) => return Err(internal()),
+ }
+ }
+ Ok(())
+}
+
fn archived() -> Response {
error(StatusCode::CONFLICT, "this space is archived; restore it first")
}
diff --git a/tests/ask_user_test.rs b/tests/ask_user_test.rs
index f50a32da..7789a903 100644
--- a/tests/ask_user_test.rs
+++ b/tests/ask_user_test.rs
@@ -90,6 +90,30 @@ async fn ask_pauses_the_turn_and_a_choice_resumes_it() {
assert_eq!(s, StatusCode::CONFLICT);
}
+/// The question, its card and its waiting turn appear together: polled as fast as possible,
+/// the first sighting of an open question already has its card message and a live waiter.
+#[tokio::test]
+async fn a_question_is_never_visible_without_its_card_and_waiter() {
+ let env = setup().await;
+ send_direct(&env, &env.a, &format!("Go? {} REPLYTAG:r1", ask_marker("Deploy now?", &["yes", "no"])), json!({})).await;
+ let q = loop {
+ let (s, list) = call(&env.app, "GET", &format!("/api/questions?status=open&context_id={}", env.a), None).await;
+ assert_eq!(s, StatusCode::OK);
+ if let Some(q) = list.as_array().and_then(|l| l.first()) {
+ break q.clone();
+ }
+ tokio::task::yield_now().await;
+ };
+ let id = q["id"].as_str().unwrap().to_string();
+ let mid = q["message_id"].as_str().unwrap_or_else(|| panic!("open question without its card: {q}")).to_string();
+ assert!(question(&env, &id).await["waiting"].as_bool().unwrap(), "open question without a waiting turn");
+ assert!(messages(&env, &env.a).await.iter().any(|m| m.id == mid), "card message missing");
+ let (s, v) = call(&env.app, "POST", &format!("/api/questions/{id}/answer"), Some(json!({"choice": 0}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(v["resumed"], "turn", "an immediate answer resumes the waiting turn");
+ wait_reply(&env, &env.a, "answer r1").await;
+}
+
#[tokio::test]
async fn the_agent_keeps_working_elsewhere_while_it_waits() {
let env = setup().await;
diff --git a/tests/engine_login_test.rs b/tests/engine_login_test.rs
index 448c6a3a..a94061a3 100644
--- a/tests/engine_login_test.rs
+++ b/tests/engine_login_test.rs
@@ -222,7 +222,8 @@ async fn a_wrong_code_fails_without_echoing_cli_output_and_allows_a_retry() {
assert_eq!(v["state"], "failed", "{v}");
let detail = v["detail"].as_str().unwrap();
assert!(detail.contains("didn't accept that code"), "{v}");
- assert!(!v.to_string().contains("WRONGCODE999") && !v.to_string().contains("400"), "{v}");
+ // The CLI's HTTP status stays out of the text (not the whole body: a random session id can hold "400")
+ assert!(!v.to_string().contains("WRONGCODE999") && !detail.contains("400"), "{v}");
assert!(!env.home.join(".credentials.json").exists());
let (_, engines) = call(app, "GET", "/api/engines", None).await;
assert_ne!(claude_status(&engines), "ready");
diff --git a/tests/routine_failure_test.rs b/tests/routine_failure_test.rs
index 2a9a0e92..7385cd76 100644
--- a/tests/routine_failure_test.rs
+++ b/tests/routine_failure_test.rs
@@ -119,7 +119,7 @@ async fn failed_routine_run_records_the_engine_error() {
let id = r["id"].as_str().unwrap().to_string();
let error = run_once(&app, &id).await;
- assert!(error.starts_with("the agent's turn failed: "), "{error}");
+ assert!(error.starts_with("the bot's turn failed: "), "{error}");
assert!(error.contains("is signed out"), "{error}");
assert!(error.chars().count() <= 600, "{error}");
diff --git a/tests/spaces_isolation_test.rs b/tests/spaces_isolation_test.rs
index 82944194..97d94210 100644
--- a/tests/spaces_isolation_test.rs
+++ b/tests/spaces_isolation_test.rs
@@ -328,7 +328,7 @@ async fn delegation_without_a_member_list_stays_in_the_leads_space() {
};
let (text, is_error) = delegation::tool_delegate(&env.state, &scope, &json!({"to": "Remy", "task": "help"})).await;
assert!(is_error, "{text}");
- assert!(text.contains("No agent named 'Remy'"), "{text}");
+ assert!(text.contains("No bot named 'Remy'"), "{text}");
assert!(text.contains("Ada") && !text.contains("Remy."), "only B's bots are offered: {text}");
// The HTTP API, which takes ids: a specialist from another space is refused
diff --git a/tests/spaces_s2_fixes_test.rs b/tests/spaces_s2_fixes_test.rs
index d4721010..001bbfd4 100644
--- a/tests/spaces_s2_fixes_test.rs
+++ b/tests/spaces_s2_fixes_test.rs
@@ -588,3 +588,87 @@ async fn archiving_kills_a_running_cli_and_its_children_and_posts_nothing() {
assert!(posted.iter().all(|t| !t.contains("answer ok")), "{posted:?}");
assert!(env.state.turns.active_turns().is_empty());
}
+
+#[tokio::test]
+async fn chat_send_with_an_explicit_space_refuses_rows_of_another_space() {
+ let env = setup().await;
+ let app = &env.app;
+ let b = env.new_space("Side").await;
+ let bea = env.bot(&b, "Bea").await;
+ env.bot(&b, "Bob").await;
+ let remy = env.bot("spc_default", "Remy").await;
+ let b_general = env.general(&b).await;
+ let d_general = env.general("spc_default").await;
+ let team_id = ok(app, "POST", "/api/teams", Some(team("alpha", &remy, None))).await["id"].as_str().unwrap().to_string();
+ let thread_id = ok(app, "POST", &format!("/api/kwants/{remy}/threads"), Some(json!({"title": "t"}))).await["id"]
+ .as_str()
+ .unwrap()
+ .to_string();
+ let send = |target: Value, tag: &str| {
+ let mut body = json!({"prompt": format!("hello STRAY_{tag}"), "sender_id": "user"});
+ body.as_object_mut().unwrap().extend(target.as_object().unwrap().clone());
+ body
+ };
+
+ // Both directions, every kind of target: 404, nothing saved, no CLI turn
+ let cases = [
+ (b.clone(), json!({"channel_id": d_general}), "dch"),
+ (b.clone(), json!({"kwant_id": remy}), "dkw"),
+ (b.clone(), json!({"team_id": team_id}), "dtm"),
+ (b.clone(), json!({"thread_id": thread_id}), "dth"),
+ ("spc_default".to_string(), json!({"channel_id": b_general}), "bch"),
+ ("spc_default".to_string(), json!({"kwant_id": bea}), "bkw"),
+ ];
+ for (space, target, tag) in &cases {
+ let (s, v) = call(app, "POST", &format!("/api/chat/send?space={space}"), Some(send(target.clone(), tag))).await;
+ assert_eq!(s, StatusCode::NOT_FOUND, "?space={space} {target}: {v}");
+ assert_eq!(v["error"], "that isn't in this space", "{v}");
+ }
+ // A channel of this space with a kwant of the other is refused too
+ let (s, _) = call(app, "POST", &format!("/api/chat/send?space={b}"), Some(send(json!({"channel_id": b_general, "kwant_id": remy}), "mix"))).await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+ // An unknown space is the usual 404
+ let (s, _) = call(app, "POST", "/api/chat/send?space=nope", Some(send(json!({"kwant_id": remy}), "unk"))).await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ for ctx in [&b_general, &d_general, &remy, &bea, &thread_id] {
+ let msgs = ok(app, "GET", &format!("/api/channels/{ctx}/messages"), None).await;
+ let text = msgs.to_string();
+ assert!(!text.contains("STRAY_"), "a refused send was saved in {ctx}: {text}");
+ }
+ assert_eq!(invocations_with("STRAY_"), 0, "a refused send ran a CLI turn");
+
+ // Matching or missing ?space= still sends
+ ok(app, "POST", &format!("/api/chat/send?space={b}"), Some(send(json!({"kwant_id": bea}), "okb"))).await;
+ ok(app, "POST", "/api/chat/send?space=spc_default", Some(send(json!({"kwant_id": remy}), "okd"))).await;
+ ok(app, "POST", "/api/chat/send", Some(send(json!({"kwant_id": bea}), "okn"))).await;
+ env.idle().await;
+}
+
+#[tokio::test]
+async fn server_messages_say_bot_and_general_describes_the_space() {
+ let env = setup().await;
+ let app = &env.app;
+ let general = env.general("spc_default").await;
+ let c = ok(app, "GET", &format!("/api/channels/{general}"), None).await;
+ let desc = c["description"].as_str().or(c["channel"]["description"].as_str()).unwrap_or_default().to_string();
+ assert_eq!(desc, kwnt::db::GENERAL_DESCRIPTION, "{c}");
+
+ // An unedited old seed text is replaced on the next start; an edited one is kept
+ let pool = sqlx::SqlitePool::connect(&format!("sqlite://{}", env.data.join("kwnt.db").display())).await.unwrap();
+ sqlx::query("UPDATE channels SET description = 'Main collaboration hub for all agents' WHERE id = ?")
+ .bind(&general)
+ .execute(&pool)
+ .await
+ .unwrap();
+ Database::init(&env.data).await.unwrap();
+ let (d,): (String,) = sqlx::query_as("SELECT description FROM channels WHERE id = ?").bind(&general).fetch_one(&pool).await.unwrap();
+ assert_eq!(d, kwnt::db::GENERAL_DESCRIPTION);
+ sqlx::query("UPDATE channels SET description = 'Ours' WHERE id = ?").bind(&general).execute(&pool).await.unwrap();
+ Database::init(&env.data).await.unwrap();
+ let (d,): (String,) = sqlx::query_as("SELECT description FROM channels WHERE id = ?").bind(&general).fetch_one(&pool).await.unwrap();
+ assert_eq!(d, "Ours");
+
+ let (s, v) = call(app, "GET", "/api/kwants/nope/mcp-servers", None).await;
+ assert_eq!((s, v["error"].as_str()), (StatusCode::NOT_FOUND, Some("bot not found")), "{v}");
+}