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
//! The mission runner: on each scheduler tick (and `POST /api/missions/:id/run`) it claims the
//! highest-priority ready task of an active mission for its owner and runs one hidden turn on it.
//! At most one runner turn per mission and [`MAX_RUNNING`] server-wide.
use super::{lease_ms, transition, Actor};
use crate::db::missions::{ClaimRefused, Mission, Task, TaskChange};
use crate::server::busy_retry::{self, Slot as BusySlot};
use crate::server::routes::{scope_for, turn_once, TurnOpts};
use crate::server::AppState;
use std::collections::HashSet;
use std::future::Future;
use std::sync::{Arc, Mutex};
pub const MAX_RUNNING: usize = 2;
pub const PURPOSE: &str = "mission";
/// C0: the brief's sentence when the task has an approved check.
pub const SELF_CHECK: &str = "Before you move it to review, run these checks yourself with task_request_check and fix what fails.\n";
/// Missions with a runner turn going, one set per server (`AppState::mission_runs`), so two
/// servers in one process (as tests run them) never take each other's slots.
#[derive(Default)]
pub struct RunningMissions(Mutex<HashSet<String>>);
impl RunningMissions {
fn set(&self) -> std::sync::MutexGuard<'_, HashSet<String>> {
self.0.lock().unwrap_or_else(|e| e.into_inner())
}
}
/// Holds a mission's runner slot; frees it when dropped.
struct Slot(Arc<RunningMissions>, String);
impl Slot {
fn take(running: &Arc<RunningMissions>, mission_id: &str) -> Result<Slot, &'static str> {
let mut set = running.set();
if set.contains(mission_id) {
return Err("a runner turn is already going for this mission");
}
if set.len() >= MAX_RUNNING {
return Err("two missions are already running; it starts when one finishes");
}
set.insert(mission_id.to_string());
Ok(Slot(running.clone(), mission_id.to_string()))
}
}
impl Drop for Slot {
fn drop(&mut self) {
self.0.set().remove(&self.1);
}
}
pub fn is_running(state: &AppState, mission_id: &str) -> bool {
state.mission_runs.set().contains(mission_id)
}
/// One scheduler tick: leases that ran out go back to ready, then each active mission without a
/// runner turn gets one.
pub async fn tick(state: &AppState) {
if !super::enabled(state).await {
return;
}
// Sources first, so a live hand-off or routine refreshes kwant's lease before the sweep
super::listener::reconcile(state).await;
super::sweep_leases(state).await;
// AutoFix retries whose time has come, before tasks are picked (Phase B3)
super::autofix::run_due(state).await;
// Waiting checks whose re-run is due; in the background, as a command may take minutes
super::checks::spawn_due(state);
for m in state.db.active_missions().await.unwrap_or_default() {
// Evidence drift, at most every 10 minutes per mission (Phase B1)
super::graph::scan_if_due(state, &m).await;
if is_running(state, &m.id) {
continue;
}
let _ = run_mission(state, &m, 1).await;
}
// Watched missions that stopped get their check (P1)
super::watch::tick(state).await;
}
/// Starts runner turns for up to `max` ready tasks of `mission` (one at a time, in the
/// background). Returns `(task_id, kwant_id)` of each started, and why none were if so.
pub async fn run_mission(state: &AppState, mission: &Mission, max: usize) -> (Vec<(String, String)>, Option<String>) {
// Today's spending stop holds new turns: nothing is claimed, so no attempt is used
if let Some(why) = crate::server::spend_stop::held(state, &mission.space_id).await {
skip_for_spend(state, mission, &why).await;
return (Vec::new(), Some(why));
}
let slot = match Slot::take(&state.mission_runs, &mission.id) {
Ok(s) => s,
Err(why) => return (Vec::new(), Some(why.into())),
};
super::promote(state, &mission.id).await;
let space = crate::db::spaces::SpaceId::new(&mission.space_id);
let ready = state.db.list_tasks(&space, Some("ready"), Some(&mission.id), None, 100).await.unwrap_or_default();
let mut picked: Vec<(Task, crate::db::models::Kwant)> = Vec::new();
let mut reason = None;
for t in ready.iter().filter(|t| matches!(t.source_kind.as_str(), "mission" | "person") && t.held_at.is_none()) {
if picked.len() >= max {
break;
}
let who = runner_of(mission, t);
let Ok(Some(bot)) = state.db.get_kwant(&who).await else { continue };
if picked.iter().any(|(_, k)| k.id == bot.id) {
continue;
}
// Flight School (D7): a bot below act on an engine kwant can't gate doesn't run the task
if super::flight_school::block_if_ungated(state, t, &bot, None).await {
reason = Some(super::flight_school::ENGINE_CANT_SANDBOX.into());
continue;
}
let context = mission_context(mission, &bot);
match state.db.claim_task(&t.id, &bot.id, None, Some(&context), lease_ms(state).await, false, "kwant").await {
Ok(Ok(task)) => {
super::emit_task(state, &task).await;
super::checkpoints::before_run(state, &task).await;
picked.push((task, bot));
}
Ok(Err(ClaimRefused::Budget { remaining, needed })) => {
reason = Some(format!("the mission's budget can't cover the next task ({remaining} tokens left, {needed} needed)"));
break;
}
Ok(Err(why)) => reason = Some(why.to_string()),
Err(e) => reason = Some(e.to_string()),
}
}
if picked.is_empty() {
return (Vec::new(), Some(reason.unwrap_or_else(|| "no ready task to start".into())));
}
super::emit_mission(state, &mission.id).await;
let started = picked.iter().map(|(t, k)| (t.id.clone(), k.id.clone())).collect();
let state = state.clone();
let mission = mission.clone();
tokio::spawn(async move {
let _slot = slot;
for (task, bot) in picked {
run_one(&state, &mission, &task, &bot).await;
}
});
(started, None)
}
/// The spending stop held `mission`: its next ready task's history says so, once a day.
async fn skip_for_spend(state: &AppState, mission: &Mission, why: &str) {
let space = crate::db::spaces::SpaceId::new(&mission.space_id);
let ready = state.db.list_tasks(&space, Some("ready"), Some(&mission.id), None, 100).await.unwrap_or_default();
let Some(t) = ready.iter().find(|t| matches!(t.source_kind.as_str(), "mission" | "person") && t.held_at.is_none()) else { return };
if crate::server::spend_stop::first_skip_today(state, &format!("task:{}", t.id)).await {
let detail = serde_json::json!({"reason": crate::server::spend_stop::REASON, "why": why});
let _ = state.db.task_event(&t.id, Some(&mission.id), "skipped", "kwant", &detail).await;
super::emit_task(state, t).await;
}
}
/// Where a runner turn of `bot` in `m` runs: the mission's channel; its thread or direct chat only
/// for the lead (threads and direct chats are one bot's own), else the bot's direct chat.
fn mission_place(m: &Mission, bot: &crate::db::models::Kwant) -> (Option<String>, Option<String>) {
place_of(m, &bot.id)
}
fn place_of(m: &Mission, bot_id: &str) -> (Option<String>, Option<String>) {
match (&m.channel_id, &m.thread_id) {
(Some(c), _) => (Some(c.clone()), None),
(None, Some(t)) if bot_id == m.lead_kwant_id => (None, Some(t.clone())),
_ => (None, None),
}
}
/// The bot that runs `t` for `m`: its owner, else the suggested bot, else the mission's lead.
fn runner_of(m: &Mission, t: &Task) -> String {
t.owner_kwant_id.clone().or_else(|| t.suggested_kwant_id.clone()).unwrap_or_else(|| m.lead_kwant_id.clone())
}
/// "Due to retry" (P1 contract §3, D9): a retry of `t` is already coming, so nothing else should
/// restart it. Any of: `failed` and AutoFix will run it again ([`super::autofix::will_retry`]: not
/// merely attempts left, #513 M2); an AutoFix attempt scheduled (a stall retry, or a wait after a
/// temporary error or rate limit, in whatever state the task is); or a turn of its bot parked where
/// the mission runs it, until the usage limit resets or the bot's budget allows.
pub async fn due_to_retry(state: &AppState, m: &Mission, t: &Task) -> bool {
if super::autofix::will_retry(state, t).await || super::autofix::retry_scheduled(state, &t.id).await {
return true;
}
let bot = runner_of(m, t);
let (channel, thread) = place_of(m, &bot);
state.db.parked_waiting_in(&bot, channel.as_deref(), thread.as_deref()).await.unwrap_or(false)
}
/// The chat id of [`mission_place`], as `TurnScope::context_id` names it.
fn mission_context(m: &Mission, bot: &crate::db::models::Kwant) -> String {
let (c, t) = mission_place(m, bot);
c.or(t).unwrap_or_else(|| bot.id.clone())
}
/// B1: what a high-impact task's owner is asked first. A teammate checks the result against these
/// lines with fresh eyes (only the spec and the result, never this chat).
pub(crate) const SPEC_FIRST: &str = "This task is high impact. Before you start, call task_update with task_id and `spec` \
(no status): 1-8 short lines saying what done means and how a reviewer can check each. A teammate checks your \
result against those lines with fresh eyes: it sees only the spec and the result, not this chat.\n";
async fn prompt(state: &AppState, m: &Mission, t: &Task) -> String {
let checks = state.db.list_checks(&t.id).await.unwrap_or_default();
let list: Vec<String> = checks
.iter()
.filter(|c| c.approved)
.map(|c| format!("- {} {}{}", c.kind, super::autofix::redact_value(&c.spec_value()), if c.required { "" } else { " (optional)" }))
.collect();
let deps = state.db.dependencies_of(&t.id).await.unwrap_or_default();
format!(
"[Mission Control] You hold task {id} of the mission \"{mt}\" (goal: {goal}).\n\
Task: {title}\nAcceptance: {acc}\nChecks kwant will run when you're done:\n{checks}\n{self_check}{deps}{spec_first}\
Work on it now. Attach what you produced with task_attach_evidence, then call task_update with \
task_id {id} and status \"review\": kwant runs the checks and only they (or a teammate's review, \
or the person) can verify it. If you can't finish, call task_update with status \"blocked\" and a \
reason, or \"ready\" to let it go. Never say it is verified yourself.{budget}",
id = t.id,
mt = m.title,
goal = m.goal,
title = t.title,
acc = if t.acceptance.is_empty() { "(none given)" } else { &t.acceptance },
checks = if list.is_empty() { "- none: a teammate or the person reviews it".into() } else { list.join("\n") },
// C0: only a task with an approved check can be checked before hand-in
self_check = if list.is_empty() { "" } else { SELF_CHECK },
deps = if deps.is_empty() { String::new() } else { format!("It builds on tasks {} (verified).\n", deps.iter().map(|d| d.0.as_str()).collect::<Vec<_>>().join(", ")) },
spec_first = if super::auditor::is_high_impact(t) { SPEC_FIRST } else { "" },
budget = if t.budget_tokens > super::NO_LIMIT { format!(" Budget: {} tokens.", t.budget_tokens - t.spent_tokens) } else { String::new() },
)
}
async fn run_one(state: &AppState, m: &Mission, task: &Task, bot: &crate::db::models::Kwant) {
let started = chrono::Utc::now();
let context = mission_context(m, bot);
let job = state.turns.start_job([context.clone()]);
let (channel, thread) = mission_place(m, bot);
let reply = match scope_for(state, bot, channel, thread, &job, 0).await {
Ok(scope) => {
let mut hint = None;
let mut p = prompt(state, m, task).await;
if let Some(note) = super::autofix::retry_note(state, task).await {
p.push_str(¬e);
}
// C1: lessons from the bot's earlier tasks; held out for 1 in 5 tasks (still logged)
if let Some((block, h)) = super::lessons::for_brief(state, &bot.id, &task.id).await {
if !block.is_empty() {
p.truncate(p.trim_end().len());
p.push_str(&block);
}
hint = Some(h);
}
// 0.9.6: nobody watches a runner turn, so a busy browser step it ends on is retried
// here with the hand-offs' bounds (see [`busy_retry::unwatched`]), while the task is
// still this bot's to work on; one that still ends busy fails the task as any failed
// turn does (below). Every retry is `quiet_finish` too: one notification per outcome
let mut first = true;
busy_retry::unwatched(&scope, &bot.name, &p, |p, slot| {
let mut opts = TurnOpts::default();
(opts.unsaved, opts.quiet_failure, opts.purpose) = (true, true, Some(PURPOSE.into()));
// One notification per task outcome, sent below, not one per attempt
opts.quiet_finish = true;
opts.task = hint.clone();
opts.busy_slot = Some(slot.clone());
let retry = !std::mem::replace(&mut first, false);
let (scope, task_id, bot_id) = (&scope, task.id.as_str(), bot.id.as_str());
attempt(retry, slot, move || still_held(state, task_id, bot_id), async move {
// boxed, so the retry loop around the turn adds no stack to it
Box::pin(turn_once(scope, bot, p, opts)).await
})
})
.await
}
Err(e) => Err(e),
};
if let Err(e) = &reply {
tracing::info!(task_id = %task.id, error = %e, "mission runner turn ended without a reply");
}
let err = reply.as_ref().err().map(ToString::to_string);
after_turn(state, &task.id, err.as_deref(), started).await;
notify_outcome(state, &task.id, &bot.id, &context, reply.is_ok()).await;
}
/// Why a busy browser step's retry didn't run: the task stopped being the runner's while it
/// waited (the person took it, moved it on, or the mission let it go).
pub const MOVED_ON: &str = "the task moved on while its busy browser step waited for a retry";
/// One turn of a runner's [`busy_retry::retry_loop`]: a retry (`retry`) runs only while the task
/// is still held ([`still_held`]), and a busy end is left in `slot` for a retry only if the task
/// is still held after the turn: a bot that handed the task in, blocked it or asked the person
/// meanwhile is not run again.
async fn attempt<H, HF, T>(retry: bool, slot: BusySlot, held: H, turn: T) -> Result<String, String>
where
H: Fn() -> HF,
HF: Future<Output = bool>,
T: Future<Output = Result<String, String>>,
{
if retry && !held().await {
return Err(MOVED_ON.into());
}
let outcome = turn.await;
if let Some(step) = slot.take() {
if held().await {
slot.put(step);
}
}
outcome
}
/// Whether `task_id` is still `working` for `bot_id`. Renews its lease when it is, so a busy
/// browser retry's cooldown (1 min, then 2) never runs a short lease out.
async fn still_held(state: &AppState, task_id: &str, bot_id: &str) -> bool {
let Ok(Some(t)) = state.db.get_task(task_id).await else { return false };
let held = t.state == "working" && t.owner_kwant_id.as_deref() == Some(bot_id);
if held {
let _ = state.db.renew_claim(task_id, lease_ms(state).await).await;
}
held
}
/// The runner turn's one `turn_finished` notification: none while AutoFix has a retry of the task
/// scheduled (that retry's turn notifies, or the one after it), so a failing task gives one for
/// its final outcome. A turn that failed notifies only when the task ended `failed` or `blocked`.
async fn notify_outcome(state: &AppState, task_id: &str, kwant_id: &str, context: &str, replied: bool) {
let Ok(Some(t)) = state.db.get_task(task_id).await else { return };
if retry_coming(state, task_id).await {
return;
}
if !replied && !matches!(t.state.as_str(), "failed" | "blocked") {
return;
}
let n = crate::server::continuity::turn_finished(state, kwant_id, Some(context)).await;
crate::server::continuity::notify(state, n).await;
}
/// Whether an AutoFix attempt of the task is scheduled. It can't have started yet: it waits for
/// this mission's runner slot, which the caller still holds.
async fn retry_coming(state: &AppState, task_id: &str) -> bool {
super::autofix::retry_scheduled(state, task_id).await
}
/// After a runner turn of `task_id`: still `working` means the bot didn't finish or let go, so the
/// lease is released (one attempt used). With AutoFix on, a task with attempts left parks in
/// `failed` for it (§13), and the failure is recorded: the turn's error, a denied action since
/// `started`, or a stall; a task left waiting on the person records `needs_input`.
pub async fn after_turn(state: &AppState, task_id: &str, err: Option<&str>, started: chrono::DateTime<chrono::Utc>) {
super::lessons::note_self_check(state, task_id, started).await;
// Waiting on nothing (its cards were answered or withdrawn) is still working: release it
let Some(t) = super::listener::settle_needs_you(state, task_id).await else { return };
if t.state == "needs_you" {
super::autofix::record(state, &t.id, "turn", "needs_input", "", "the bot is waiting on the person").await;
return;
}
if t.state != "working" {
return;
}
// Today's spending stop held the turn before it started: back to ready, no attempt used and
// no failure, so AutoFix doesn't retry it
if let Some(why) = err.filter(|e| crate::server::spend_stop::is_stop_error(e)) {
let change = TaskChange {
kind: "released".into(),
reason: Some(format!("skipped: {}", crate::server::spend_stop::REASON)),
..Default::default()
};
let _ = transition(state, &t.id, "working", "ready", Actor::Kwant, "kwant", change).await;
// …and its timeline says why, once a day (the same mark [`skip_for_spend`] leaves)
if crate::server::spend_stop::first_skip_today(state, &format!("task:{}", t.id)).await {
let detail = serde_json::json!({"reason": crate::server::spend_stop::REASON, "why": why});
let _ = state.db.task_event(&t.id, t.mission_id.as_deref(), "skipped", "kwant", &detail).await;
}
return;
}
let park = super::autofix::parks(state, &t, true).await;
let change = TaskChange {
kind: "released".into(),
reason: Some("the runner turn ended without a review".into()),
attempt: true,
..Default::default()
};
let to = if park { "failed" } else { "ready" };
if transition(state, &t.id, "working", to, Actor::Kwant, "kwant", change).await.is_err() {
return;
}
if !park {
if let Ok(Some(t)) = state.db.get_task(task_id).await {
if t.attempts >= t.max_attempts && t.state == "ready" {
let change = TaskChange { reason: Some("no review after its last attempt".into()), ..Default::default() };
let _ = transition(state, &t.id, "ready", "blocked", Actor::Kwant, "kwant", change).await;
}
}
}
let denied = state.db.denied_since(task_id, started).await.unwrap_or_default();
match (err, denied) {
(Some(e), _) => super::autofix::record(state, task_id, "turn", "error", e, e.lines().next().unwrap_or("the turn failed")).await,
(None, Some(what)) => super::autofix::record(state, task_id, "turn", "denied", &what, &format!("denied: {what}")).await,
(None, None) => super::autofix::record(state, task_id, "turn", "stalled", "", "the runner turn ended without a review").await,
};
}
#[cfg(test)]
mod tests {
use super::*;
use crate::server::busy_retry::{retry_loop, Step};
use serde_json::json;
use std::collections::VecDeque;
use std::time::Duration;
fn act(args: serde_json::Value) -> Step {
Step { tool: "browser_act".into(), args: args.to_string() }
}
/// What a fake runner task did: the outcome, the prompts its turns got and the waits
/// (attempt, cooldown) between them.
struct Ran {
outcome: Result<String, String>,
prompts: Vec<String>,
waits: Vec<(u8, Duration)>,
}
/// A runner task through [`attempt`] and the same loop [`busy_retry::unwatched`] runs: turn n
/// replies "reply n" and ends on `step` where `busy[n]`; each "is the task still held?"
/// answers the next of `held` (then yes), as the database would.
async fn run_task(step: &Step, busy: &[bool], held: &[bool]) -> Ran {
let prompts = Mutex::new(Vec::new());
let waits = Mutex::new(Vec::new());
let held = Mutex::new(held.iter().copied().collect::<VecDeque<bool>>());
let mut first = true;
let outcome = retry_loop(
"[Mission Control] You hold task t1",
|p, slot| {
let retry = !std::mem::replace(&mut first, false);
let (prompts, held) = (&prompts, &held);
attempt(retry, slot.clone(), move || async move { held.lock().unwrap().pop_front().unwrap_or(true) }, async move {
let n = {
let mut ps = prompts.lock().unwrap();
ps.push(p);
ps.len() - 1
};
if busy.get(n).copied().unwrap_or(false) {
slot.put(step.clone());
}
Ok(format!("reply {n}"))
})
},
|s, attempt, after| {
assert_eq!(&s, step, "the retry is for the same step");
waits.lock().unwrap().push((attempt, after));
async { true }
},
)
.await;
Ran { outcome, prompts: prompts.into_inner().unwrap(), waits: waits.into_inner().unwrap() }
}
#[tokio::test]
async fn a_task_turn_that_ends_busy_is_retried_twice_then_fails_as_today() {
let step = act(json!({"action": "scroll", "delta_y": 400}));
let ran = run_task(&step, &[true, true, true], &[]).await;
assert_eq!(ran.prompts.len(), 3, "the turn, then 2 retries, never a third");
assert_eq!(ran.prompts[0], "[Mission Control] You hold task t1");
for p in &ran.prompts[1..] {
assert!(p.contains("the browser was busy") && p.contains("`browser_act`"), "{p}");
assert_eq!(p.matches("You hold task t1").count(), 1, "the brief once");
}
assert_eq!(ran.waits, vec![(1, Duration::from_secs(60)), (2, Duration::from_secs(120))]);
// The turn's error, which `after_turn` records like any failed runner turn: a temporary
// error AutoFix doesn't run again (0.9.7, see autofix's `busy_give_up_is_never_run_again`)
let err = ran.outcome.expect_err("the task fails once the retries are used up");
assert_eq!(err, "the browser stayed busy after 2 automatic retries of `browser_act`");
assert_eq!(super::super::autofix::classify("turn", "error", &err), "transient");
}
#[tokio::test]
async fn a_task_turn_that_gets_through_on_retry_1_ends_with_that_reply() {
let ran = run_task(&act(json!({"action": "click", "ref": "e9"})), &[true, false], &[]).await;
assert_eq!(ran.outcome, Ok("reply 1".into()));
assert_eq!((ran.prompts.len(), ran.waits.len()), (2, 1));
// and one that never ends busy runs once, as before
let ran = run_task(&act(json!({})), &[false], &[]).await;
assert_eq!((ran.outcome, ran.prompts.len(), ran.waits.len()), (Ok("reply 0".into()), 1, 0));
}
#[tokio::test]
async fn a_busy_task_step_that_may_reach_outside_is_never_run_again() {
let send = act(json!({"action": "click", "ref": "e4", "name": "Send"}));
let ran = run_task(&send, &[true, true, true], &[]).await;
assert_eq!((ran.prompts.len(), ran.waits.len()), (1, 0), "straight to the one failure");
let err = ran.outcome.unwrap_err();
assert!(err.contains("may reach outside") && err.contains("wasn't run again by itself"), "{err}");
}
#[tokio::test]
async fn a_task_the_bot_let_go_of_in_its_busy_turn_is_not_run_again() {
// It ended busy, but it handed the task in (or blocked it, or asked the person) first
let ran = run_task(&act(json!({"action": "scroll"})), &[true, true], &[false]).await;
assert_eq!(ran.outcome, Ok("reply 0".into()), "the turn's own reply, as before");
assert_eq!((ran.prompts.len(), ran.waits.len()), (1, 0));
}
#[tokio::test]
async fn a_task_that_moved_on_during_the_cooldown_is_not_run_again() {
// Held when the busy turn ended, gone by the time the retry is due
let ran = run_task(&act(json!({"action": "scroll"})), &[true, true], &[true, false]).await;
assert_eq!(ran.outcome, Err(MOVED_ON.into()));
assert_eq!((ran.prompts.len(), ran.waits.len()), (1, 1), "no retry turn ran");
}
#[test]
fn slots_are_per_server_and_freed_when_dropped() {
let (a, b) = (Arc::new(RunningMissions::default()), Arc::new(RunningMissions::default()));
let (one, _two) = (Slot::take(&a, "m1").unwrap(), Slot::take(&a, "m2").unwrap());
assert!(Slot::take(&a, "m1").err().unwrap().contains("already going"));
assert!(Slot::take(&a, "m3").err().unwrap().contains("two missions"));
// Another server's missions don't count against this one's
assert!(Slot::take(&b, "m3").is_ok());
drop(one);
assert!(Slot::take(&a, "m3").is_ok());
}
}