Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

feat(drivers): add dynamic team-mission alignment context to agent turns

Oleksandr Ivanchenkoc2087dc8c9c8
diff --git a/src/drivers/api.rs b/src/drivers/api.rs
index c2d8671a..841b568a 100644
--- a/src/drivers/api.rs
+++ b/src/drivers/api.rs
@@ -69,10 +69,7 @@ impl Driver for ApiDriver {
// If target is a real live API endpoint with API key or local Ollama, call HTTP streaming
if api_key.is_some() || target_model == "local_ollama" {
- let system_prompt = format!(
- "{}\n\nYou are {}, {}. Respond clearly in character.",
- input.kwant.persona_prompt, input.kwant.name, input.kwant.title
- );
+ let system_prompt = input.format_system_prompt();
let mut messages = vec![json!({"role": "system", "content": system_prompt})];
for msg in &input.history {
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index d30ed406..906d632d 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -111,6 +111,8 @@ impl Driver for CliDriver {
)))
.await;
+ let system_prompt = input.format_system_prompt();
+
match self.tool_kind.as_str() {
"codex" => {
let out_file = format!("/tmp/kwnt_codex_{}.txt", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos());
@@ -119,6 +121,11 @@ impl Driver for CliDriver {
"low" => "low",
_ => "medium",
};
+ let full_prompt = if input.team_context.is_some() {
+ format!("[System Context: {}]\n\n{}", system_prompt, input.prompt)
+ } else {
+ input.prompt.clone()
+ };
cmd.arg("exec")
.arg("--ephemeral")
.arg("--skip-git-repo-check")
@@ -128,14 +135,21 @@ impl Driver for CliDriver {
.arg(format!("reasoning_effort=\"{}\"", codex_effort))
.arg("-o")
.arg(&out_file)
- .arg(&input.prompt);
+ .arg(&full_prompt);
codex_out_file = Some(out_file);
}
"grok" => {
+ if let Some(ref team) = input.team_context {
+ let desc = team.description.as_deref().unwrap_or("General team objectives");
+ cmd.arg("--rules").arg(format!("You are contributing to team @{}: {}", team.name, desc));
+ }
cmd.arg("-p").arg(&input.prompt);
}
_ => {
// claude default
+ if input.team_context.is_some() {
+ cmd.arg("--append-system-prompt").arg(&system_prompt);
+ }
cmd.arg("-p").arg(&input.prompt);
}
}
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index fbe5f6f1..c68c1ee6 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -24,6 +24,13 @@ pub enum DriverError {
Execution(String),
}
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub struct TeamContext {
+ pub id: String,
+ pub name: String,
+ pub description: Option<String>,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TurnInput {
pub thread_id: String,
@@ -32,6 +39,25 @@ pub struct TurnInput {
pub history: Vec<Message>,
pub model_override: Option<String>,
pub effort_level: Option<String>,
+ pub team_context: Option<TeamContext>,
+}
+
+impl TurnInput {
+ pub fn format_system_prompt(&self) -> String {
+ let base = format!(
+ "{}\n\nYou are {}, {}.",
+ self.kwant.persona_prompt, self.kwant.name, self.kwant.title
+ );
+ if let Some(ref team) = self.team_context {
+ let desc = team.description.as_deref().unwrap_or("General team objectives");
+ format!(
+ "{}\n\n[Active Team Alignment: @{}]\nTeam Mission: {}\nAs a member of team @{}, align your tone, recommendations, and analysis with this team's mission and collaborate effectively with fellow team members.",
+ base, team.name, desc, team.name
+ )
+ } else {
+ format!("{}\n\nRespond clearly in character.", base)
+ }
+ }
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 0ed56702..dbf70857 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -211,6 +211,7 @@ fn execute_single_turn(
session_id: String,
team_keys: Option<(String, String)>,
kwant_id: Option<String>,
+ team_context: Option<crate::drivers::TeamContext>,
) {
let event_broadcast = state.event_sender.clone();
let db = state.db.clone();
@@ -264,6 +265,7 @@ fn execute_single_turn(
history,
model_override: Some(target_model),
effort_level: Some(effort_level),
+ team_context,
};
let (driver_tx, mut driver_rx) = mpsc::channel(32);
@@ -397,6 +399,38 @@ pub async fn send_chat(
None
};
+ // Also resolve active team context for single Kwants invoked inside team channels
+ let active_team = if let Some(ref t) = target_team {
+ Some(t.clone())
+ } else if let Some(tid) = &payload.team_id {
+ all_teams
+ .iter()
+ .find(|t| &t.id == tid || t.name.eq_ignore_ascii_case(tid))
+ .cloned()
+ } else if let Some(cid) = &payload.channel_id {
+ if let Ok(Some(channel)) = state.db.get_channel(cid).await {
+ if channel.name.starts_with("team-") {
+ let tname = &channel.name[5..];
+ all_teams
+ .iter()
+ .find(|t| t.name.eq_ignore_ascii_case(tname))
+ .cloned()
+ } else {
+ None
+ }
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
+ let active_team_context = active_team.as_ref().map(|t| crate::drivers::TeamContext {
+ id: t.id.clone(),
+ name: t.name.clone(),
+ description: t.description.clone(),
+ });
+
// Insert user message to DB
let user_msg = NewMessage {
channel_id: payload.channel_id.clone(),
@@ -470,6 +504,7 @@ pub async fn send_chat(
session_id,
Some((team.id.clone(), team.name.clone())),
kwant_id_cleanup,
+ active_team_context,
);
Ok(Json(json!({
@@ -583,6 +618,11 @@ pub async fn send_chat(
history: Vec::new(),
model_override: Some(target_model.clone()),
effort_level: Some(effort_level),
+ team_context: Some(crate::drivers::TeamContext {
+ id: team_clone.id.clone(),
+ name: team_clone.name.clone(),
+ description: team_clone.description.clone(),
+ }),
};
let (driver_tx, mut driver_rx) = mpsc::channel(32);
@@ -692,6 +732,7 @@ pub async fn send_chat(
}
.ok_or(StatusCode::BAD_REQUEST)?;
+ let team_keys = active_team.as_ref().map(|t| (t.id.clone(), t.name.clone()));
let kwant_id_cleanup = payload.kwant_id.clone();
execute_single_turn(
state.clone(),
@@ -699,8 +740,9 @@ pub async fn send_chat(
payload,
cancel_token,
session_id,
- None,
+ team_keys,
kwant_id_cleanup,
+ active_team_context,
);
Ok(Json(json!({
diff --git a/tests/driver_test.rs b/tests/driver_test.rs
index 9682127d..3e5ff056 100644
--- a/tests/driver_test.rs
+++ b/tests/driver_test.rs
@@ -83,6 +83,7 @@ async fn test_mock_driver_streaming() {
history: vec![],
model_override: None,
effort_level: None,
+ team_context: None,
};
let handle = tokio::spawn(async move {
@@ -107,3 +108,61 @@ async fn test_mock_driver_streaming() {
let output = handle.await.unwrap();
assert_eq!(output.tokens_used, 42);
}
+
+#[test]
+fn test_turn_input_format_system_prompt_with_and_without_team_context() {
+ use kwnt::drivers::TeamContext;
+
+ let kwant = Kwant {
+ id: "k-1".into(),
+ name: "Architect".into(),
+ title: "Systems Architect".into(),
+ persona_prompt: "You design bulletproof distributed architectures.".into(),
+ avatar_sprite: "cyber_mage".into(),
+ driver_type: "api".into(),
+ preferred_model: "claude".into(),
+ temperature: 0.7,
+ max_tokens: 2048,
+ level: 1,
+ turns_completed: 0,
+ created_at: None,
+ };
+
+ // 1. Without team context
+ let input_solo = TurnInput {
+ thread_id: "thread-1".into(),
+ kwant: kwant.clone(),
+ prompt: "Review the system".into(),
+ history: vec![],
+ model_override: None,
+ effort_level: None,
+ team_context: None,
+ };
+
+ let solo_prompt = input_solo.format_system_prompt();
+ assert!(solo_prompt.contains("Systems Architect"));
+ assert!(solo_prompt.contains("bulletproof distributed architectures"));
+ assert!(!solo_prompt.contains("Active Team Alignment"));
+
+ // 2. With team context
+ let input_team = TurnInput {
+ thread_id: "thread-team".into(),
+ kwant: kwant.clone(),
+ prompt: "Review the system".into(),
+ history: vec![],
+ model_override: None,
+ effort_level: None,
+ team_context: Some(TeamContext {
+ id: "team-123".into(),
+ name: "core-engineering".into(),
+ description: Some("Core architectural, engineering, and infrastructure team".into()),
+ }),
+ };
+
+ let team_prompt = input_team.format_system_prompt();
+ assert!(team_prompt.contains("Systems Architect"));
+ assert!(team_prompt.contains("[Active Team Alignment: @core-engineering]"));
+ assert!(team_prompt.contains("Team Mission: Core architectural, engineering, and infrastructure team"));
+ assert!(team_prompt.contains("align your tone, recommendations, and analysis with this team's mission"));
+}
+