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
Delegation: parallel tasks resume the lead once with every result; no handing a task back
Lin (kwant bot)d560e516098b
diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 6cc32b33..3970453d 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -354,7 +354,7 @@ fn delegation_tools() -> Vec<Value> {vec![json!({"name": "delegate",- "description": "Hand a task to another agent (a specialist). It works on it in its own thread in the background while you and the user carry on; its result is posted to this chat and you get a turn to continue. Use it for longer, self-contained work that fits another agent's role. Write the task so it stands on its own.",+ "description": "Hand a task to another agent (a specialist). It works on it in its own thread in the background while you and the user carry on; its result is posted to this chat and you get a turn to continue. Use it for longer, self-contained work that fits another agent's role. Write the task so it stands on its own. If you hand tasks to several agents at once, you get one turn once all of them have ended. Never hand a task back to the agent that gave it to you.","inputSchema": {"type": "object","properties": {diff --git a/src/server/delegation.rs b/src/server/delegation.rsindex 47bd4ee7..14936070 100644--- a/src/server/delegation.rs+++ b/src/server/delegation.rs@@ -163,6 +163,17 @@ pub async fn start(state: &AppState, req: StartRequest) -> Result<Delegation, (Sreturn Err((StatusCode::FORBIDDEN, format!("{} isn't in this chat.", req.specialist.name)));}}+ // No handing a task back to the bot that gave it: the reply in the thread already goes back to it+ if let Some(tid) = &req.origin.thread_id {+ if let Ok(Some(parent)) = state.db.delegation_for_thread(tid).await {+ if parent.lead_kwant_id == req.specialist.id {+ return bad(&format!(+ "{} gave you this task, so don't hand it back. Do the work here; your reply goes back to {} automatically.",+ req.specialist.name, req.specialist.name+ ));+ }+ }+ }let o = &req.origin;let set = [&o.channel_id, &o.kwant_id, &o.thread_id].iter().filter(|x| x.is_some()).count();if set != 1 {@@ -325,13 +336,73 @@ async fn finish(state: &AppState, d: &Delegation, specialist: &Kwant, outcome: R},).await;- if let (Ok(reply), true) = (&outcome, done.continue_lead) {- continue_lead(state, &done, specialist, reply).await;+ if done.continue_lead {+ if let Some(batch) = finished_batch(state, &done).await {+ continue_lead(state, &done, &batch).await;+ }+ }+}++/// The delegations a lead sent from one chat that ran at the same time as `d`, once all of them+/// have ended. `None` while one is still open, or when another one of them ended later: the last+/// to end resumes the lead, once, with every result.+async fn finished_batch(state: &AppState, d: &Delegation) -> Option<Vec<Delegation>> {+ let siblings: Vec<Delegation> = state+ .db+ .list_delegations(Some(&d.lead_kwant_id), None, 50)+ .await+ .ok()?+ .into_iter()+ .filter(|s| s.continue_lead && s.origin_context() == d.origin_context())+ .collect();+ if siblings.iter().any(Delegation::is_open) {+ return None;+ }+ let end = |s: &Delegation| s.ended_at.unwrap_or(s.created_at);+ // Grow from `d` to every delegation whose run overlaps the batch's span+ let mut batch = vec![siblings.iter().find(|s| s.id == d.id)?.clone()];+ let (mut lo, mut hi) = (d.created_at, end(d));+ loop {+ let more: Vec<Delegation> = siblings+ .iter()+ .filter(|s| !batch.iter().any(|b| b.id == s.id) && s.created_at <= hi && end(s) >= lo)+ .cloned()+ .collect();+ if more.is_empty() {+ break;+ }+ for s in more {+ lo = lo.min(s.created_at);+ hi = hi.max(end(&s));+ batch.push(s);+ }+ }+ let last = batch.iter().max_by(|a, b| end(a).cmp(&end(b)).then_with(|| a.id.cmp(&b.id)))?;+ if last.id != d.id || !batch.iter().any(|b| b.status == "completed") {+ return None;}+ batch.sort_by_key(|b| b.created_at);+ Some(batch)+}++/// The specialist's last reply in a delegation thread.+async fn result_of(state: &AppState, d: &Delegation) -> String {+ let lead = name_of(state, &d.lead_kwant_id).await;+ state+ .db+ .list_messages(&d.thread_id, 100)+ .await+ .unwrap_or_default()+ .into_iter()+ .rev()+ .find(|m| m.sender_role == "kwant" && m.sender_id != lead)+ .map(|m| m.text)+ .unwrap_or_else(|| "(The result is in the chat above.)".into())}-/// Gives the lead a turn in the origin chat with the result, so it can carry on with the request.-async fn continue_lead(state: &AppState, d: &Delegation, specialist: &Kwant, reply: &str) {+/// Gives the lead one turn in the origin chat with every result of the batch, so it checks them+/// and gives the user one answer.+async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation]) {let Ok(Some(lead)) = state.db.get_kwant(&d.lead_kwant_id).await else {return;};@@ -340,12 +411,25 @@ async fn continue_lead(state: &AppState, d: &Delegation, specialist: &Kwant, replet Ok(scope) = scope_for(state, &lead, d.origin_channel_id.clone(), d.origin_thread_id.clone(), &job, d.depth - 1).await else {return;};+ let budget = 4000 / batch.len().max(1);+ let mut results = String::new();+ for b in batch {+ let who = name_of(state, &b.specialist_kwant_id).await;+ let body = match b.status.as_str() {+ "completed" => clip(&result_of(state, b).await, budget),+ _ => format!("({}: {})", b.status, b.error.as_deref().unwrap_or("no result")),+ };+ results.push_str(&format!("### {who}: “{}”\n{body}\n\n", b.title));+ }+ let opening = match batch {+ [one] => format!("{} finished the task you delegated (“{}”).", name_of(state, &one.specialist_kwant_id).await, one.title),+ _ => format!("All {} tasks you delegated have ended.", batch.len()),+ };let prompt = format!(- "{name} finished the task you delegated (“{title}”). Their result is in the chat above, quoted here:\n\n{result}\n\n\- Continue with what the user asked: use the result, and reply to the user. Don't repeat the whole result.",- name = specialist.name,- title = d.title,- result = clip(reply, 4000),+ "{opening} The results are in the chat above, quoted here:\n\n{results}\+ Check each result against what the user asked. If something is missing or wrong, delegate a concrete \+ correction. Otherwise continue with the user's request and give them one answer that uses the results. \+ Don't repeat the results in full.");let _ = try_kwant_turn(&scope, &lead, prompt, TurnOpts::default()).await;}diff --git a/tests/delegation_test.rs b/tests/delegation_test.rsindex 144e17e1..c29ce19b 100644--- a/tests/delegation_test.rs+++ b/tests/delegation_test.rs@@ -614,3 +614,85 @@ async fn migration_is_additive_and_idempotent() {assert_eq!(wire["data"], "hi");assert_eq!((wire["turn_id"].as_str(), wire["context_id"].as_str(), wire["thread_id"].as_str()), (Some("t1"), Some("th"), Some("th")));}++/// A specialist can't hand its task back to the lead that gave it; its reply already goes back.+#[tokio::test]+async fn a_task_cannot_be_handed_back_to_its_sender() {+ let env = setup().await;+ let release = env.release_file("handback-release");+ let d = delegate(&env, &format!("Hold on LONGTASK:{} REPLYTAG:handback", release.display())).await;+ let thread = d["thread_id"].as_str().unwrap();+ let (s, v) = call(+ &env.app,+ "POST",+ "/api/delegations",+ Some(json!({+ "lead_kwant_id": env.specialist,+ "specialist_kwant_id": env.lead,+ "task": "You do it",+ "thread_id": thread,+ })),+ )+ .await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");+ assert!(v["error"].as_str().unwrap().contains("don't hand it back"), "{v}");+ std::fs::write(&release, "").unwrap();+ wait_for("the held task to finish", || async { delegation_status(&env, d["id"].as_str().unwrap()).await == "completed" }).await;+}++/// A lead that hands work to two agents at once gets one turn after both end, with both results.+#[tokio::test]+async fn parallel_delegations_resume_the_lead_once_with_every_result() {+ let env = setup().await;+ let (_, kwants) = call(&env.app, "GET", "/api/kwants", None).await;+ let third = kwants.as_array().unwrap().iter().map(|k| k["id"].as_str().unwrap().to_string()).find(|id| *id != env.lead && *id != env.specialist);+ let Some(third) = third else {+ // The default space has only two bots; add one+ let (s, v) = call(&env.app, "POST", "/api/kwants", Some(json!({"name": "Third", "title": "QA", "preferred_model": "claude"}))).await;+ assert!(s.is_success(), "{v}");+ return run_fan_in(&env, v["id"].as_str().unwrap().to_string()).await;+ };+ let mut body = kwants.as_array().unwrap().iter().find(|k| k["id"] == third.as_str()).unwrap().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(&env.app, "PUT", &format!("/api/kwants/{third}"), Some(body)).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ run_fan_in(&env, third).await;+}++async fn run_fan_in(env: &Env, third: String) {+ let (rel_a, rel_b) = (env.release_file("fan-a"), env.release_file("fan-b"));+ let mut ids = Vec::new();+ for (to, rel, tag, title) in [(&env.specialist, &rel_a, "fanA", "Fan part A"), (&third, &rel_b, "fanB", "Fan part B")] {+ let (s, d) = call(+ &env.app,+ "POST",+ "/api/delegations",+ Some(json!({+ "lead_kwant_id": env.lead,+ "specialist_kwant_id": to,+ "task": format!("Part LONGTASK:{} REPLYTAG:{tag}", rel.display()),+ "title": title,+ "kwant_id": env.lead,+ })),+ )+ .await;+ assert_eq!(s, StatusCode::ACCEPTED, "{d}");+ ids.push(d["id"].as_str().unwrap().to_string());+ }+ std::fs::write(&rel_a, "").unwrap();+ wait_for("part A to complete", || async { delegation_status(env, &ids[0]).await == "completed" }).await;+ // Part B is still open, so the lead isn't resumed yet+ tokio::time::sleep(Duration::from_millis(500)).await;+ assert!(prompts_with("(“Fan part A”)").is_empty(), "no turn for A alone");+ std::fs::write(&rel_b, "").unwrap();+ wait_for("part B to complete", || async { delegation_status(env, &ids[1]).await == "completed" }).await;+ wait_for("the lead's one continuation turn", || async { !prompts_with("All 2 tasks you delegated have ended").is_empty() }).await;+ tokio::time::sleep(Duration::from_millis(500)).await;+ let resumed = prompts_with("All 2 tasks you delegated have ended");+ assert_eq!(resumed.len(), 1, "exactly one resume");+ let p = &resumed[0];+ assert!(p.contains("answer fanA") && p.contains("answer fanB"), "both results: {p}");+ assert!(p.contains("Check each result"), "{p}");+ assert!(prompts_with("finished the task you delegated (“Fan part").is_empty(), "no per-part turns");+}