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
Accept legacy tz names; record why a routine run failed
Lin (kwant bot)43bd3836016e
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex 7cbd43e9..32aef6ef 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -882,6 +882,11 @@ impl Driver for CliDriver {tokens = result.tokens();result.result}+ // A failed run with no output is an error, not an empty reply+ None if stdout.trim().is_empty() && !exit.is_some_and(|s| s.success()) => {+ let status = exit.and_then(|s| s.code()).map_or("a signal".to_string(), |c| format!("status {c}"));+ return Err(DriverError::Execution(format!("{bin_path} exited with {status} and no output")));+ }// Not JSON (an older claude): its plain text is the replyNone => stdout,}diff --git a/src/routines.rs b/src/routines.rsindex e801406e..12f3a10a 100644--- a/src/routines.rs+++ b/src/routines.rs@@ -76,8 +76,42 @@ impl Zone {}}-fn parse_tz(tz: &str) -> Result<Zone, String> {+/// Old IANA names (the tz `backward` links) that browsers' ICU still reports but some systems+/// (e.g. Ubuntu 24.04 without tzdata-legacy) no longer ship. Mirrors frontend/src/continuity.ts.+const LEGACY_TZ: &[(&str, &str)] = &[+ ("Africa/Asmera", "Africa/Asmara"),+ ("America/Buenos_Aires", "America/Argentina/Buenos_Aires"),+ ("America/Catamarca", "America/Argentina/Catamarca"),+ ("America/Cordoba", "America/Argentina/Cordoba"),+ ("America/Godthab", "America/Nuuk"),+ ("America/Indianapolis", "America/Indiana/Indianapolis"),+ ("America/Jujuy", "America/Argentina/Jujuy"),+ ("America/Louisville", "America/Kentucky/Louisville"),+ ("America/Mendoza", "America/Argentina/Mendoza"),+ ("Asia/Calcutta", "Asia/Kolkata"),+ ("Asia/Katmandu", "Asia/Kathmandu"),+ ("Asia/Rangoon", "Asia/Yangon"),+ ("Asia/Saigon", "Asia/Ho_Chi_Minh"),+ ("Atlantic/Faeroe", "Atlantic/Faroe"),+ ("Europe/Kiev", "Europe/Kyiv"),+ ("Pacific/Enderbury", "Pacific/Kanton"),+ ("Pacific/Ponape", "Pacific/Pohnpei"),+ ("Pacific/Truk", "Pacific/Chuuk"),+];++/// The current IANA name for `tz`, trimmed; unknown names pass through for `parse_tz` to judge.+pub fn canonical_tz(tz: &str) -> String {let name = tz.trim();+ LEGACY_TZ+ .iter()+ .find(|(old, _)| *old == name)+ .map_or(name, |(_, new)| new)+ .to_string()+}++fn parse_tz(tz: &str) -> Result<Zone, String> {+ let canonical = canonical_tz(tz);+ let name = canonical.as_str();let unknown = || format!("unknown time zone '{tz}'; use an IANA name like Europe/Kyiv");if name == "UTC" {return Ok(Zone(tz::TimeZone::utc()));@@ -119,6 +153,22 @@ fn parse_weekday(day: &str) -> Result<Weekday, String> {}impl Schedule {+ /// The same schedule with its time zone under its current IANA name, as it should be stored.+ pub fn canonical(self) -> Self {+ match self {+ Schedule::Daily { time, tz } => Schedule::Daily {+ time,+ tz: canonical_tz(&tz),+ },+ Schedule::Weekly { time, weekdays, tz } => Schedule::Weekly {+ time,+ weekdays,+ tz: canonical_tz(&tz),+ },+ other => other,+ }+ }+/// Checks every field; the API returns the message as a 400.pub fn validate(&self) -> Result<(), String> {match self {@@ -415,4 +465,50 @@ mod tests {assert!(parsed.validate().is_ok());assert!(serde_json::from_str::<Schedule>(r#"{"type":"daily","time":"07:30"}"#).is_err());}++ #[test]+ fn legacy_zone_names_are_accepted_and_stored_canonically() {+ for (old, new) in [("Europe/Kiev", "Europe/Kyiv"), ("Asia/Calcutta", "Asia/Kolkata")] {+ let s = Schedule::Daily {+ time: "09:00".into(),+ tz: format!(" {old} "),+ };+ assert!(s.validate().is_ok(), "{old}");+ let canonical = s.clone().canonical();+ assert_eq!(+ canonical,+ Schedule::Daily {+ time: "09:00".into(),+ tz: new.into()+ }+ );+ let after = utc("2026-10-17T00:00:00Z");+ assert_eq!(s.next_after(after, None), canonical.next_after(after, None));+ }+ let weekly = Schedule::Weekly {+ time: "09:00".into(),+ weekdays: vec!["mon".into()],+ tz: "Asia/Calcutta".into(),+ }+ .canonical();+ assert!(matches!(weekly, Schedule::Weekly { ref tz, .. } if tz == "Asia/Kolkata"));+ // Kyiv is UTC+3 in summer: 09:00 local is 06:00Z+ assert_eq!(+ Schedule::Daily {+ time: "09:00".into(),+ tz: "Europe/Kiev".into()+ }+ .next_after(utc("2026-07-01T00:00:00Z"), None),+ Some(utc("2026-07-01T06:00:00Z"))+ );+ assert_eq!(canonical_tz("Europe/Kyiv"), "Europe/Kyiv");+ assert_eq!(canonical_tz("Mars/Olympus"), "Mars/Olympus");+ // Aliasing never opens a path around the name checks+ assert!(Schedule::Daily {+ time: "09:00".into(),+ tz: "Europe/Kiev/../../../etc/passwd".into()+ }+ .validate()+ .is_err());+ }}diff --git a/src/server/routes.rs b/src/server/routes.rsindex 4bf39052..3b58bb05 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -490,9 +490,9 @@ pub(super) async fn run_routine_turn(teammates,cancel_token: cancel_token.clone(),};- let reply = run_kwant_turn(&scope, kwant, prompt.clone(), TurnOpts::default()).await;+ let reply = try_kwant_turn(&scope, kwant, prompt.clone(), TurnOpts::default()).await;let outcome = match reply {- Some(text) => {+ Ok(text) => {let context_id = keys[0].clone();let reply_id = state.db@@ -506,8 +506,8 @@ pub(super) async fn run_routine_turn(run_handoffs(&scope, std::slice::from_ref(&kwant.id), &[(kwant.clone(), text)], &prompt).await;Ok(reply_id)}- None if cancel_token.is_cancelled() => Err("stopped by the user".into()),- None => Err("the agent's turn failed".into()),+ Err(_) if cancel_token.is_cancelled() => Err("stopped by the user".into()),+ Err(why) => Err(format!("the agent's turn failed: {why}")),};let mut tokens = state.active_cancellations.lock().await;for key in &keys {@@ -727,6 +727,19 @@ async fn run_kwant_turn(prompt: String,opts: TurnOpts,) -> Option<String> {+ try_kwant_turn(scope, target_kwant, prompt, opts).await.ok()+}++/// Longest failure reason kept for a routine run's history.+const MAX_FAILURE_CHARS: usize = 500;++/// [`run_kwant_turn`], but a failed turn says why: the driver's error or the provider's refusal.+async fn try_kwant_turn(+ scope: &TurnScope,+ target_kwant: &Kwant,+ prompt: String,+ opts: TurnOpts,+) -> Result<String, String> {let context_id = scope.channel_id.clone()@@ -745,11 +758,33 @@ async fn run_kwant_turn(};let reply = run_kwant_turn_inner(scope, target_kwant, prompt, opts).await;ended.outcome = match (&reply, scope.cancel_token.is_cancelled()) {- (Some(_), _) => "completed",- (None, true) => "cancelled",- (None, false) => "failed",+ (Ok(_), _) => "completed",+ (Err(_), true) => "cancelled",+ (Err(_), false) => "failed",};- reply+ reply.map_err(|why| truncate_chars(&scrub_urls(why.trim()), MAX_FAILURE_CHARS).to_string())+}++/// `text` with every URL's userinfo and query dropped, so a failure reason that names a+/// custom endpoint can be stored without the credentials some endpoints carry there.+fn scrub_urls(text: &str) -> String {+ text.split(' ')+ .map(|word| {+ let Some(scheme_end) = word.find("://") else {+ return word.to_string();+ };+ let (scheme, rest) = word.split_at(scheme_end + 3);+ let host_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());+ let (authority, path) = rest.split_at(host_end);+ let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h);+ let path = match path.find(['?', '#']) {+ Some(q) => format!("{}?…", &path[..q]),+ None => path.to_string(),+ };+ format!("{scheme}{host}{path}")+ })+ .collect::<Vec<_>>()+ .join(" ")}struct TurnEndedGuard {@@ -774,7 +809,7 @@ async fn run_kwant_turn_inner(target_kwant: &Kwant,prompt: String,opts: TurnOpts,-) -> Option<String> {+) -> Result<String, String> {let state = &scope.state;let event_broadcast = state.event_sender.clone();let db = state.db.clone();@@ -1117,18 +1152,20 @@ async fn run_kwant_turn_inner(};if cancelled {let _ = event_broadcast.send(RuntimeEvent::ThinkingDelta("⏹️ Cancelled by user".into()));+ return Err("stopped by the user".into());} else if let Some(text) = gave_up {let msg = NewMessage {channel_id: channel_id.clone(),direct_kwant_id: kwant_id.clone(),sender_role: "kwant".into(),sender_id: target_kwant.name.clone(),- text,+ text: text.clone(),reasoning_content: with_notices(opts.label.clone()),tool_calls: None,tokens_used: 0,};let _ = db.insert_message(&msg).await;+ return Err(text);} else if let Some(Ok(Ok(output))) = driver_result {// Post-turn sync: If bot response outputs a URL, sync navigation so the user sees it in Sandbox VMif let Some(bot_url) = extract_url_from_text(&output.text) {@@ -1182,9 +1219,13 @@ async fn run_kwant_turn_inner(};let _ = db.insert_message(&asst_msg).await;}- return Some(output.text);+ return Ok(output.text);}- None+ Err(match driver_result {+ Some(Ok(Err(e))) => format!("the {target_model} driver failed: {e}"),+ Some(Err(_)) => format!("the {target_model} driver stopped unexpectedly"),+ _ => format!("the {target_model} turn ended without a reply"),+ })}}@@ -2525,3 +2566,18 @@ pub async fn delete_password(}}++#[cfg(test)]+mod tests {+ use super::scrub_urls;++ #[test]+ fn failure_reasons_drop_url_credentials() {+ assert_eq!(+ scrub_urls("HTTP API error: error sending request for url (https://u:[email protected]/v1/chat?key=sk-123&x=1)"),+ "HTTP API error: error sending request for url (https://llm.example/v1/chat?…"+ );+ assert_eq!(scrub_urls("see http://host:8080/a#frag now"), "see http://host:8080/a?… now");+ assert_eq!(scrub_urls("not logged in; run `codex login`"), "not logged in; run `codex login`");+ }+}diff --git a/src/server/scheduler.rs b/src/server/scheduler.rsindex 45e0f687..d28076b6 100644--- a/src/server/scheduler.rs+++ b/src/server/scheduler.rs@@ -142,6 +142,7 @@ async fn build(.ok_or_else(|| bad("schedule is required"))?,};schedule.validate().map_err(|m| bad(&m))?;+ let schedule = schedule.canonical();let enabled = p.enabled.or(existing.map(|e| e.enabled)).unwrap_or(true);let next_run_at = if enabled {schedule.next_after(Utc::now(), existing.and_then(|e| e.last_run_at))diff --git a/tests/routine_failure_test.rs b/tests/routine_failure_test.rsnew file mode 100644index 00000000..db294cf7--- /dev/null+++ b/tests/routine_failure_test.rs@@ -0,0 +1,152 @@+//! A routine whose engine can't run records why in its history, not just that it failed. Uses a+//! signed-out fake claude CLI on PATH, so it is its own test binary: it changes the process env.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::Database,+ router::LayaRouter,+ server::{create_router, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::time::Duration;+use tower::ServiceExt;++/// Signed out, as the real CLI reports it; or, with `$CRASH` set, dying with no output at all.+const FAKE_CLAUDE: &str = r#"#!/bin/sh+case "$1" in+ auth) echo '{"loggedIn":false}'; exit 1 ;;+esac+[ -f "$CRASH" ] && exit 3+echo '{"type":"result","is_error":true,"num_turns":1,"result":"Invalid API key · Please run /login"}'+exit 1+"#;++async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {+ let resp = app+ .clone()+ .oneshot(+ Request::builder()+ .method(method)+ .uri(uri)+ .header("content-type", "application/json")+ .body(+ body.map(|v| Body::from(v.to_string()))+ .unwrap_or_else(Body::empty),+ )+ .unwrap(),+ )+ .await+ .unwrap();+ let s = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (s, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++#[tokio::test]+async fn failed_routine_run_records_the_engine_error() {+ let tmp = tempfile::tempdir().unwrap();+ let bin = tmp.path().join("bin");+ std::fs::create_dir_all(&bin).unwrap();+ let fake = bin.join("claude");+ std::fs::write(&fake, FAKE_CLAUDE).unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ let crash = tmp.path().join("crash");+ std::env::set_var("CRASH", &crash);+ std::env::set_var(+ "PATH",+ format!(+ "{}:{}",+ bin.display(),+ std::env::var("PATH").unwrap_or_default()+ ),+ );++ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ // Laya is unreachable: routing falls back to the kwant's preferred model+ let config = Config {+ data_dir: data.clone(),+ laya_url: "http://127.0.0.1:9".into(),+ browser_cdp_url: Some("http://127.0.0.1:9".into()),+ ..Config::default()+ };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(data.join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ let app = create_router(state.clone());++ let (_, kwants) = call(&app, "GET", "/api/kwants", None).await;+ let k = kwants[0].clone();+ let kid = k["id"].as_str().unwrap().to_string();+ let mut body = k.clone();+ body.as_object_mut().unwrap().retain(|key, _| {+ ["name", "title", "persona_prompt", "soul", "avatar_sprite"].contains(&key.as_str())+ });+ body["preferred_model"] = json!("claude");+ let (s, v) = call(&app, "PUT", &format!("/api/kwants/{kid}"), Some(body)).await;+ assert_eq!(s, StatusCode::OK, "{v}");++ let (s, r) = call(+ &app,+ "POST",+ "/api/routines",+ Some(json!({+ "kwant_id": kid,+ "name": "Digest",+ "instructions": "Summarise yesterday.",+ "schedule": {"type": "daily", "time": "09:00", "tz": "Europe/Kiev"},+ })),+ )+ .await;+ assert_eq!(s, StatusCode::CREATED, "{r}");+ // Stored under the current name, so the schedule survives a host without tzdata-legacy+ assert_eq!(r["schedule"]["tz"], "Europe/Kyiv");+ 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.contains("is signed out"), "{error}");+ assert!(error.chars().count() <= 600, "{error}");++ // A CLI that dies silently used to be recorded as an ok run with an empty reply+ std::fs::write(&crash, "").unwrap();+ let error = run_once(&app, &id).await;+ assert!(error.contains("exited with status 3 and no output"), "{error}");+}++/// Runs the routine now and returns the run's error, which it must have.+async fn run_once(app: &Router, id: &str) -> String {+ let (_, before) = call(app, "GET", &format!("/api/routines/{id}/runs"), None).await;+ let seen = before.as_array().map_or(0, Vec::len);+ let (s, _) = call(app, "POST", &format!("/api/routines/{id}/run"), None).await;+ assert_eq!(s, StatusCode::ACCEPTED);+ let run = tokio::time::timeout(Duration::from_secs(60), async {+ loop {+ let (_, runs) = call(app, "GET", &format!("/api/routines/{id}/runs"), None).await;+ let runs = runs.as_array().cloned().unwrap_or_default();+ if let Some(run) = runs.first().filter(|r| runs.len() > seen && r["status"] != "running") {+ return run.clone();+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ })+ .await+ .expect("routine run did not finish");+ assert_eq!(run["status"], "error", "{run}");+ run["error"].as_str().unwrap_or_default().to_string()+}