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: add Axum REST API and SSE event endpoints

Oleksandr Ivanchenko6c05544c2460
diff --git a/Cargo.lock b/Cargo.lock
index e917e3a7..136af894 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -616,6 +616,21 @@ dependencies = [
"percent-encoding",
]
+[[package]]
+name = "futures"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-executor",
+ "futures-io",
+ "futures-sink",
+ "futures-task",
+ "futures-util",
+]
+
[[package]]
name = "futures-channel"
version = "0.3.34"
@@ -689,6 +704,7 @@ version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
dependencies = [
+ "futures-channel",
"futures-core",
"futures-io",
"futures-macro",
@@ -1130,6 +1146,7 @@ dependencies = [
"chrono",
"clap",
"dirs",
+ "futures",
"reqwest",
"rust-embed",
"serde",
@@ -1138,6 +1155,7 @@ dependencies = [
"tempfile",
"thiserror 1.0.69",
"tokio",
+ "tokio-stream",
"toml",
"tower 0.4.13",
"tower-http 0.5.2",
@@ -1457,6 +1475,26 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+[[package]]
+name = "pin-project"
+version = "1.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924"
+dependencies = [
+ "pin-project-internal",
+]
+
+[[package]]
+name = "pin-project-internal"
+version = "1.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "pin-project-lite"
version = "0.2.17"
@@ -2446,6 +2484,7 @@ dependencies = [
"futures-core",
"pin-project-lite",
"tokio",
+ "tokio-util",
]
[[package]]
@@ -2509,6 +2548,10 @@ version = "0.4.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c"
dependencies = [
+ "futures-core",
+ "futures-util",
+ "pin-project",
+ "pin-project-lite",
"tower-layer",
"tower-service",
"tracing",
diff --git a/Cargo.toml b/Cargo.toml
index 4179ea10..e4e9afd7 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -15,12 +15,14 @@ path = "src/main.rs"
[dependencies]
tokio = { version = "1.40", features = ["full"] }
axum = { version = "0.7", features = ["macros"] }
-tower = "0.4"
+tower = { version = "0.4", features = ["util"] }
tower-http = { version = "0.5", features = ["cors", "fs", "trace"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sqlx = { version = "0.8", features = ["runtime-tokio-rustls", "sqlite", "migrate", "chrono"] }
reqwest = { version = "0.12", features = ["json", "stream"] }
+futures = "0.3"
+tokio-stream = { version = "0.1", features = ["sync"] }
rust-embed = "8.5"
clap = { version = "4.5", features = ["derive"] }
tracing = "0.1"
diff --git a/src/lib.rs b/src/lib.rs
index 70f6452c..06351a39 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -3,6 +3,7 @@ pub mod config;
pub mod db;
pub mod drivers;
pub mod router;
+pub mod server;
pub mod tools;
pub use broker::{ApprovalDecision, ApprovalRequest, PermissionBroker};
@@ -10,4 +11,5 @@ 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};
+pub use server::{create_router, AppState};
pub use tools::{ToolError, ToolRunner};
diff --git a/src/main.rs b/src/main.rs
index aeb549aa..1f2133d7 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,5 +1,12 @@
use clap::{Parser, Subcommand};
-use kwnt::config::Config;
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::Database,
+ router::LayaRouter,
+ server::{create_router, AppState},
+ tools::ToolRunner,
+};
use std::path::PathBuf;
#[derive(Parser, Debug)]
@@ -41,7 +48,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
};
match cli.command {
- Some(Commands::Serve { host, port, data_dir, laya_url }) => {
+ Some(Commands::Serve {
+ host,
+ port,
+ data_dir,
+ laya_url,
+ }) => {
if let Some(h) = host {
config.host = h;
}
@@ -55,6 +67,17 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
config.laya_url = l;
}
+ let db = Database::init(&config.data_dir).await?;
+ let tools = ToolRunner::new(config.data_dir.join("workspace"));
+ let broker = PermissionBroker::new();
+ let router = LayaRouter::new(config.laya_url.clone());
+
+ let state = AppState::new(config.clone(), db, tools, broker, router);
+ let app = create_router(state);
+
+ let addr = format!("{}:{}", config.host, config.port);
+ let listener = tokio::net::TcpListener::bind(&addr).await?;
+
tracing::info!(
host = %config.host,
port = config.port,
@@ -63,9 +86,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
"Starting Kwants engine..."
);
println!(
- "🕹️ Kwants 8-Bit AI Agent Platform listening at http://{}:{}",
- config.host, config.port
+ "🕹️ Kwants 8-Bit AI Agent Platform listening at http://{}",
+ addr
);
+
+ axum::serve(listener, app).await?;
}
None => {
println!("🕹️ Kwants: 8-Bit AI Agent Platform in Rust");
diff --git a/src/server/mod.rs b/src/server/mod.rs
new file mode 100644
index 00000000..6ad43a39
--- /dev/null
+++ b/src/server/mod.rs
@@ -0,0 +1,63 @@
+pub mod routes;
+pub mod sse;
+
+use crate::broker::PermissionBroker;
+use crate::config::Config;
+use crate::db::Database;
+use crate::drivers::events::RuntimeEvent;
+use crate::router::LayaRouter;
+use crate::tools::ToolRunner;
+use axum::{
+ routing::{get, post},
+ Router,
+};
+use tokio::sync::broadcast;
+use tower_http::cors::{Any, CorsLayer};
+
+#[derive(Clone)]
+pub struct AppState {
+ pub config: Config,
+ pub db: Database,
+ pub tools: ToolRunner,
+ pub broker: PermissionBroker,
+ pub router: LayaRouter,
+ pub event_sender: broadcast::Sender<RuntimeEvent>,
+}
+
+impl AppState {
+ pub fn new(
+ config: Config,
+ db: Database,
+ tools: ToolRunner,
+ broker: PermissionBroker,
+ router: LayaRouter,
+ ) -> Self {
+ let (event_sender, _) = broadcast::channel(128);
+ Self {
+ config,
+ db,
+ tools,
+ broker,
+ router,
+ event_sender,
+ }
+ }
+}
+
+pub fn create_router(state: AppState) -> Router {
+ let cors = CorsLayer::new()
+ .allow_origin(Any)
+ .allow_methods(Any)
+ .allow_headers(Any);
+
+ Router::new()
+ .route("/api/health", get(routes::health))
+ .route("/api/kwants", get(routes::list_kwants).post(routes::create_kwant))
+ .route("/api/channels", get(routes::list_channels).post(routes::create_channel))
+ .route("/api/channels/:id/messages", get(routes::list_messages))
+ .route("/api/chat/send", post(routes::send_chat))
+ .route("/api/approvals/:id/resolve", post(routes::resolve_approval))
+ .route("/api/events", get(sse::sse_handler))
+ .layer(cors)
+ .with_state(state)
+}
diff --git a/src/server/routes.rs b/src/server/routes.rs
new file mode 100644
index 00000000..c897e633
--- /dev/null
+++ b/src/server/routes.rs
@@ -0,0 +1,241 @@
+use super::AppState;
+use crate::broker::ApprovalDecision;
+use crate::db::models::*;
+use crate::drivers::{create_driver_for_kwant, TurnInput};
+use axum::{
+ extract::{Path, State},
+ http::StatusCode,
+ response::IntoResponse,
+ Json,
+};
+use serde::{Deserialize, Serialize};
+use serde_json::json;
+use tokio::sync::mpsc;
+
+#[derive(Serialize)]
+pub struct HealthResponse {
+ pub status: &'static str,
+ pub app: &'static str,
+ pub version: &'static str,
+ pub laya_url: String,
+}
+
+pub async fn health(State(state): State<AppState>) -> impl IntoResponse {
+ Json(HealthResponse {
+ status: "ok",
+ app: "kwnt",
+ version: env!("CARGO_PKG_VERSION"),
+ laya_url: state.config.laya_url.clone(),
+ })
+}
+
+pub async fn list_kwants(State(state): State<AppState>) -> Result<Json<Vec<Kwant>>, StatusCode> {
+ state
+ .db
+ .list_kwants()
+ .await
+ .map(Json)
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
+}
+
+pub async fn create_kwant(
+ State(state): State<AppState>,
+ Json(payload): Json<NewKwant>,
+) -> Result<Json<Kwant>, StatusCode> {
+ state
+ .db
+ .create_kwant(&payload)
+ .await
+ .map(Json)
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
+}
+
+pub async fn list_channels(State(state): State<AppState>) -> Result<Json<Vec<Channel>>, StatusCode> {
+ state
+ .db
+ .list_channels()
+ .await
+ .map(Json)
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
+}
+
+pub async fn create_channel(
+ State(state): State<AppState>,
+ Json(payload): Json<NewChannel>,
+) -> Result<Json<Channel>, StatusCode> {
+ state
+ .db
+ .create_channel(&payload)
+ .await
+ .map(Json)
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
+}
+
+pub async fn list_messages(
+ State(state): State<AppState>,
+ Path(channel_or_kwant_id): Path<String>,
+) -> Result<Json<Vec<Message>>, StatusCode> {
+ state
+ .db
+ .list_messages(&channel_or_kwant_id, 100)
+ .await
+ .map(Json)
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
+}
+
+#[derive(Debug, Deserialize)]
+pub struct SendChatPayload {
+ pub channel_id: Option<String>,
+ pub kwant_id: Option<String>,
+ pub prompt: String,
+ pub sender_id: String,
+}
+
+pub async fn send_chat(
+ State(state): State<AppState>,
+ Json(payload): Json<SendChatPayload>,
+) -> Result<Json<serde_json::Value>, StatusCode> {
+ // 1. Identify Kwant to execute
+ let kwants = state
+ .db
+ .list_kwants()
+ .await
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
+
+ let target_kwant = if let Some(kid) = &payload.kwant_id {
+ kwants.into_iter().find(|k| &k.id == kid)
+ } else if let Some(cid) = &payload.channel_id {
+ if let Ok(Some(channel)) = state.db.get_channel(cid).await {
+ kwants.into_iter().find(|k| k.id == channel.lead_kwant_id)
+ } else {
+ kwants.into_iter().next()
+ }
+ } else {
+ kwants.into_iter().next()
+ }
+ .ok_or(StatusCode::BAD_REQUEST)?;
+
+ // 2. Insert user message to DB
+ let user_msg = NewMessage {
+ channel_id: payload.channel_id.clone(),
+ direct_kwant_id: payload.kwant_id.clone(),
+ sender_role: "user".into(),
+ sender_id: payload.sender_id.clone(),
+ text: payload.prompt.clone(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: payload.prompt.len() as i64 / 4,
+ };
+ let saved_user_msg = state
+ .db
+ .insert_message(&user_msg)
+ .await
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
+
+ // 3. Route model using Laya if kwant preferred_model is "auto"
+ let model_override = if target_kwant.preferred_model == "auto" {
+ let route = state
+ .router
+ .route_prompt(&payload.prompt, "chat")
+ .await
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
+ Some(route.selected_model)
+ } else {
+ None
+ };
+
+ // 4. Load recent conversation history
+ let context_id = payload
+ .channel_id
+ .as_deref()
+ .or(payload.kwant_id.as_deref())
+ .unwrap_or(&target_kwant.id);
+ let history = state
+ .db
+ .list_messages(context_id, 20)
+ .await
+ .unwrap_or_default();
+
+ // 5. Build turn input and driver
+ let driver = create_driver_for_kwant(&target_kwant);
+ let turn_input = TurnInput {
+ thread_id: context_id.to_string(),
+ kwant: target_kwant.clone(),
+ prompt: payload.prompt.clone(),
+ history,
+ model_override,
+ };
+
+ // 6. Spawn driver execution in background, feeding events into the SSE event_sender
+ let event_broadcast = state.event_sender.clone();
+ let db = state.db.clone();
+ let channel_id = payload.channel_id.clone();
+ let kwant_id = payload.kwant_id.clone();
+ let target_kwant_clone = target_kwant.clone();
+
+ tokio::spawn(async move {
+ let (driver_tx, mut driver_rx) = mpsc::channel(32);
+
+ let driver_task = tokio::spawn(async move {
+ driver.stream_turn(turn_input, driver_tx).await
+ });
+
+ // Forward events to SSE clients
+ while let Some(event) = driver_rx.recv().await {
+ let _ = event_broadcast.send(event);
+ }
+
+ if let Ok(Ok(output)) = driver_task.await {
+ // Save assistant message to DB
+ let asst_msg = NewMessage {
+ channel_id,
+ direct_kwant_id: kwant_id,
+ sender_role: "kwant".into(),
+ sender_id: target_kwant_clone.id,
+ text: output.text,
+ reasoning_content: output.reasoning,
+ tool_calls: None,
+ tokens_used: output.tokens_used as i64,
+ };
+ let _ = db.insert_message(&asst_msg).await;
+ }
+ });
+
+ Ok(Json(json!({
+ "status": "dispatched",
+ "user_message_id": saved_user_msg.id,
+ "kwant": target_kwant.name
+ })))
+}
+
+#[derive(Debug, Deserialize)]
+pub struct ResolveApprovalPayload {
+ pub decision: String, // "allow_once", "always_allow", "deny"
+}
+
+pub async fn resolve_approval(
+ State(state): State<AppState>,
+ Path(ticket_id): Path<String>,
+ Json(payload): Json<ResolveApprovalPayload>,
+) -> Result<Json<serde_json::Value>, StatusCode> {
+ let decision = match payload.decision.as_str() {
+ "allow_once" => ApprovalDecision::AllowOnce,
+ "always_allow" => ApprovalDecision::AlwaysAllowSession,
+ _ => ApprovalDecision::Deny,
+ };
+
+ let status_str = match decision {
+ ApprovalDecision::AllowOnce => "allowed_once",
+ ApprovalDecision::AlwaysAllowSession => "always_allowed",
+ ApprovalDecision::Deny => "denied",
+ };
+
+ let _ = state.db.update_approval_status(&ticket_id, status_str).await;
+ let resolved = state.broker.resolve(&ticket_id, decision).await;
+
+ Ok(Json(json!({
+ "ticket_id": ticket_id,
+ "resolved": resolved,
+ "status": status_str
+ })))
+}
diff --git a/src/server/sse.rs b/src/server/sse.rs
new file mode 100644
index 00000000..4ab81264
--- /dev/null
+++ b/src/server/sse.rs
@@ -0,0 +1,24 @@
+use axum::{
+ extract::State,
+ response::sse::{Event, KeepAlive, Sse},
+};
+use futures::stream::Stream;
+use std::convert::Infallible;
+use tokio_stream::wrappers::BroadcastStream;
+use tokio_stream::StreamExt;
+use super::AppState;
+
+pub async fn sse_handler(
+ State(state): State<AppState>,
+) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
+ let rx = state.event_sender.subscribe();
+ let stream = BroadcastStream::new(rx).filter_map(|msg| match msg {
+ Ok(event) => {
+ let json_str = serde_json::to_string(&event).unwrap_or_default();
+ Some(Ok(Event::default().data(json_str)))
+ }
+ Err(_) => None,
+ });
+
+ Sse::new(stream).keep_alive(KeepAlive::default())
+}
diff --git a/tests/server_test.rs b/tests/server_test.rs
new file mode 100644
index 00000000..9cd557a6
--- /dev/null
+++ b/tests/server_test.rs
@@ -0,0 +1,60 @@
+use axum::{
+ body::Body,
+ http::{Request, StatusCode},
+};
+use kwnt::{
+ config::Config,
+ db::Database,
+ server::{create_router, AppState},
+ tools::ToolRunner,
+ broker::PermissionBroker,
+ router::LayaRouter,
+};
+use serde_json::json;
+use tempfile::tempdir;
+use tower::ServiceExt;
+
+#[tokio::test]
+async fn test_server_health_and_kwants() {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config::default();
+ let tools = ToolRunner::new(tmp.path().join("workspace"));
+ let broker = PermissionBroker::new();
+ let router = LayaRouter::new(config.laya_url.clone());
+
+ let state = AppState::new(config, db, tools, broker, router);
+ let app = create_router(state);
+
+ // 1. Health check
+ let req = Request::builder()
+ .uri("/api/health")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.clone().oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ // 2. List Kwants
+ let req = Request::builder()
+ .uri("/api/kwants")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.clone().oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ // 3. Send chat message
+ let send_body = json!({
+ "channel_id": null,
+ "kwant_id": null,
+ "prompt": "Hello 8-bit realm!",
+ "sender_id": "player1"
+ });
+ let req = Request::builder()
+ .method("POST")
+ .uri("/api/chat/send")
+ .header("content-type", "application/json")
+ .body(Body::from(serde_json::to_vec(&send_body).unwrap()))
+ .unwrap();
+ let resp = app.clone().oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+}