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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Only promise kwnt's app tools when their server really started
Lin (kwant bot)516db0fa79a9
diff --git a/src/drivers/api.rs b/src/drivers/api.rsindex 6104acef..a0a5e187 100644--- a/src/drivers/api.rs+++ b/src/drivers/api.rs@@ -1183,7 +1183,7 @@ impl ApiDriver {impl Driver for ApiDriver {async fn stream_turn(&self,- input: TurnInput,+ mut input: TurnInput,event_tx: mpsc::Sender<RuntimeEvent>,) -> Result<TurnOutput, DriverError> {let start = Instant::now();@@ -1204,15 +1204,9 @@ impl Driver for ApiDriver {// If target is a real live API endpoint with API key or local Ollama, call HTTP streamingif api_key.is_some() || is_ollama(target_model) || custom {- // An API turn has no shell: the browser is reachable only through the tools- let browser = if input.has_self_tools() {- super::BrowserAccess::Tools- } else {- super::BrowserAccess::Unavailable- };let anthropic = is_anthropic(&url);- let parts = input.system_prompt_parts(browser);- let effort = input.effort_level.as_deref().unwrap_or("medium");+ let effort_owned = input.effort_level.clone().unwrap_or_else(|| "medium".into());+ let effort = effort_owned.as_str();let max_tokens = match effort {"low" => 512,"high" => 4096,@@ -1228,18 +1222,32 @@ impl Driver for ApiDriver {Ok(m) => m,Err(why) => return Err(DriverError::Execution(why)),};- let mcp = input.mcp.as_ref();- let session = match mcp {+ let mut self_failed = false;+ let session = match input.mcp.as_ref() {Some(ctx) => {let cwd = input.workspace_dir.as_deref().filter(|d| d.exists());let (session, problems) = McpToolSession::open(ctx, cwd).await;+ let own = format!("{}:", crate::mcp::SELF_SERVER_NAME);for problem in problems {+ self_failed |= problem.starts_with(&own);let _ = event_tx.send(RuntimeEvent::ThinkingDelta(format!("MCP server unavailable: {problem}"))).await;}Some(session)}None => None,};+ // The prompt promises kwnt's tools only once they really started+ if self_failed {+ input.drop_app_tools();+ }+ // An API turn has no shell: the browser is reachable only through the tools+ let browser = if input.has_self_tools() {+ super::BrowserAccess::Tools+ } else {+ super::BrowserAccess::Unavailable+ };+ let parts = input.system_prompt_parts(browser);+ let mcp = input.mcp.as_ref();let request = ChatRequest {url: &url,api_key: api_key.as_deref(),diff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex 37136fd5..4f5c1759 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -973,7 +973,7 @@ impl Driver for CliDriver {"invoking local CLI");- let system_prompt = input.format_system_prompt();+ let mut system_prompt = input.format_system_prompt();let effective_prompt = build_cli_prompt(&input);// Prevent CLI tools from spawning desktop browser windows on host@@ -1162,6 +1162,11 @@ impl Driver for CliDriver {}Err(e) => {tracing::warn!(error = %e, "could not write MCP config; running without MCP");+ // Without the config no tool server starts: don't promise kwnt's tools+ let mut bare = input.clone();+ bare.drop_app_tools();+ bare.mcp = None;+ system_prompt = bare.format_system_prompt();let _ = event_tx.send(RuntimeEvent::ThinkingDelta("MCP tools are unavailable this turn (config file error).".into())).await;diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex 8a5e5caa..b252bc3e 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -219,7 +219,31 @@ pub enum BrowserAccess {Unavailable,}+/// Where the instructions for kwnt's own tools start in `TurnInput::continuity`+/// (see `server::continuity::prompt_block`); everything from here on assumes the tools work.+pub const APP_TOOLS_MARKER: &str = "\n\n[Your tools for continuity]";++/// Replaces the tool instructions when kwnt's tools server didn't start for a turn.+pub const NO_APP_TOOLS_NOTE: &str = "\n\n[Your app tools]\n\+ Your kwant app tools didn't start this turn, so you can't save notes, schedule routines or follow-ups, delegate, share \+ files, ask the person through a card or change any settings right now. Don't say you did any of these. If the person \+ asks for one, tell them plainly it didn't work this time and that they can try again in a moment.";+impl TurnInput {+ /// For a turn whose kwnt tools server failed to start: drop it from the turn and swap the+ /// prompt's tool instructions for a plain note that they are unavailable.+ pub fn drop_app_tools(&mut self) {+ if let Some(ctx) = &mut self.mcp {+ ctx.servers.retain(|s| s.name != crate::mcp::SELF_SERVER_NAME);+ }+ if let Some(at) = self.continuity.find(APP_TOOLS_MARKER) {+ self.continuity.truncate(at);+ }+ if !self.continuity.contains(NO_APP_TOOLS_NOTE) {+ self.continuity.push_str(NO_APP_TOOLS_NOTE);+ }+ }+/// Whether kwnt's own tools server (which carries the `browser_*` tools) is attached.pub fn has_self_tools(&self) -> bool {self.mcp@@ -599,6 +623,17 @@ mod tests {}}+ #[test]+ fn dropping_app_tools_swaps_their_instructions_for_a_note() {+ let mut i = input();+ i.continuity = format!("\n\n[Your notes]\n- likes tea{APP_TOOLS_MARKER}\n- `routine_create` schedules it");+ i.drop_app_tools();+ assert!(i.continuity.contains("likes tea") && !i.continuity.contains("routine_create"), "{}", i.continuity);+ assert!(i.continuity.ends_with(NO_APP_TOOLS_NOTE));+ i.drop_app_tools();+ assert_eq!(i.continuity.matches("didn't start this turn").count(), 1);+ }+#[test]fn every_turn_is_told_it_is_a_kwant_bot_not_its_engine() {for access in [BrowserAccess::Tools, BrowserAccess::Shell, BrowserAccess::Unavailable] {diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 6541a975..5f86ff16 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -89,8 +89,9 @@ pub async fn prompt_block(let memories = db.list_memories(&kwant.id).await.unwrap_or_default();out.push_str(&memory_block(&memories, with_tools));if with_tools {+ out.push_str(crate::drivers::APP_TOOLS_MARKER);out.push_str(&format!(- "\n\n[Your tools for continuity]\n\+ "\n\If you have the `{SELF_SERVER_NAME}` tools:\n\- `search_history` finds earlier messages in chats you can see; use it when the user refers to something said before that isn't in this conversation.\n\- `memory_add`, `memory_update` and `memory_remove` keep your notes. Save only durable facts worth knowing in later chats \diff --git a/tests/mcp_api_loop_test.rs b/tests/mcp_api_loop_test.rsindex 3008bd5a..55bcb631 100644--- a/tests/mcp_api_loop_test.rs+++ b/tests/mcp_api_loop_test.rs@@ -322,3 +322,37 @@ async fn anthropic_tool_calls_go_through_the_approver() {assert_eq!(last["content"][0]["content"], "The user denied this tool call.");assert_eq!(c.take_records()[0]["status"], "denied");}++/// The system prompt of the model's first request.+fn system_prompt(mock: &Mock) -> String {+ let requests = mock.requests.lock().unwrap();+ requests[0]["messages"].as_array().unwrap().iter().filter(|m| m["role"] == "system").map(|m| m["content"].to_string()).collect()+}++fn with_app_tools(server: McpServer) -> TurnInput {+ let mut c = ctx(Arc::new(FixedApprover(true)), 10, 8);+ c.servers = vec![McpServer { name: kwnt::mcp::SELF_SERVER_NAME.into(), ..server }];+ let mut i = input(Some(c));+ i.continuity = format!("\n\n[Your notes]\n- likes tea{}\n- `routine_create` schedules it", kwnt::drivers::APP_TOOLS_MARKER);+ i+}++#[tokio::test]+async fn app_tools_that_fail_to_start_are_not_promised() {+ let broken = McpServer { command: Some("/nonexistent/kwnt-tools".into()), ..echo_server(5) };+ let (url, mock) = start_mock(vec![answer("I can't schedule that right now.")]).await;+ let (out, events) = run(url, with_app_tools(broken)).await;+ assert_eq!(out.text, "I can't schedule that right now.");+ let system = system_prompt(&mock);+ assert!(!system.contains("routine_create"), "{system}");+ assert!(system.contains("likes tea") && system.contains("Your kwant app tools didn't start this turn"), "{system}");+ assert!(system.contains("You have no kwant tools this turn"), "{system}");+ assert!(mock.requests.lock().unwrap()[0].get("tools").is_none_or(|t| t.as_array().is_none_or(|a| a.is_empty())));+ assert!(events.iter().any(|e| matches!(e, RuntimeEvent::ThinkingDelta(t) if t.contains("MCP server unavailable"))));++ // A server that starts keeps the instructions+ let (url, mock) = start_mock(vec![answer("ok")]).await;+ run(url, with_app_tools(echo_server(5))).await;+ let system = system_prompt(&mock);+ assert!(system.contains("routine_create") && !system.contains("didn't start this turn"), "{system}");+}