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
Ship Laya with Kwant: managed sidecar, status indicator, Docker Compose
Oleksandr Ivanchenko0fba8db42071
diff --git a/.dockerignore b/.dockerignorenew file mode 100644index 00000000..f0d3dfba--- /dev/null+++ b/.dockerignore@@ -0,0 +1,7 @@+target+.git+.superpowers+frontend/node_modules+frontend/dist+**/*.db+**/*.db-*diff --git a/.gitignore b/.gitignoreindex 6c28c69a..f1184311 100644--- a/.gitignore+++ b/.gitignore@@ -6,4 +6,3 @@ dist/*.db-wal*.db-shm.DS_Store-.laya-venv/diff --git a/README.md b/README.mdindex 0315bda2..c0e0da00 100644--- a/README.md+++ b/README.md@@ -61,6 +61,7 @@ ExecStart=/usr/local/bin/kwnt serve --host 0.0.0.0 --port 8799Restart=alwaysEnvironment=KWNT_DATA_DIR=/var/lib/kwntEnvironment=LAYA_URL=http://127.0.0.1:8000+# kwnt installs and supervises Laya under KWNT_DATA_DIR/laya; set KWNT_LAYA_MANAGED=0 to run your ownEnvironment=XAI_API_KEY=your_xai_key_hereEnvironment=ANTHROPIC_API_KEY=your_claude_key_here@@ -77,15 +78,38 @@ systemctl enable --now kwnt## 🔮 Laya Model Router (`convaiinnovations/laya`)-When a Kwant's model is set to `"auto"` (the default), `kwnt` queries Laya's Jev-compatible non-autoregressive decision model on `/v1/systemone`:+Laya picks which agent answers in a channel and which model and effort each agent uses when its model is `"auto"`. It runs as a small Python service speaking `/v1/systemone`.++**`kwnt serve` manages Laya for you.** If nothing answers at `laya_url` (default `http://127.0.0.1:8000`), kwnt:++1. installs `laya[serve]==0.4.8` into `~/.kwnt/laya/venv` on first run, using [`uv`](https://docs.astral.sh/uv/) when present (it fetches Python too) or `python3 -m venv` otherwise;+2. starts `laya-serve` on the configured port, downloading the English checkpoint (~420 MB) into `~/.kwnt/laya/hf` on first start;+3. restarts it with backoff if it exits, and stops it when kwnt shuts down.++The header shows the router status (green online, amber installing or loading, red offline), and `GET /api/laya/status` returns it with the failure reason. Logs are in `~/.kwnt/laya/laya.log` and `install.log`. While Laya is unavailable, kwnt routes by keyword and says so in the routing card.++| Setting | `config.toml` | Environment | Default |+|---|---|---|---|+| Laya URL | `laya_url` | `LAYA_URL` | `http://127.0.0.1:8000` |+| Manage a local sidecar | `laya_managed` | `KWNT_LAYA_MANAGED=0` to disable, or `kwnt serve --no-laya` | `true` |+| Checkpoints to preload | `laya_models` | `KWNT_LAYA_MODELS` | `english` |+| Use an existing `laya-serve` binary | | `KWNT_LAYA_SERVE_BIN` | |++kwnt only starts Laya for loopback URLs. If Laya already answers, for example from Docker, kwnt uses it as is.++**Networks that block Hugging Face.** The first start needs `huggingface.co`. If a proxy blocks it, start kwnt once on an open network, or copy an existing `~/.kwnt/laya/hf` from another machine; after that Laya starts offline.++---++## 🐳 Docker Compose (VPS)++`docker-compose.yml` runs kwnt with a Laya image that has the weights baked in, so the server never downloads them at runtime:```bash-# Start Laya service sidecar (optional)-pip install "laya[serve]"-laya-serve --port 8000+docker compose up -d --build # UI on http://127.0.0.1:8799```-If Laya is offline, `kwnt` automatically engages a local heuristic router with zero interruption.+The `laya` image (`docker/laya.Dockerfile`) uses CPU PyTorch and preloads the checkpoints listed in the `LAYA_MODELS` build arg. kwnt runs with `KWNT_LAYA_MANAGED=0` and `LAYA_URL=http://laya:8000`; data persists in the `kwnt-data` volume. Put a TLS reverse proxy in front as described in [browser service and VPS hosting](docs/browser-service.md).---diff --git a/docker-compose.yml b/docker-compose.ymlnew file mode 100644index 00000000..10189286--- /dev/null+++ b/docker-compose.yml@@ -0,0 +1,32 @@+# Kwant + Laya for a VPS: docker compose up -d --build+# The UI is bound to localhost; put a TLS reverse proxy in front (see docs/browser-service.md).+services:+ laya:+ build:+ context: docker+ dockerfile: laya.Dockerfile+ args:+ LAYA_MODELS: english+ image: kwnt-laya:0.4.8+ restart: unless-stopped++ kwnt:+ build:+ context: .+ dockerfile: docker/kwnt.Dockerfile+ image: kwnt:latest+ restart: unless-stopped+ ports:+ - "127.0.0.1:8799:8799"+ environment:+ LAYA_URL: http://laya:8000+ KWNT_LAYA_MANAGED: "0"+ # KWNT_BROWSER_CDP_URL: http://browser:9222+ volumes:+ - kwnt-data:/data+ depends_on:+ laya:+ condition: service_started++volumes:+ kwnt-data:diff --git a/docker/kwnt.Dockerfile b/docker/kwnt.Dockerfilenew file mode 100644index 00000000..54dae886--- /dev/null+++ b/docker/kwnt.Dockerfile@@ -0,0 +1,29 @@+# Kwant server: React UI embedded in a single Rust binary.+FROM node:20-bookworm-slim AS web+WORKDIR /app/frontend+COPY frontend/package.json frontend/package-lock.json ./+RUN npm ci+COPY frontend/ ./+RUN npm run build++FROM rust:1-bookworm AS build+WORKDIR /app+COPY Cargo.toml Cargo.lock ./+COPY src src+COPY docker docker+COPY --from=web /app/frontend/dist frontend/dist+RUN cargo build --release --locked --bin kwnt++FROM debian:bookworm-slim+RUN apt-get update \+ && apt-get install -y --no-install-recommends ca-certificates \+ && rm -rf /var/lib/apt/lists/*+COPY --from=build /app/target/release/kwnt /usr/local/bin/kwnt+ENV KWNT_HOST=0.0.0.0 \+ KWNT_PORT=8799 \+ KWNT_DATA_DIR=/data \+ KWNT_LAYA_MANAGED=0 \+ LAYA_URL=http://laya:8000+VOLUME /data+EXPOSE 8799+CMD ["kwnt", "serve"]diff --git a/docker/laya.Dockerfile b/docker/laya.Dockerfilenew file mode 100644index 00000000..01e665a6--- /dev/null+++ b/docker/laya.Dockerfile@@ -0,0 +1,26 @@+# Laya routing sidecar with model weights baked in, so it starts offline.+FROM python:3.12-slim++ARG LAYA_VERSION=0.4.8+ARG LAYA_MODELS=english++ENV PIP_NO_CACHE_DIR=1 \+ PYTHONUNBUFFERED=1 \+ HF_HOME=/opt/hf \+ LAYA_HOST=0.0.0.0 \+ LAYA_PORT=8000 \+ LAYA_MODELS=${LAYA_MODELS} \+ LAYA_DEFAULT_MODEL=english++# CPU-only PyTorch keeps the image a fraction of the CUDA build's size.+RUN pip install --index-url https://download.pytorch.org/whl/cpu torch \+ && pip install "laya[serve]==${LAYA_VERSION}"++# Download and load the checkpoints once at build time.+RUN python -c "from laya.serve import build_router; build_router()"++ENV HF_HUB_OFFLINE=1+EXPOSE 8000+HEALTHCHECK --interval=10s --timeout=3s --start-period=120s --retries=3 \+ CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health')"+CMD ["laya-serve"]diff --git a/frontend/src/components/AppHeader.tsx b/frontend/src/components/AppHeader.tsxindex 2b5a3105..50dfbdf5 100644--- a/frontend/src/components/AppHeader.tsx+++ b/frontend/src/components/AppHeader.tsx@@ -9,12 +9,69 @@ interface AppHeaderProps {activeModel?: string;}+type LayaState = 'unknown' | 'external' | 'installing' | 'starting' | 'online' | 'offline' | 'failed';++interface LayaStatus {+ state: LayaState;+ detail: string;+ url: string;+ managed: boolean;+}++const useLayaStatus = (): LayaStatus | null => {+ const [status, setStatus] = React.useState<LayaStatus | null>(null);+ React.useEffect(() => {+ let cancelled = false;+ let timer: ReturnType<typeof setTimeout>;+ const poll = async () => {+ let next: LayaStatus | null = null;+ try {+ const res = await fetch('/api/laya/status');+ if (res.ok) next = await res.json();+ } catch {+ // server restarting; keep the last known status+ }+ if (cancelled) return;+ if (next) setStatus(next);+ const up = next?.state === 'online' || next?.state === 'external';+ timer = setTimeout(poll, up ? 20000 : 4000);+ };+ poll();+ return () => {+ cancelled = true;+ clearTimeout(timer);+ };+ }, []);+ return status;+};++const layaPill = (status: LayaStatus | null, activeModel: string) => {+ const ready = activeModel === 'auto' ? 'Laya • Dynamic Effort' : `Laya ➔ ${activeModel}`;+ switch (status?.state) {+ case 'online':+ case 'external':+ return { dot: 'bg-emerald-400', label: ready };+ case 'installing':+ return { dot: 'bg-amber-400 animate-pulse', label: 'Laya installing… • keyword routing' };+ case 'starting':+ return { dot: 'bg-amber-400 animate-pulse', label: 'Laya loading model… • keyword routing' };+ case 'failed':+ case 'offline':+ return { dot: 'bg-rose-500', label: 'Laya offline • keyword routing' };+ default:+ return { dot: 'bg-zinc-500 animate-pulse', label: 'Laya…' };+ }+};+export const AppHeader: React.FC<AppHeaderProps> = ({onOpenSettings,tokensUsed,activeModel = 'auto',}) => {const [sfxMuted, setSfxMuted] = React.useState(isSfxMuted());+ const laya = useLayaStatus();+ const pill = layaPill(laya, activeModel);+ const pillTitle = laya ? `${laya.detail || laya.state}\n${laya.url}${laya.managed ? ' (managed by Kwant)' : ''}` : 'Checking Laya…';const handleToggleSfx = () => {const next = toggleSfxMute();@@ -35,12 +92,15 @@ export const AppHeader: React.FC<AppHeaderProps> = ({</div>{/* Center: Laya Decision Engine pill */}- <div className="hidden md:flex items-center gap-2 bg-zinc-950/60 border border-zinc-800 px-3 py-1 rounded-full text-xs text-zinc-400 shadow-inner">- <span className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse" />+ <div+ className="hidden md:flex items-center gap-2 bg-zinc-950/60 border border-zinc-800 px-3 py-1 rounded-full text-xs text-zinc-400 shadow-inner"+ title={pillTitle}+ >+ <span className={`w-2 h-2 rounded-full ${pill.dot}`} /><span className="text-zinc-500 font-medium">ROUTER:</span><span className="text-zinc-200 font-semibold flex items-center gap-1"><Cpu size={13} className="text-sky-400" />- <span>{activeModel === 'auto' ? 'Laya (33ms) • Dynamic Effort' : `Laya ➔ ${activeModel}`}</span>+ <span>{pill.label}</span></span></div>diff --git a/src/config.rs b/src/config.rsindex 3d159dd2..d8a6ed51 100644--- a/src/config.rs+++ b/src/config.rs@@ -34,6 +34,14 @@ fn default_laya_url() -> String {DEFAULT_LAYA_URL.to_string()}+fn default_true() -> bool {+ true+}++fn default_laya_models() -> String {+ "english".to_string()+}+fn default_fallback_model() -> String {DEFAULT_FALLBACK_MODEL.to_string()}@@ -62,6 +70,14 @@ pub struct Config {#[serde(default = "default_laya_url")]pub laya_url: String,+ /// When true, `kwnt serve` installs, starts and supervises a local `laya-serve`.+ #[serde(default = "default_true")]+ pub laya_managed: bool,++ /// Laya checkpoints the managed sidecar preloads (comma list).+ #[serde(default = "default_laya_models")]+ pub laya_models: String,+#[serde(default = "default_fallback_model")]pub default_fallback_model: String,@@ -77,6 +93,8 @@ impl Default for Config {port: default_port(),data_dir: default_data_dir(),laya_url: default_laya_url(),+ laya_managed: true,+ laya_models: default_laya_models(),default_fallback_model: default_fallback_model(),browser_cdp_url: None,}@@ -154,6 +172,14 @@ impl Config {self.laya_url = url;}}+ if let Ok(v) = std::env::var("KWNT_LAYA_MANAGED") {+ self.laya_managed = !matches!(v.trim().to_lowercase().as_str(), "0" | "false" | "no" | "off");+ }+ if let Ok(models) = std::env::var("KWNT_LAYA_MODELS") {+ if !models.trim().is_empty() {+ self.laya_models = models.trim().to_string();+ }+ }if let Ok(model) = std::env::var("KWNT_DEFAULT_FALLBACK_MODEL").or_else(|_| std::env::var("DEFAULT_FALLBACK_MODEL")){diff --git a/src/main.rs b/src/main.rsindex 688eeefd..0786dcb7 100644--- a/src/main.rs+++ b/src/main.rs@@ -3,11 +3,15 @@ use kwnt::{broker::PermissionBroker,config::Config,db::Database,- router::LayaRouter,+ router::{+ sidecar::{self, SidecarOptions},+ LayaRouter,+ },server::{create_router, AppState},tools::ToolRunner,};use std::path::PathBuf;+use tokio_util::sync::CancellationToken;#[derive(Parser, Debug)]#[command(name = "kwnt", author, version, about = "Kwants: Multi-Agent AI Platform in Rust")]@@ -35,6 +39,9 @@ pub enum Commands {#[arg(long, help = "Laya router service URL")]laya_url: Option<String>,++ #[arg(long, help = "Do not install or start a local Laya router")]+ no_laya: bool,},/// Print the resolved config and whether local data files exist@@ -69,6 +76,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {host,port,laya_url,+ no_laya,}) => {if let Some(h) = host {config.host = h;@@ -79,18 +87,32 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {if let Some(l) = laya_url {config.laya_url = l;}+ if no_laya {+ config.laya_managed = false;+ }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());- if router.is_reachable().await {- println!("🔮 Laya router online at {}", router.base_url);- } else {+ let shutdown = CancellationToken::new();+ let sidecar = sidecar::spawn(+ router.clone(),+ SidecarOptions {+ data_dir: config.data_dir.clone(),+ managed: config.laya_managed,+ models: config.laya_models.clone(),+ },+ shutdown.clone(),+ );+ if config.laya_managed {println!(- "⚠️ Laya router not reachable at {} — using keyword routing. Start it with `laya-serve` (pip install \"laya[serve]\").",- router.base_url+ "🔮 Laya router at {} (managed; logs in {})",+ router.base_url,+ config.data_dir.join("laya").display());+ } else {+ println!("🔮 Laya router at {} (external)", router.base_url);}let state = AppState::new(config.clone(), db, tools, broker, router);@@ -111,7 +133,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {addr);- axum::serve(listener, app).await?;+ tokio::select! {+ res = axum::serve(listener, app) => res?,+ _ = shutdown_signal() => println!("Shutting down…"),+ }+ shutdown.cancel();+ let _ = tokio::time::timeout(std::time::Duration::from_secs(5), sidecar).await;}Some(Commands::Status) => print_status(&config),Some(Commands::Agents) => print_agents(&config).await?,@@ -147,7 +174,12 @@ fn print_status(config: &Config) {println!(" data dir {}", config.data_dir.display());println!(" config {config_label}");println!(" database {db_label}");- println!(" laya {}", config.laya_url);+ println!(+ " laya {} ({}; models {})",+ config.laya_url,+ if config.laya_managed { "managed" } else { "external" },+ config.laya_models+ );println!(" fallback {}", config.default_fallback_model);}@@ -206,3 +238,21 @@ async fn print_channels(config: &Config) -> Result<(), Box<dyn std::error::Error}Ok(())}++async fn shutdown_signal() {+ let ctrl_c = async {+ let _ = tokio::signal::ctrl_c().await;+ };+ #[cfg(unix)]+ let term = async {+ if let Ok(mut sig) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {+ sig.recv().await;+ }+ };+ #[cfg(not(unix))]+ let term = std::future::pending::<()>();+ tokio::select! {+ _ = ctrl_c => {},+ _ = term => {},+ }+}diff --git a/src/router/laya.rs b/src/router/laya.rsindex 27886420..8b8314ac 100644--- a/src/router/laya.rs+++ b/src/router/laya.rs@@ -1,12 +1,15 @@use super::{RouteDecision, RouterError};use reqwest::Client;use serde_json::json;+use super::sidecar::{LayaState, LayaStatus};+use std::sync::{Arc, RwLock};use std::time::Duration;#[derive(Clone, Debug)]pub struct LayaRouter {pub base_url: String,pub(crate) client: Client,+ status: Arc<RwLock<LayaStatus>>,}impl LayaRouter {@@ -16,7 +19,30 @@ impl LayaRouter {.build().unwrap_or_else(|_| Client::new());- Self { base_url: normalize_base_url(&base_url), client }+ let base_url = normalize_base_url(&base_url);+ let status = Arc::new(RwLock::new(LayaStatus::new(&base_url)));+ Self { base_url, client, status }+ }++ pub fn status(&self) -> LayaStatus {+ self.status.read().map(|s| s.clone()).unwrap_or_else(|_| LayaStatus::new(&self.base_url))+ }++ pub fn set_status(&self, state: LayaState, detail: &str, managed: bool) {+ if let Ok(mut s) = self.status.write() {+ s.state = state;+ s.detail = detail.to_string();+ s.managed = managed;+ }+ }++ /// Short note appended to routing reasons when Laya could not be asked.+ pub fn offline_note(&self) -> &'static str {+ match self.status().state {+ LayaState::Installing => "Laya is still installing, so this was a keyword match",+ LayaState::Starting => "Laya is still starting, so this was a keyword match",+ _ => "Laya is offline, so this was a keyword match",+ }}/// Returns true when the Laya sidecar answers on its health endpoint.diff --git a/src/router/mod.rs b/src/router/mod.rsindex 5c64cb91..483efacc 100644--- a/src/router/mod.rs+++ b/src/router/mod.rs@@ -1,5 +1,6 @@pub mod fallback;pub mod laya;+pub mod sidecar;pub mod tags;pub mod team;diff --git a/src/router/sidecar.rs b/src/router/sidecar.rsnew file mode 100644index 00000000..94f71b34--- /dev/null+++ b/src/router/sidecar.rs@@ -0,0 +1,326 @@+//! Managed Laya sidecar: installs `laya-serve` into the kwnt data dir on first run,+//! starts it next to the server, restarts it if it dies and reports its status.++use super::LayaRouter;+use serde::Serialize;+use std::path::{Path, PathBuf};+use std::process::Stdio;+use std::time::Duration;+use tokio::process::{Child, Command};+use tokio_util::sync::CancellationToken;++/// Pinned so every install routes the same way; bump deliberately.+pub const LAYA_PACKAGE: &str = "laya[serve]==0.4.8";++#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum LayaState {+ /// Not checked yet.+ Unknown,+ /// Reachable, but run by someone else (Docker, systemd, a dev shell).+ External,+ Installing,+ Starting,+ Online,+ Offline,+ Failed,+}++#[derive(Debug, Clone, Serialize)]+pub struct LayaStatus {+ pub state: LayaState,+ pub detail: String,+ pub url: String,+ pub managed: bool,+}++impl LayaStatus {+ pub fn new(url: &str) -> Self {+ Self { state: LayaState::Unknown, detail: String::new(), url: url.to_string(), managed: false }+ }++ pub fn is_up(&self) -> bool {+ matches!(self.state, LayaState::Online | LayaState::External)+ }+}++#[derive(Debug, Clone)]+pub struct SidecarOptions {+ pub data_dir: PathBuf,+ pub managed: bool,+ /// Comma list of Laya checkpoints to preload (`english`, `multilingual`, `typed-decisions`).+ pub models: String,+}++/// Starts the supervisor in the background. Cancel the token to stop the sidecar.+pub fn spawn(router: LayaRouter, opts: SidecarOptions, shutdown: CancellationToken) -> tokio::task::JoinHandle<()> {+ tokio::spawn(async move { supervise(router, opts, shutdown).await })+}++async fn supervise(router: LayaRouter, opts: SidecarOptions, shutdown: CancellationToken) {+ if router.is_reachable().await {+ router.set_status(LayaState::External, "Using the Laya service already running", false);+ return monitor_external(router, shutdown).await;+ }++ let port = match local_port(&router.base_url) {+ Some(port) if opts.managed => port,+ _ => {+ let why = if opts.managed {+ "Laya URL is not on this machine, so kwnt cannot start it"+ } else {+ "Laya is not answering and kwnt is not managing it; using keyword routing"+ };+ router.set_status(LayaState::Offline, why, false);+ return monitor_external(router, shutdown).await;+ }+ };++ let dir = opts.data_dir.join("laya");+ let _ = std::fs::create_dir_all(&dir);+ let mut backoff = Duration::from_secs(5);++ while !shutdown.is_cancelled() {+ let bin = match ensure_installed(&router, &dir).await {+ Ok(bin) => bin,+ Err(e) => {+ router.set_status(LayaState::Failed, &format!("Install failed: {e}"), true);+ if wait_or_cancel(&shutdown, Duration::from_secs(300)).await {+ return;+ }+ continue;+ }+ };++ router.set_status(+ LayaState::Starting,+ "Loading the routing model (the first start downloads it, ~420 MB)",+ true,+ );+ let log_path = dir.join("laya.log");+ let log_offset = std::fs::metadata(&log_path).map(|m| m.len()).unwrap_or(0);+ let mut child = match start(&bin, &dir, port, &opts.models) {+ Ok(child) => child,+ Err(e) => {+ router.set_status(LayaState::Failed, &format!("Could not start laya-serve: {e}"), true);+ if wait_or_cancel(&shutdown, backoff).await {+ return;+ }+ continue;+ }+ };++ let started = std::time::Instant::now();+ let exit = run_until_exit(&router, &mut child, &shutdown).await;+ if shutdown.is_cancelled() {+ let _ = child.kill().await;+ return;+ }++ let reason = last_error_line_from(&log_path, log_offset)+ .unwrap_or_else(|| format!("laya-serve exited ({})", exit.map(|s| s.to_string()).unwrap_or_default()));+ tracing::warn!(%reason, "Laya sidecar stopped; restarting in {:?}", backoff);+ router.set_status(LayaState::Failed, &reason, true);++ if started.elapsed() > Duration::from_secs(600) {+ backoff = Duration::from_secs(5);+ }+ if wait_or_cancel(&shutdown, backoff).await {+ return;+ }+ backoff = (backoff * 2).min(Duration::from_secs(300));+ }+}++/// Waits for the child to exit, flipping the status to online once `/health` answers.+async fn run_until_exit(+ router: &LayaRouter,+ child: &mut Child,+ shutdown: &CancellationToken,+) -> Option<std::process::ExitStatus> {+ let mut tick = tokio::time::interval(Duration::from_secs(2));+ let mut online = false;+ loop {+ tokio::select! {+ _ = shutdown.cancelled() => return None,+ status = child.wait() => return status.ok(),+ _ = tick.tick() => {+ let up = router.is_reachable().await;+ if up && !online {+ online = true;+ tick = tokio::time::interval(Duration::from_secs(15));+ tracing::info!(url = %router.base_url, "Laya sidecar online");+ router.set_status(LayaState::Online, "Model-based routing is active", true);+ } else if !up && online {+ router.set_status(LayaState::Starting, "Laya stopped answering; waiting for it", true);+ online = false;+ }+ }+ }+ }+}++async fn monitor_external(router: LayaRouter, shutdown: CancellationToken) {+ loop {+ if wait_or_cancel(&shutdown, Duration::from_secs(30)).await {+ return;+ }+ let up = router.is_reachable().await;+ let current = router.status();+ if up && !current.is_up() {+ router.set_status(LayaState::External, "Using the Laya service already running", false);+ } else if !up && current.is_up() {+ router.set_status(LayaState::Offline, "Laya stopped answering; using keyword routing", false);+ }+ }+}++/// Returns the `laya-serve` executable, installing it into `<data>/laya/venv` when missing.+async fn ensure_installed(router: &LayaRouter, dir: &Path) -> Result<PathBuf, String> {+ if let Ok(bin) = std::env::var("KWNT_LAYA_SERVE_BIN") {+ if !bin.is_empty() {+ return Ok(PathBuf::from(bin));+ }+ }+ let venv = dir.join("venv");+ let bin = venv_bin(&venv, "laya-serve");+ if bin.exists() {+ return Ok(bin);+ }++ router.set_status(+ LayaState::Installing,+ "Installing the Laya router (one-time, downloads PyTorch)",+ true,+ );+ let log = dir.join("install.log");+ let python = venv_bin(&venv, "python");++ let steps: Vec<Vec<String>> = if let Some(uv) = which("uv") {+ // uv fetches a suitable Python itself, so this works on machines without one.+ let uv = uv.to_string_lossy().to_string();+ vec![+ vec![uv.clone(), "venv".into(), "--python".into(), "3.12".into(), path_str(&venv)],+ vec![uv, "pip".into(), "install".into(), "--python".into(), path_str(&python), LAYA_PACKAGE.into()],+ ]+ } else if let Some(py) = which("python3").or_else(|| which("python")) {+ vec![+ vec![path_str(&py), "-m".into(), "venv".into(), path_str(&venv)],+ vec![path_str(&python), "-m".into(), "pip".into(), "install".into(), "--upgrade".into(), "pip".into()],+ vec![path_str(&python), "-m".into(), "pip".into(), "install".into(), LAYA_PACKAGE.into()],+ ]+ } else {+ return Err("neither `uv` nor Python 3.10+ was found; install uv from https://docs.astral.sh/uv/".into());+ };++ let offset = std::fs::metadata(&log).map(|m| m.len()).unwrap_or(0);+ for step in steps {+ let out = log_file(&log)?;+ let err = out.try_clone().map_err(|e| e.to_string())?;+ let status = Command::new(&step[0])+ .args(&step[1..])+ .stdout(Stdio::from(out))+ .stderr(Stdio::from(err))+ .status()+ .await+ .map_err(|e| format!("{}: {e}", step[0]))?;+ if !status.success() {+ let _ = std::fs::remove_dir_all(&venv);+ let reason = last_error_line_from(&log, offset).unwrap_or_else(|| format!("`{}` failed", step.join(" ")));+ return Err(reason);+ }+ }++ if bin.exists() {+ Ok(bin)+ } else {+ Err(format!("install finished but {} is missing", bin.display()))+ }+}++fn start(bin: &Path, dir: &Path, port: u16, models: &str) -> Result<Child, String> {+ let log = log_file(&dir.join("laya.log"))?;+ let err = log.try_clone().map_err(|e| e.to_string())?;+ let default_model = models.split(',').map(str::trim).find(|m| !m.is_empty()).unwrap_or("english");++ let mut cmd = Command::new(bin);+ cmd.env("LAYA_HOST", "127.0.0.1")+ .env("LAYA_PORT", port.to_string())+ .env("LAYA_MODELS", models)+ .env("LAYA_DEFAULT_MODEL", default_model)+ .env("LAYA_LOG_LEVEL", "warning")+ .stdin(Stdio::null())+ .stdout(Stdio::from(log))+ .stderr(Stdio::from(err))+ .kill_on_drop(true);+ if std::env::var_os("HF_HOME").is_none() {+ cmd.env("HF_HOME", dir.join("hf"));+ }+ cmd.spawn().map_err(|e| e.to_string())+}++/// Port of a loopback URL (`http://127.0.0.1:8000`), or `None` for remote hosts.+pub fn local_port(url: &str) -> Option<u16> {+ let rest = url.split("://").nth(1).unwrap_or(url);+ let authority = rest.split('/').next()?;+ let (host, port) = match authority.rfind(':').filter(|&i| !authority[i..].contains(']')) {+ Some(i) => (&authority[..i], authority[i + 1..].parse().ok()?),+ None => (authority, if url.starts_with("https") { 443 } else { 80 }),+ };+ matches!(host, "127.0.0.1" | "localhost" | "[::1]" | "0.0.0.0").then_some(port)+}++/// Last line of a log that looks like an error, to show users why Laya is down.+pub fn last_error_line(log: &Path) -> Option<String> {+ last_error_line_from(log, 0)+}++/// Like [`last_error_line`], but only looks at bytes written after `offset`.+pub fn last_error_line_from(log: &Path, offset: u64) -> Option<String> {+ let bytes = std::fs::read(log).ok()?;+ let text = String::from_utf8_lossy(bytes.get(offset as usize..)?);+ let tail: Vec<&str> = text.lines().rev().take(200).collect();+ let line = tail+ .iter()+ .find(|l| {+ let l = l.trim_start();+ l.starts_with("ERROR") || l.contains("Error:") || l.contains("error:")+ })+ .or_else(|| tail.iter().find(|l| !l.trim().is_empty()))?;+ let line = line.trim();+ Some(if line.len() > 300 { format!("{}…", &line[..line.floor_char_boundary(300)]) } else { line.to_string() })+}++async fn wait_or_cancel(shutdown: &CancellationToken, wait: Duration) -> bool {+ tokio::select! {+ _ = shutdown.cancelled() => true,+ _ = tokio::time::sleep(wait) => false,+ }+}++fn log_file(path: &Path) -> Result<std::fs::File, String> {+ std::fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(path)+ .map_err(|e| format!("{}: {e}", path.display()))+}++fn venv_bin(venv: &Path, name: &str) -> PathBuf {+ if cfg!(windows) {+ venv.join("Scripts").join(format!("{name}.exe"))+ } else {+ venv.join("bin").join(name)+ }+}++fn which(name: &str) -> Option<PathBuf> {+ let path = std::env::var_os("PATH")?;+ std::env::split_paths(&path)+ .map(|dir| dir.join(name))+ .find(|candidate| candidate.is_file())+}++fn path_str(p: &Path) -> String {+ p.to_string_lossy().to_string()+}diff --git a/src/router/team.rs b/src/router/team.rsindex 12b84713..7d59345f 100644--- a/src/router/team.rs+++ b/src/router/team.rs@@ -116,11 +116,13 @@ impl LayaRouter {match self.query_laya_for_kwant(prompt, channel_name, members).await {Ok(choice) => choice,Err(e) => {- tracing::warn!(error = %e, url = %self.base_url, "Laya channel routing unavailable, using keyword fallback");+ if self.status().is_up() {+ tracing::warn!(error = %e, url = %self.base_url, "Laya channel routing failed, using keyword fallback");+ }let (kwant, reason) = heuristic_pick_kwant(prompt, lead_kwant_id, members).map(|(k, r)| (k.id.clone(), r)).unwrap_or_else(|| (lead_kwant_id.to_string(), "Routed to channel lead".into()));- (kwant, reason)+ (kwant, format!("{reason}. {}", self.offline_note()))}}}diff --git a/src/server/mod.rs b/src/server/mod.rsindex 41191d9c..78ce7ada 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -74,6 +74,7 @@ pub fn create_router(state: AppState) -> Router {Router::new().route("/api/health", get(routes::health))+ .route("/api/laya/status", get(routes::laya_status)).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))diff --git a/src/server/routes.rs b/src/server/routes.rsindex c961b4f8..0a8ee958 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -21,6 +21,7 @@ pub struct HealthResponse {pub app: &'static str,pub version: &'static str,pub laya_url: String,+ pub laya: crate::router::sidecar::LayaStatus,}pub async fn health(State(state): State<AppState>) -> impl IntoResponse {@@ -29,9 +30,14 @@ pub async fn health(State(state): State<AppState>) -> impl IntoResponse {app: "kwnt",version: env!("CARGO_PKG_VERSION"),laya_url: state.config.laya_url.clone(),+ laya: state.router.status(),})}+pub async fn laya_status(State(state): State<AppState>) -> impl IntoResponse {+ Json(state.router.status())+}+pub async fn list_kwants(State(state): State<AppState>) -> Result<Json<Vec<Kwant>>, StatusCode> {state.dbdiff --git a/tests/router_test.rs b/tests/router_test.rsindex 74588b14..c0e0c341 100644--- a/tests/router_test.rs+++ b/tests/router_test.rs@@ -190,3 +190,42 @@ fn laya_base_url_is_normalized() {assert_eq!(normalize_base_url("http://127.0.0.1:8000/v1/systemone/"), "http://127.0.0.1:8000");assert_eq!(normalize_base_url("http://127.0.0.1:8000/v1"), "http://127.0.0.1:8000");}++#[test]+fn laya_sidecar_only_manages_loopback_urls() {+ use kwnt::router::sidecar::local_port;+ assert_eq!(local_port("http://127.0.0.1:8000"), Some(8000));+ assert_eq!(local_port("http://localhost:9001/"), Some(9001));+ assert_eq!(local_port("http://[::1]:8000"), Some(8000));+ assert_eq!(local_port("http://localhost"), Some(80));+ assert_eq!(local_port("http://laya:8000"), None);+ assert_eq!(local_port("https://laya.example.com"), None);+}++#[test]+fn laya_sidecar_surfaces_the_failure_reason() {+ use kwnt::router::sidecar::last_error_line;+ let dir = tempfile::tempdir().unwrap();+ let log = dir.path().join("laya.log");+ std::fs::write(+ &log,+ "Traceback (most recent call last):\n File \"x.py\"\nhuggingface_hub.errors.LocalEntryNotFoundError: cannot reach the Hub\n\n",+ )+ .unwrap();+ assert_eq!(+ last_error_line(&log).unwrap(),+ "huggingface_hub.errors.LocalEntryNotFoundError: cannot reach the Hub"+ );+ assert!(last_error_line(&dir.path().join("missing.log")).is_none());+}++#[tokio::test]+async fn laya_status_starts_unknown_and_updates() {+ use kwnt::router::sidecar::LayaState;+ let router = LayaRouter::new("http://127.0.0.1:1/v1/systemone".into());+ assert_eq!(router.base_url, "http://127.0.0.1:1");+ assert_eq!(router.status().state, LayaState::Unknown);+ router.set_status(LayaState::Starting, "loading", true);+ assert_eq!(router.status().state, LayaState::Starting);+ assert!(router.offline_note().contains("starting"));+}