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
Attribution by chat, and bots save corrections that would apply again (#259)
Oleksandr Ivanchenkoe3974321a963
diff --git a/src/db/performance.rs b/src/db/performance.rsindex 939d2610..83a3d3b6 100644--- a/src/db/performance.rs+++ b/src/db/performance.rs@@ -13,7 +13,7 @@ use std::collections::HashMap;const BACKFILL_DONE: &str = "performance_backfill_v1";/// One model call of the owner: model, fresh input, output, cost, when.-type UsageRow = (String, i64, i64, Option<f64>, DateTime<Utc>);+type UsageRow = (i64, String, String, i64, i64, Option<f64>, DateTime<Utc>);#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]pub struct Observation {@@ -170,39 +170,50 @@ impl Database {return Ok(None);};// Claims: the windows a bot held the task (an open one ends at the settle)- let claims: Vec<(i64, Option<i64>)> =- sqlx::query_as("SELECT claimed_at, released_at FROM agent_claims WHERE task_id = ? ORDER BY claimed_at").bind(&t.id).fetch_all(&self.pool).await?;+ let claims: Vec<(i64, Option<i64>, Option<String>)> =+ sqlx::query_as("SELECT claimed_at, released_at, context_id FROM agent_claims WHERE task_id = ? ORDER BY claimed_at").bind(&t.id).fetch_all(&self.pool).await?;if claims.is_empty() && result == "unverified" {return Ok(None);}let end_ms = finished_at.timestamp_millis();- let windows: Vec<(i64, i64)> = claims.iter().map(|&(a, b)| (a, b.unwrap_or(end_ms).max(a))).collect();+ let windows: Vec<(i64, i64)> = claims.iter().map(|(a, b, _)| (*a, b.unwrap_or(end_ms).max(*a))).collect();let latency_ms = windows.iter().map(|(a, b)| b - a).sum();let started_at = windows.first().and_then(|(a, _)| DateTime::<Utc>::from_timestamp_millis(*a));- // Model and cost: the owner's model calls inside the claim windows+ // Model and cost: the owner's model calls inside the claim windows. In a window whose claim+ // knows its chat (`context_id`), only that chat's calls count when there are any: another+ // chat turn of the same bot, or a second running mission, is not this task's spend. A claim+ // with no context, or whose context has no call in the window, falls back to the whole window.let (mut by_model, mut cost, mut any_cost) = (HashMap::<String, i64>::new(), 0.0, false);if let (Some(first), Some(last)) = (windows.iter().map(|w| w.0).min(), windows.iter().map(|w| w.1).max()) {// A second of slack on each side for the stored time format; the windows decide belowlet from = DateTime::<Utc>::from_timestamp_millis(first - 1000).unwrap_or(finished_at);let to = DateTime::<Utc>::from_timestamp_millis(last + 1000).unwrap_or(finished_at);let calls: Vec<UsageRow> = sqlx::query_as(- "SELECT model, fresh_input, output, cost_usd, created_at FROM model_usage WHERE kwant_id = ? AND created_at >= ? AND created_at <= ?",+ "SELECT id, context_id, model, fresh_input, output, cost_usd, created_at FROM model_usage WHERE kwant_id = ? AND created_at >= ? AND created_at <= ?",).bind(&kwant_id).bind(from).bind(to).fetch_all(&self.pool).await?;- for (model, fresh, output, c, at) in calls {- let ms = at.timestamp_millis();- if !windows.iter().any(|(a, b)| ms >= *a && ms <= *b) {- continue;- }- *by_model.entry(model).or_default() += fresh + output;- if let Some(c) = c {- cost += c;- any_cost = true;+ let mut counted = std::collections::HashSet::new();+ for ((a, b), (_, _, claim_context)) in windows.iter().zip(&claims) {+ let inside: Vec<&UsageRow> = calls.iter().filter(|c| (*a..=*b).contains(&c.6.timestamp_millis())).collect();+ let own: Vec<&UsageRow> = match claim_context {+ Some(ctx) => inside.iter().copied().filter(|c| &c.1 == ctx).collect(),+ None => vec![],+ };+ // A call inside two windows (a system claim over a bot's own) counts once+ for (id, _, model, fresh, output, c, _) in if own.is_empty() { inside } else { own } {+ if !counted.insert(*id) {+ continue;+ }+ *by_model.entry(model.clone()).or_default() += fresh + output;+ if let Some(c) = c {+ cost += c;+ any_cost = true;+ }}}}diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex dd37ccdb..887b844c 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -141,8 +141,9 @@ pub async fn prompt_block([How to work]\n\- Never tell the person to do what your tools can do; do it now. Hand over only the rest.\n\- Check with the list or search tools before stating what exists or was done. Never claim an action you didn't take.\n\- - When the person reveals a lasting preference or fact (diet, goals, schedule), save it with `memory_add` without \- asking, and apply your notes unasked later.\n\+ - When the person reveals a lasting preference or fact (diet, goals, schedule), or corrects how you did something in \+ a way that would apply again (\"use a table\", \"always cc Sam\"), save it with `memory_add` without asking, and apply \+ your notes unasked later.\n\- Be proactive: after the asked work, do the obvious next step. Add one concrete extra the person would \clearly want: a shopping list with a meal plan; with a new routine, a sample of what it will send (a \motivation, the reminder's checklist); a monthly routine that sends a report you wrote. When a plan has \diff --git a/tests/fixtures/truth_ledger_off_prompt_895a96c.txt b/tests/fixtures/truth_ledger_off_prompt.txtsimilarity index 97%rename from tests/fixtures/truth_ledger_off_prompt_895a96c.txtrename to tests/fixtures/truth_ledger_off_prompt.txtindex 69ff83f1..b2319b82 100644--- a/tests/fixtures/truth_ledger_off_prompt_895a96c.txt+++ b/tests/fixtures/truth_ledger_off_prompt.txt@@ -21,7 +21,7 @@ If you have the `kwnt_tools` tools:[How to work]- Never tell the person to do what your tools can do; do it now. Hand over only the rest.- Check with the list or search tools before stating what exists or was done. Never claim an action you didn't take.-- When the person reveals a lasting preference or fact (diet, goals, schedule), save it with `memory_add` without asking, and apply your notes unasked later.+- When the person reveals a lasting preference or fact (diet, goals, schedule), or corrects how you did something in a way that would apply again ("use a table", "always cc Sam"), save it with `memory_add` without asking, and apply your notes unasked later.- Be proactive: after the asked work, do the obvious next step. Add one concrete extra the person would clearly want: a shopping list with a meal plan; with a new routine, a sample of what it will send (a motivation, the reminder's checklist); a monthly routine that sends a report you wrote. When a plan has a start date or deadline, schedule a check-in with `follow_up_create` a few days in.- Research before you ask: first try your tools (the named site and its pricing and docs pages, web search, files, notes, earlier chats). Ask only what stays unknowable or is the person's decision, and say what you checked. Told you could have looked it up? Look it up now.- For a reversible choice (wording, order, a setting that can change later), don't `ask_user`: pick, state the assumption in your reply and continue. Ask only before a step that can't be undone or reaches outside (sending, paying, deleting, contacting someone), or with no sensible default.diff --git a/tests/performance_test.rs b/tests/performance_test.rsindex 80961b95..d1364569 100644--- a/tests/performance_test.rs+++ b/tests/performance_test.rs@@ -355,3 +355,66 @@ async fn insights_counts_verified_tasks_per_week_and_cost_per_verified_outcome()// The old fields are unchangedassert_eq!(v["verified_7d"], 2);}++/// One model call of the bot, `fresh` + 100 output tokens, in chat `context`.+async fn call_in(e: &Env, context: &str, model: &str, fresh: i64, cost: f64) {+ e.state+ .db+ .record_usage(&NewUsage {+ kwant_id: e.bot.id.clone(),+ context_id: context.into(),+ purpose: kwnt::db::usage::PURPOSE_REPLY,+ model: model.into(),+ fresh_input: fresh,+ output: 100,+ reported: true,+ cost_usd: Some(cost),+ ..Default::default()+ })+ .await+ .unwrap();+}++/// A task the bot takes in `context` (`None`: a claim that doesn't know its chat), then fails.+async fn run_task(e: &Env, title: &str, context: Option<&str>, calls: impl std::future::Future<Output = ()>) -> kwnt::db::performance::Observation {+ let tid = id(&person(e, "POST", "/api/tasks", Some(json!({"title": title, "owner_kwant_id": e.bot.id}))).await);+ let claimed = e.state.db.claim_task(&tid, &e.bot.id, None, context, 600_000, false, "kwant").await.unwrap();+ assert!(claimed.is_ok(), "{:?}", claimed.err());+ tokio::time::sleep(Duration::from_millis(1100)).await; // the stored time has a second's grain+ calls.await;+ missions::transition(&e.state, &tid, "working", "failed", missions::Actor::Kwant, "kwant", TaskChange::default()).await.unwrap();+ observed(e, &tid, "failed").await+}++#[tokio::test]+async fn a_chat_turn_during_the_claim_is_not_billed_to_the_task() {+ let e = setup().await;+ // The task runs in its own context; the same bot also answers in #general during the claim+ let o = run_task(&e, "Own context", Some("mission-ctx"), async {+ call_in(&e, "mission-ctx", "claude-opus-5-5", 900, 0.25).await;+ call_in(&e, &e.general, "grok-4", 5000, 9.0).await;+ call_in(&e, "mission-ctx", "claude-opus-5-5", 400, 0.10).await;+ })+ .await;+ assert_eq!(o.model, "claude-opus-5-5", "the chat's model must not win: {o:?}");+ assert_eq!(o.cost_usd.map(|c| (c * 100.0).round() as i64), Some(35), "only the task's calls cost: {o:?}");+}++#[tokio::test]+async fn a_claim_with_no_context_or_no_matching_call_uses_the_whole_window() {+ let e = setup().await;+ // No context on the claim (the task_claim tool has none): the window decides, as before+ let o = run_task(&e, "No context", None, async {+ call_in(&e, "chat-a", "claude-opus-5-5", 900, 0.25).await;+ call_in(&e, "chat-b", "claude-opus-5-5", 100, 0.05).await;+ })+ .await;+ assert_eq!(o.cost_usd.map(|c| (c * 100.0).round() as i64), Some(30), "{o:?}");++ // A context that no call carries (a turn recorded under another id): the window decides too+ let o = run_task(&e, "Unmatched context", Some("never-used"), async {+ call_in(&e, "chat-a", "claude-opus-5-5", 900, 0.25).await;+ })+ .await;+ assert_eq!(o.cost_usd.map(|c| (c * 100.0).round() as i64), Some(25), "{o:?}");+}diff --git a/tests/truth_ledger_on_test.rs b/tests/truth_ledger_on_test.rsindex 64f8d9b3..c130530d 100644--- a/tests/truth_ledger_on_test.rs+++ b/tests/truth_ledger_on_test.rs@@ -2,7 +2,7 @@//! ledger and labelled, the deterministic contradiction scan opens disputes ("4 GB" vs "12 GB";//! not paraphrases), a dispute is settled by the person or by a passing kwant-run check, tasks//! that rely on a disputed fact land in Needs you, and `off`/`shadow` stay byte-identical to main-//! (fixtures/truth_ledger_off_prompt_895a96c.txt).+//! (fixtures/truth_ledger_off_prompt.txt).//! Contract: docs/mission-control.md §21.use axum::{@@ -247,10 +247,12 @@ async fn off_and_shadow_prompts_are_byte_identical_and_switching_off_restores_thtool(&e, &token, "memory_add", json!({"text": "Read on a web page"})).await;let off = prompt(&e, &a).await;- // Off is main's prompt, not just this build's: the fixture is this exact setup's prompt on- // main 895a96c (before C2), with ids as {id}- let golden = include_str!("fixtures/truth_ledger_off_prompt_895a96c.txt");- assert_eq!(without_ids(&off), golden, "off differs from main's prompt");+ // Off is today's prompt, not just this build's: the fixture is this exact setup's prompt (with+ // ids as {id}), first taken on main 895a96c before C2 and updated only when the prompt itself+ // changes on main. It last changed for the chat-correction sentence (0.6.8, after c9d5cd7).+ // The off == shadow == fixture check proves the ledger setting adds nothing to the prompt.+ let golden = include_str!("fixtures/truth_ledger_off_prompt.txt");+ assert_eq!(without_ids(&off), golden, "off differs from today's prompt");ledger(&e, "shadow").await;assert_eq!(prompt(&e, &a).await, off, "shadow is today's prompt");// Off and shadow: no dispute is opened, no fact tool offered