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: implement hybrid API and CLI driver fleet with SSE events

Oleksandr Ivanchenko15b638be9b16
diff --git a/src/drivers/api.rs b/src/drivers/api.rs
new file mode 100644
index 00000000..9245a3e5
--- /dev/null
+++ b/src/drivers/api.rs
@@ -0,0 +1,169 @@
+use super::{events::RuntimeEvent, Driver, DriverError, TurnInput, TurnOutput};
+use async_trait::async_trait;
+use reqwest::Client;
+use serde_json::json;
+use std::time::{Duration, Instant};
+use tokio::sync::mpsc;
+
+#[derive(Clone, Debug)]
+pub struct ApiDriver {
+ client: Client,
+ api_key: Option<String>,
+ endpoint: Option<String>,
+}
+
+impl ApiDriver {
+ pub fn new(api_key: Option<String>, endpoint: Option<String>) -> Self {
+ Self {
+ client: Client::new(),
+ api_key,
+ endpoint,
+ }
+ }
+
+ fn resolve_endpoint_and_key(&self, model: &str) -> (String, Option<String>) {
+ if let Some(ep) = &self.endpoint {
+ return (ep.clone(), self.api_key.clone());
+ }
+
+ if model == "local_ollama" || model.starts_with("ollama/") {
+ let base = std::env::var("OLLAMA_URL")
+ .unwrap_or_else(|_| "http://localhost:11434/v1".to_string());
+ (format!("{}/chat/completions", base.trim_end_matches('/')), None)
+ } else if model.contains("claude") {
+ let key = self
+ .api_key
+ .clone()
+ .or_else(|| std::env::var("ANTHROPIC_API_KEY").ok());
+ ("https://api.anthropic.com/v1/messages".to_string(), key)
+ } else if model.contains("grok") {
+ let key = self
+ .api_key
+ .clone()
+ .or_else(|| std::env::var("XAI_API_KEY").ok());
+ ("https://api.x.ai/v1/chat/completions".to_string(), key)
+ } else {
+ let key = self
+ .api_key
+ .clone()
+ .or_else(|| std::env::var("OPENAI_API_KEY").ok());
+ ("https://api.openai.com/v1/chat/completions".to_string(), key)
+ }
+ }
+}
+
+#[async_trait]
+impl Driver for ApiDriver {
+ async fn stream_turn(
+ &self,
+ input: TurnInput,
+ event_tx: mpsc::Sender<RuntimeEvent>,
+ ) -> Result<TurnOutput, DriverError> {
+ let start = Instant::now();
+ let target_model = input
+ .model_override
+ .as_deref()
+ .unwrap_or(&input.kwant.preferred_model);
+
+ let (url, api_key) = self.resolve_endpoint_and_key(target_model);
+
+ // 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 mut messages = vec![json!({"role": "system", "content": system_prompt})];
+ for msg in &input.history {
+ messages.push(json!({"role": msg.sender_role, "content": msg.text}));
+ }
+ messages.push(json!({"role": "user", "content": input.prompt}));
+
+ let body = json!({
+ "model": target_model,
+ "messages": messages,
+ "stream": false, // Non-stream fallback when parsing simple JSON or stream
+ "temperature": input.kwant.temperature,
+ "max_tokens": input.kwant.max_tokens,
+ });
+
+ let mut req = self.client.post(&url).json(&body);
+ if let Some(key) = api_key {
+ req = req.header("Authorization", format!("Bearer {}", key));
+ }
+
+ match req.send().await {
+ Ok(resp) if resp.status().is_success() => {
+ if let Ok(json_body) = resp.json::<serde_json::Value>().await {
+ let text = json_body["choices"][0]["message"]["content"]
+ .as_str()
+ .or_else(|| json_body["content"][0]["text"].as_str())
+ .unwrap_or("No response content")
+ .to_string();
+
+ let tokens = json_body["usage"]["total_tokens"].as_u64().unwrap_or(45) as usize;
+
+ let _ = event_tx.send(RuntimeEvent::TextDelta(text.clone())).await;
+ let duration = start.elapsed().as_millis() as u64;
+ let _ = event_tx
+ .send(RuntimeEvent::TurnComplete {
+ tokens,
+ duration_ms: duration,
+ })
+ .await;
+
+ return Ok(TurnOutput {
+ text,
+ reasoning: None,
+ tokens_used: tokens,
+ });
+ }
+ }
+ Ok(resp) => {
+ tracing::warn!(status = %resp.status(), "API returned non-success, using arcade emulation");
+ }
+ Err(e) => {
+ tracing::warn!(error = %e, "API connection failed, using arcade emulation");
+ }
+ }
+ }
+
+ // Offline / Sandbox Mode: Emulate retro 8-bit agent reply with typing effect
+ let _ = event_tx
+ .send(RuntimeEvent::ThinkingDelta(format!(
+ "[{}] Channeling mana via {}...",
+ input.kwant.name, target_model
+ )))
+ .await;
+ tokio::time::sleep(Duration::from_millis(50)).await;
+
+ let response_text = format!(
+ "⚔️ [{}] \"Quest acknowledged! I have received your command: '{}'. Ready for action.\"",
+ input.kwant.name, input.prompt
+ );
+
+ // Stream tokens in chunks
+ for word in response_text.split(' ') {
+ let chunk = format!("{} ", word);
+ let _ = event_tx.send(RuntimeEvent::TextDelta(chunk)).await;
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+
+ let tokens = response_text.len() / 4 + 10;
+ let duration = start.elapsed().as_millis() as u64;
+
+ let _ = event_tx
+ .send(RuntimeEvent::TurnComplete {
+ tokens,
+ duration_ms: duration,
+ })
+ .await;
+
+ Ok(TurnOutput {
+ text: response_text,
+ reasoning: Some(format!("Model: {}", target_model)),
+ tokens_used: tokens,
+ })
+ }
+}
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
new file mode 100644
index 00000000..9abf194a
--- /dev/null
+++ b/src/drivers/cli.rs
@@ -0,0 +1,89 @@
+use super::{events::RuntimeEvent, Driver, DriverError, TurnInput, TurnOutput};
+use async_trait::async_trait;
+use std::process::Stdio;
+use std::time::Instant;
+use tokio::io::AsyncReadExt;
+use tokio::process::Command;
+use tokio::sync::mpsc;
+
+#[derive(Clone, Debug, Default)]
+pub struct CliDriver {
+ pub cli_binary: Option<String>,
+}
+
+impl CliDriver {
+ pub fn new(cli_binary: Option<String>) -> Self {
+ Self { cli_binary }
+ }
+}
+
+#[async_trait]
+impl Driver for CliDriver {
+ async fn stream_turn(
+ &self,
+ input: TurnInput,
+ event_tx: mpsc::Sender<RuntimeEvent>,
+ ) -> Result<TurnOutput, DriverError> {
+ let start = Instant::now();
+ let bin = self.cli_binary.as_deref().unwrap_or("claude");
+
+ let mut cmd = Command::new(bin);
+ cmd.arg("--print").arg(&input.prompt);
+ cmd.stdout(Stdio::piped());
+ cmd.stderr(Stdio::piped());
+
+ match cmd.spawn() {
+ Ok(mut child) => {
+ let mut stdout = child.stdout.take().unwrap();
+ let mut output_str = String::new();
+ let mut buffer = [0u8; 1024];
+
+ while let Ok(n) = stdout.read(&mut buffer).await {
+ if n == 0 {
+ break;
+ }
+ let chunk = String::from_utf8_lossy(&buffer[..n]).to_string();
+ let _ = event_tx.send(RuntimeEvent::TextDelta(chunk.clone())).await;
+ output_str.push_str(&chunk);
+ }
+
+ let _ = child.wait().await;
+ let duration = start.elapsed().as_millis() as u64;
+ let tokens = output_str.len() / 4;
+
+ let _ = event_tx
+ .send(RuntimeEvent::TurnComplete {
+ tokens,
+ duration_ms: duration,
+ })
+ .await;
+
+ Ok(TurnOutput {
+ text: output_str,
+ reasoning: Some(format!("Executed via {} CLI", bin)),
+ tokens_used: tokens,
+ })
+ }
+ Err(e) => {
+ tracing::warn!(error = %e, binary = %bin, "CLI binary execution failed");
+ let msg = format!(
+ "⚠️ [{}] CLI `{}` is not installed or available on this host. ({})",
+ input.kwant.name, bin, e
+ );
+ let _ = event_tx.send(RuntimeEvent::TextDelta(msg.clone())).await;
+ let _ = event_tx
+ .send(RuntimeEvent::TurnComplete {
+ tokens: 15,
+ duration_ms: start.elapsed().as_millis() as u64,
+ })
+ .await;
+
+ Ok(TurnOutput {
+ text: msg,
+ reasoning: None,
+ tokens_used: 15,
+ })
+ }
+ }
+ }
+}
diff --git a/src/drivers/events.rs b/src/drivers/events.rs
new file mode 100644
index 00000000..8b506af3
--- /dev/null
+++ b/src/drivers/events.rs
@@ -0,0 +1,31 @@
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(tag = "type", content = "data")]
+pub enum RuntimeEvent {
+ TextDelta(String),
+ ThinkingDelta(String),
+ ToolCallPending {
+ id: String,
+ name: String,
+ args: Value,
+ },
+ ToolCallCompleted {
+ id: String,
+ result: Value,
+ },
+ ApprovalRequired {
+ id: String,
+ tool_name: String,
+ details: Value,
+ },
+ TurnComplete {
+ tokens: usize,
+ duration_ms: u64,
+ },
+ Error {
+ code: String,
+ message: String,
+ },
+}
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
new file mode 100644
index 00000000..036da3cc
--- /dev/null
+++ b/src/drivers/mod.rs
@@ -0,0 +1,59 @@
+pub mod api;
+pub mod cli;
+pub mod events;
+
+pub use api::ApiDriver;
+pub use cli::CliDriver;
+pub use events::RuntimeEvent;
+
+use crate::db::models::{Kwant, Message};
+use async_trait::async_trait;
+use serde::{Deserialize, Serialize};
+use thiserror::Error;
+use tokio::sync::mpsc;
+
+#[derive(Error, Debug)]
+pub enum DriverError {
+ #[error("I/O or Subprocess error: {0}")]
+ Io(#[from] std::io::Error),
+
+ #[error("HTTP API error: {0}")]
+ Http(#[from] reqwest::Error),
+
+ #[error("Driver execution error: {0}")]
+ Execution(String),
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TurnInput {
+ pub thread_id: String,
+ pub kwant: Kwant,
+ pub prompt: String,
+ pub history: Vec<Message>,
+ pub model_override: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TurnOutput {
+ pub text: String,
+ pub reasoning: Option<String>,
+ pub tokens_used: usize,
+}
+
+#[async_trait]
+pub trait Driver: Send + Sync {
+ async fn stream_turn(
+ &self,
+ input: TurnInput,
+ event_tx: mpsc::Sender<RuntimeEvent>,
+ ) -> Result<TurnOutput, DriverError>;
+}
+
+/// Factory function creating the appropriate driver for a given Kwant
+pub fn create_driver_for_kwant(kwant: &Kwant) -> Box<dyn Driver> {
+ if kwant.driver_type == "cli" {
+ Box::new(CliDriver::new(Some("claude".into())))
+ } else {
+ Box::new(ApiDriver::new(None, None))
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
index 2ed5b122..ad385add 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,7 +1,9 @@
pub mod config;
pub mod db;
+pub mod drivers;
pub mod router;
pub use config::{Config, ConfigError};
pub use db::{Database, DbError};
+pub use drivers::{create_driver_for_kwant, ApiDriver, CliDriver, Driver, DriverError, RuntimeEvent, TurnInput, TurnOutput};
pub use router::{LayaRouter, RouteDecision, RouterError};
diff --git a/tests/driver_test.rs b/tests/driver_test.rs
new file mode 100644
index 00000000..f80faac0
--- /dev/null
+++ b/tests/driver_test.rs
@@ -0,0 +1,108 @@
+use kwnt::drivers::{
+ events::RuntimeEvent,
+ Driver, TurnInput, TurnOutput,
+};
+use kwnt::db::models::Kwant;
+use serde_json::json;
+use tokio::sync::mpsc;
+
+#[test]
+fn test_runtime_event_serialization() {
+ let ev = RuntimeEvent::TextDelta("Press Start!".into());
+ let serialized = serde_json::to_string(&ev).unwrap();
+ assert!(serialized.contains("TextDelta"));
+ assert!(serialized.contains("Press Start!"));
+
+ let approval_ev = RuntimeEvent::ApprovalRequired {
+ id: "app-1".into(),
+ tool_name: "execute_shell".into(),
+ details: json!({"command": "cargo build"}),
+ };
+ let app_str = serde_json::to_string(&approval_ev).unwrap();
+ assert!(app_str.contains("ApprovalRequired"));
+ assert!(app_str.contains("execute_shell"));
+}
+
+struct TestDriver;
+
+#[async_trait::async_trait]
+impl Driver for TestDriver {
+ async fn stream_turn(
+ &self,
+ input: TurnInput,
+ event_tx: mpsc::Sender<RuntimeEvent>,
+ ) -> Result<TurnOutput, kwnt::drivers::DriverError> {
+ event_tx
+ .send(RuntimeEvent::ThinkingDelta("Calculating combo...".into()))
+ .await
+ .unwrap();
+ event_tx
+ .send(RuntimeEvent::TextDelta(format!("Player says: {}", input.prompt)))
+ .await
+ .unwrap();
+ event_tx
+ .send(RuntimeEvent::TurnComplete {
+ tokens: 42,
+ duration_ms: 120,
+ })
+ .await
+ .unwrap();
+
+ Ok(TurnOutput {
+ text: format!("Player says: {}", input.prompt),
+ reasoning: Some("Calculating combo...".into()),
+ tokens_used: 42,
+ })
+ }
+}
+
+#[tokio::test]
+async fn test_mock_driver_streaming() {
+ let driver = TestDriver;
+ let (tx, mut rx) = mpsc::channel(16);
+
+ let dummy_kwant = Kwant {
+ id: "k-1".into(),
+ name: "CyberMage".into(),
+ title: "Arcane".into(),
+ persona_prompt: "Wizard".into(),
+ avatar_sprite: "cyber_mage".into(),
+ driver_type: "api".into(),
+ preferred_model: "grok".into(),
+ temperature: 0.7,
+ max_tokens: 2048,
+ level: 1,
+ turns_completed: 0,
+ created_at: None,
+ };
+
+ let input = TurnInput {
+ thread_id: "thread-1".into(),
+ kwant: dummy_kwant,
+ prompt: "Cast fireball".into(),
+ history: vec![],
+ model_override: None,
+ };
+
+ let handle = tokio::spawn(async move {
+ driver.stream_turn(input, tx).await.unwrap()
+ });
+
+ let mut events = vec![];
+ while let Some(ev) = rx.recv().await {
+ events.push(ev);
+ }
+
+ assert_eq!(events.len(), 3);
+ match &events[0] {
+ RuntimeEvent::ThinkingDelta(th) => assert_eq!(th, "Calculating combo..."),
+ _ => panic!("Expected thinking event"),
+ }
+ match &events[1] {
+ RuntimeEvent::TextDelta(t) => assert_eq!(t, "Player says: Cast fireball"),
+ _ => panic!("Expected text event"),
+ }
+
+ let output = handle.await.unwrap();
+ assert_eq!(output.tokens_used, 42);
+}