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
Give delegated specialists the person's request, files and channel instructions
Lin (kwant bot)f41306f48eab
diff --git a/src/server/attachments.rs b/src/server/attachments.rsindex 0a3ac706..63aab1df 100644--- a/src/server/attachments.rs+++ b/src/server/attachments.rs@@ -533,24 +533,42 @@ fn context_of(scope: &SelfScope) -> Option<String> {o.channel_id.clone().or_else(|| o.thread_id.clone()).or_else(|| o.direct_kwant_id.clone())}-/// The turn may see files of its own chat and files this agent shared anywhere.+/// The chat a delegated task in this turn's thread came from, when the specialist may see it.+async fn task_origin(state: &AppState, scope: &SelfScope) -> Option<String> {+ let thread = scope.origin.as_ref()?.thread_id.as_deref()?;+ super::delegation::shared_origin(state, &scope.kwant_id, thread).await+}++/// The turn may see files of its own chat, of the chat its delegated task came from, and files+/// this agent shared anywhere.async fn visible(state: &AppState, scope: &SelfScope, id: &str) -> Option<Attachment> {let a = load(state, id).await?;let own_chat = a.context_id.is_some() && a.context_id == context_of(scope);let own_file = a.source == "agent" && a.kwant_id.as_deref() == Some(scope.kwant_id.as_str());- (own_chat || own_file).then_some(a)+ if own_chat || own_file {+ return Some(a);+ }+ let origin = task_origin(state, scope).await;+ (origin.is_some() && a.context_id == origin).then_some(a)}pub async fn tool_list(state: &AppState, scope: &SelfScope) -> (String, bool) {let Some(ctx) = context_of(scope) else {return ("This turn has no chat.".into(), true);};+ let line = |a: &Attachment| format!("- {} ({}, {}, from {}) id {}", a.name, a.mime, kb(a.size), a.source, a.id);let list = state.db.list_attachments_in(&ctx, 20).await.unwrap_or_default();- if list.is_empty() {+ let mut lines: Vec<String> = list.iter().map(line).collect();+ if let Some(origin) = task_origin(state, scope).await {+ let theirs = state.db.list_attachments_in(&origin, 20).await.unwrap_or_default();+ if !theirs.is_empty() {+ lines.push("Files in the chat your task came from:".into());+ lines.extend(theirs.iter().map(line));+ }+ }+ if lines.is_empty() {return ("No files in this chat.".into(), false);}- let lines: Vec<String> =- list.iter().map(|a| format!("- {} ({}, {}, from {}) id {}", a.name, a.mime, kb(a.size), a.source, a.id)).collect();(lines.join("\n"), false)}diff --git a/src/server/delegation.rs b/src/server/delegation.rsindex 4d0187b5..591d9569 100644--- a/src/server/delegation.rs+++ b/src/server/delegation.rs@@ -321,9 +321,10 @@ async fn run(});let prompt = format!("{lead} delegated this task to you. Work on it here; when you finish, your reply is posted back to {lead} \- and the chat it came from, so make it a complete, self-contained answer.\n\n{task}{again}",+ and the chat it came from, so make it a complete, self-contained answer.\n\n{task}{origin}{again}",lead = lead.name,task = crate::drivers::peer_message(&lead.name, &format!("Task: {}\n\n{}", d.title, d.task)),+ origin = origin_brief(&state, &d).await,again = if after_restart { RESTARTED_NOTE } else { "" },);let mut opts = TurnOpts::default();@@ -361,6 +362,78 @@ async fn run(finish(&state, &d, &specialist, outcome).await;}+/// Most of the person's request, and of the origin chat's instructions, a delegated task quotes.+const BRIEF_CHARS: usize = 2000;+/// Most files of the origin chat a delegated task lists.+const BRIEF_FILES: i64 = 10;++/// The chat a delegation came from, when its specialist may see it: the lead's own direct chat or+/// thread, or a channel the specialist is a member of (the members a turn there would have).+async fn visible_origin(state: &AppState, d: &Delegation) -> Option<String> {+ if let Some(id) = &d.origin_channel_id {+ let channel = state.db.get_channel(id).await.ok().flatten()?;+ let space = SpaceId::new(&channel.space_id);+ let all = state.db.list_kwants(&space).await.ok()?;+ let team = match channel.name.strip_prefix("team-") {+ Some(name) => state.db.list_teams(&space).await.ok()?.into_iter().find(|t| t.name.eq_ignore_ascii_case(name)),+ None => None,+ };+ let members = super::routes::channel_member_ids(&channel, team.as_ref(), &all);+ return members.contains(&d.specialist_kwant_id).then(|| id.clone());+ }+ if let Some(id) = &d.origin_thread_id {+ let thread = state.db.get_thread(id).await.ok().flatten()?;+ return (thread.kwant_id == d.lead_kwant_id).then(|| id.clone());+ }+ d.origin_kwant_id.clone().filter(|k| *k == d.lead_kwant_id)+}++/// The origin chat of the delegation in `thread_id`, when `kwant_id` is its specialist and may+/// see that chat: its files are readable from the task's thread.+pub(super) async fn shared_origin(state: &AppState, kwant_id: &str, thread_id: &str) -> Option<String> {+ let d = state.db.delegation_for_thread(thread_id).await.ok().flatten()?;+ if d.specialist_kwant_id != kwant_id {+ return None;+ }+ visible_origin(state, &d).await+}++/// What the specialist should know of the chat the task came from: the person's last request+/// before it, that chat's instructions and its files. Empty when the specialist may not see it.+async fn origin_brief(state: &AppState, d: &Delegation) -> String {+ let Some(ctx) = visible_origin(state, d).await else {+ return String::new();+ };+ let mut parts = Vec::new();+ let recent = state.db.list_messages(&ctx, 20).await.unwrap_or_default();+ let asked = recent+ .iter()+ .rev()+ .find(|m| m.sender_role == "user" && m.created_at.is_none_or(|t| t <= d.created_at) && !m.text.trim().is_empty());+ if let Some(m) = asked {+ parts.push(format!("[What the person asked in the chat this task came from]\n{}", clip(m.text.trim(), BRIEF_CHARS)));+ }+ if let Some(id) = &d.origin_channel_id {+ if let Ok(Some(text)) = state.db.channel_instructions(id).await {+ if !text.trim().is_empty() {+ parts.push(format!("[That chat's pinned instructions]\n{}", clip(text.trim(), BRIEF_CHARS)));+ }+ }+ }+ let files = state.db.list_attachments_in(&ctx, BRIEF_FILES).await.unwrap_or_default();+ if !files.is_empty() {+ let lines: Vec<String> = files.iter().map(|a| format!("- {} ({}) id {}", a.name, a.mime, a.id)).collect();+ parts.push(format!(+ "[Files in that chat; read one with `read_attachment` and its id]\n{}",+ lines.join("\n")+ ));+ }+ if parts.is_empty() {+ return String::new();+ }+ format!("\n\n{}", parts.join("\n\n"))+}+/// Added to a delegated task that runs again because kwnt restarted in the middle of it.pub const RESTARTED_NOTE: &str = "\n\n[kwnt restarted while an earlier run of this task was in progress, so it may have partly run: \files may already be written, messages sent or settings changed. Check what is already done before redoing anything, \diff --git a/src/server/routes.rs b/src/server/routes.rsindex 6d236fb3..e4a85553 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -708,12 +708,9 @@ pub(super) async fn scope_for(_ => None,};// Threads are one agent's own conversation: nobody to hand the turn to- let member_ids: Vec<String> = match (&thread, &team, &channel) {- (Some(_), _, _) => Vec::new(),- (None, Some(t), _) => serde_json::from_str(&t.member_kwants).unwrap_or_default(),- (None, None, Some(c)) if c.name == "general" => all_kwants.iter().map(|k| k.id.clone()).collect(),- (None, None, Some(c)) => serde_json::from_str(&c.member_kwants).unwrap_or_default(),- (None, None, None) => Vec::new(),+ let member_ids: Vec<String> = match (&thread, &channel) {+ (None, Some(c)) => channel_member_ids(c, team.as_ref(), &all_kwants),+ _ => Vec::new(),};let teammates: Vec<Kwant> = member_ids.iter().filter_map(|id| all_kwants.iter().find(|k| &k.id == id).cloned()).collect();let workspace_dir = match &team {@@ -743,6 +740,16 @@ pub(super) async fn scope_for(})}+/// The bots of a channel: its team's members for a `team-` channel, every bot of the space in+/// "general", else the channel's own member list. `team` is the channel's team, if any.+pub(super) fn channel_member_ids(channel: &Channel, team: Option<&Team>, all_kwants: &[Kwant]) -> Vec<String> {+ match team {+ Some(t) => serde_json::from_str(&t.member_kwants).unwrap_or_default(),+ None if channel.name == "general" => all_kwants.iter().map(|k| k.id.clone()).collect(),+ None => serde_json::from_str(&channel.member_kwants).unwrap_or_default(),+ }+}+fn team_context(t: &Team) -> crate::drivers::TeamContext {crate::drivers::TeamContext {id: t.id.clone(),diff --git a/tests/attachments_test.rs b/tests/attachments_test.rsindex 76a81bbf..1771ae73 100644--- a/tests/attachments_test.rs+++ b/tests/attachments_test.rs@@ -381,3 +381,60 @@ async fn attachments_migration_is_idempotent() {let db = kwnt::db::Database::init(tmp.path()).await.unwrap();assert!(db.get_attachment("nope").await.unwrap().is_none());}++#[tokio::test]+async fn a_delegated_task_carries_the_persons_request_and_files() {+ let env = setup().await;+ let (_, up) = upload(&env, "brief.md", b"# Brief\nBRIEF_SECRET_LINE\n".to_vec()).await;+ let id = up["id"].as_str().unwrap().to_string();+ send_direct(&env, &env.a, "Plan the Berlin launch from my brief REPLYTAG:o1", json!({"attachment_ids": [id]})).await;+ wait_reply(&env, &env.a, "answer o1").await;++ let marker = call_tool_marker("read_attachment", json!({"id": id}));+ let task = format!("Write the launch copy. {marker} REPLYTAG:o2");+ let (s, d) = call(+ &env.app,+ "POST",+ "/api/delegations",+ Some(json!({"lead_kwant_id": env.a, "specialist_kwant_id": env.b, "task": task, "title": "Launch copy", "kwant_id": env.a, "continue_lead": false})),+ )+ .await;+ assert_eq!(s, StatusCode::ACCEPTED, "{d}");+ let thread = d["thread_id"].as_str().unwrap().to_string();++ // The specialist's brief quotes the person's request and lists the chat's file, which it can read+ // (The quoted request's own REPLYTAG comes last, so the fake answers "o1"; the file text is what counts)+ wait_reply(&env, &env.a, "BRIEF_SECRET_LINE").await;+ let brief = invocations_with("Task: Launch copy").pop().unwrap();+ assert!(brief.contains("[What the person asked in the chat this task came from]"), "{brief}");+ assert!(brief.contains("Plan the Berlin launch from my brief") && brief.contains("brief.md (") && brief.contains(&format!("id {id}")), "{brief}");++ // Only from the task's thread: the same bot in its own chat still can't read it+ env.state.self_tools.lock().await.insert(+ "tok-task".into(),+ SelfScope {+ kwant_id: env.b.clone(),+ kwant_name: "B".into(),+ origin: Some(TurnOrigin { thread_id: Some(thread.clone()), ..Default::default() }),+ ..Default::default()+ },+ );+ let r = self_call(&env, "tok-task", "list_attachments", json!({})).await;+ assert!(text_of(&r).contains("Files in the chat your task came from") && text_of(&r).contains(&id), "{r}");+ direct_turn(&env, "tok-b-own", &env.b, None).await;+ let r = self_call(&env, "tok-b-own", "read_attachment", json!({"id": id})).await;+ assert_eq!(r["isError"], true);++ // The lead's own scope in that thread doesn't widen anything either: it isn't the specialist+ env.state.self_tools.lock().await.insert(+ "tok-lead-thread".into(),+ SelfScope {+ kwant_id: env.a.clone(),+ kwant_name: "A".into(),+ origin: Some(TurnOrigin { thread_id: Some(thread), ..Default::default() }),+ ..Default::default()+ },+ );+ let r = self_call(&env, "tok-lead-thread", "list_attachments", json!({})).await;+ assert!(!text_of(&r).contains("Files in the chat your task came from"), "{r}");+}