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: redesign UI into sleek Grok Bot dark theme with professional roles

Oleksandr Ivanchenko61be068371e3
diff --git a/Cargo.toml b/Cargo.toml
index 7dc68e1f..8e691de8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -2,7 +2,7 @@
name = "kwnt"
version = "0.1.0"
edition = "2021"
-description = "Kwants: 8-Bit AI Agent Platform in Rust"
+description = "Kwants: Multi-Agent AI Platform in Rust"
[lib]
name = "kwnt"
diff --git a/README.md b/README.md
index 99c9fd7f..fe7f7211 100644
--- a/README.md
+++ b/README.md
@@ -1,18 +1,18 @@
-# 🕹️ KWNTS: 8-Bit AI Agent Platform in Rust
+# ⚡ KWNTS: Multi-Agent AI Platform in Rust
> Inspired by **Grok Bot** & **OpenMausBot**. Built with **Rust**, **Axum**, and **Laya**.
-Kwants is a high-performance, self-hosted AI agent platform packaged as a **single, standalone 10 MB binary** with an embedded retro 8-bit arcade Web UI and SQLite storage. Every agent is a **Kwant**—a specialized autonomous companion with its own personality, 8-bit sprite, stats (HP, MP/Mana context gauge, Level), model provider, and developer abilities.
+Kwants is a high-performance, self-hosted multi-agent AI platform packaged as a **single, standalone binary** with an embedded sleek dark-mode Web UI and SQLite storage. Every agent is a **Kwant**—a specialized autonomous companion with its own persona (`Architect`, `TechLead`, `DevOps`), model provider routing, and developer capabilities.
---
## ⚡ Key Highlights
-- **Single-Binary Zero-Dependency Deploy**: No Node.js or Docker required in production. One compiled native binary (`kwnt`) serves both the Tokio/Axum asynchronous engine and the embedded 8-bit React web application in under 25 MB of RAM on your laptop or a VPS.
-- **Sub-50ms Intelligent Routing with Laya**: By default, task-based model selection queries [convaiinnovations/laya](https://huggingface.co/convaiinnovations/laya) over its Jev-compatible `/v1/systemone` API in ~33ms, with seamless offline heuristic fallback.
+- **Single-Binary Zero-Dependency Deploy**: No Node.js or Docker required in production. One compiled native binary (`kwnt`) serves both the Tokio/Axum asynchronous engine and the embedded modern React web application in under 25 MB of RAM on your laptop or a VPS.
+- **Sub-50ms Intelligent Routing with Laya**: By default, task-based model selection queries [convaiinnovations/laya](https://huggingface.co/convaiinnovations/laya) over its `/v1/systemone` API in ~33ms, with seamless offline heuristic fallback and dynamic effort-level selection.
- **Hybrid Driver Fleet**: Run direct cloud & local APIs (xAI Grok, Anthropic Claude, OpenAI, OpenRouter, local Ollama) or supervise host CLI agents (`claude`, `codex`, `grok` CLIs).
-- **Human-in-the-Loop RPG Permission Broker**: Risky operations (shell execution, file writes) trigger retro RPG encounter cards: `[ALLOW ONCE]`, `[ALWAYS ALLOW]`, `[DENY]`.
-- **Authentic 8-Bit Arcade Aesthetics**: Pixel fonts (*Press Start 2P*, *Silkscreen*), toggleable CRT scanlines, animated pixel avatars, and procedural chiptune sound effects synthesized in pure code via the **Web Audio API** (zero audio files needed).
+- **Human-in-the-Loop Permission Broker**: Security-critical operations (shell execution, workspace file edits) require user approval via modern security cards: `[Allow Once]`, `[Always Allow]`, `[Deny]`.
+- **Sleek Modern Grok Bot Interface**: Dark zinc aesthetics (`zinc-950`), clean typography (`Inter`, `JetBrains Mono`), collapsible reasoning disclosures (`Thought for Xs • Laya [Grok] • Low Effort`), role-based SVG/gradient avatars, and subtle modern micro-interaction click & completion sounds synthesized via the Web Audio API.
---
diff --git a/frontend/index.html b/frontend/index.html
index 646ec71a..9b2f205d 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -4,12 +4,12 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><rect width='100' height='100' fill='%23181622'/><rect x='20' y='20' width='60' height='60' fill='%2300f5d4'/><rect x='30' y='35' width='15' height='15' fill='%23000'/><rect x='55' y='35' width='15' height='15' fill='%23000'/><rect x='30' y='60' width='40' height='10' fill='%23fca311'/></svg>" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>KWNTS // 8-Bit AI Agent Guild</title>
+ <title>Kwants // Multi-Agent AI Platform</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
- <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=Silkscreen:wght@400;700&family=VT323&display=swap" rel="stylesheet">
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
</head>
- <body class="bg-arcade-dark text-white select-none overflow-hidden">
+ <body class="bg-zinc-950 text-zinc-100 antialiased overflow-hidden font-sans">
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index ae157e3a..1ab4cfdb 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,12 +1,13 @@
import React, { useState, useEffect } from 'react';
-import { HudBar } from './components/HudBar';
-import { KwantSidebar, Kwant, Channel } from './components/KwantSidebar';
-import { DialogueWindow, ChatMessage } from './components/DialogueWindow';
-import { PendingApproval } from './components/ApprovalCard';
+import { AppHeader } from './components/AppHeader';
+import { Sidebar, Kwant, Channel } from './components/Sidebar';
+import { ChatView, ChatMessage } from './components/ChatView';
+import { PendingApproval } from './components/ModernApprovalCard';
+import { SettingsModal } from './components/SettingsModal';
+import { NewAgentModal } from './components/NewAgentModal';
import { playSfx } from './audio/chiptune';
export const App: React.FC = () => {
- const [crtEnabled, setCrtEnabled] = useState(true);
const [kwants, setKwants] = useState<Kwant[]>([]);
const [channels, setChannels] = useState<Channel[]>([]);
const [selectedId, setSelectedId] = useState<string>('');
@@ -18,13 +19,9 @@ export const App: React.FC = () => {
const [pendingApproval, setPendingApproval] = useState<PendingApproval | null>(null);
const [tokensUsed, setTokensUsed] = useState(0);
- // Summon Modal state
- const [isSummonOpen, setIsSummonOpen] = useState(false);
- const [newKwantName, setNewKwantName] = useState('');
- const [newKwantTitle, setNewKwantTitle] = useState('');
- const [newKwantSprite, setNewKwantSprite] = useState('cyber_mage');
- const [newKwantPrompt, setNewKwantPrompt] = useState('');
- const [newKwantModel, setNewKwantModel] = useState('auto');
+ // Modals state
+ const [isSettingsOpen, setIsSettingsOpen] = useState(false);
+ const [isNewAgentOpen, setIsNewAgentOpen] = useState(false);
// Load initial Kwants and Channels
useEffect(() => {
@@ -90,6 +87,7 @@ export const App: React.FC = () => {
tool_name: event.data.tool_name,
details: event.data.details,
});
+ playSfx('alert');
break;
case 'TurnComplete':
playSfx('coin');
@@ -168,21 +166,24 @@ export const App: React.FC = () => {
}
};
- const handleCreateKwant = async (e: React.FormEvent) => {
- e.preventDefault();
- if (!newKwantName.trim()) return;
-
+ const handleCreateAgent = async (agentData: {
+ name: string;
+ title: string;
+ persona_prompt: string;
+ avatar_sprite: string;
+ preferred_model: string;
+ }) => {
try {
const res = await fetch('/api/kwants', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
- name: newKwantName,
- title: newKwantTitle || 'Apprentice Kwant',
- persona_prompt: newKwantPrompt || 'You are an eager 8-bit AI agent ready to assist.',
- avatar_sprite: newKwantSprite,
+ name: agentData.name,
+ title: agentData.title,
+ persona_prompt: agentData.persona_prompt,
+ avatar_sprite: agentData.avatar_sprite,
driver_type: 'api',
- preferred_model: newKwantModel,
+ preferred_model: agentData.preferred_model,
}),
});
@@ -191,15 +192,11 @@ export const App: React.FC = () => {
setKwants((prev) => [...prev, created]);
setSelectedId(created.id);
setIsChannel(false);
- setIsSummonOpen(false);
+ setIsNewAgentOpen(false);
playSfx('fanfare');
- // Reset form
- setNewKwantName('');
- setNewKwantTitle('');
- setNewKwantPrompt('');
}
} catch (err) {
- console.error('Failed creating Kwant:', err);
+ console.error('Failed creating Agent:', err);
}
};
@@ -207,19 +204,17 @@ export const App: React.FC = () => {
const currentKwant = !isChannel ? kwants.find((k) => k.id === selectedId) : null;
return (
- <div className={`h-screen w-screen flex flex-col overflow-hidden ${crtEnabled ? 'crt-overlay' : ''}`}>
- {/* Top Arcade HUD */}
- <HudBar
- crtEnabled={crtEnabled}
- onToggleCrt={() => setCrtEnabled(!crtEnabled)}
+ <div className="h-screen w-screen flex flex-col bg-zinc-950 text-zinc-100 overflow-hidden font-sans">
+ {/* Modern App Header */}
+ <AppHeader
+ onOpenSettings={() => setIsSettingsOpen(true)}
tokensUsed={tokensUsed}
activeModel={currentKwant?.preferred_model || 'auto'}
- isLayaOnline={true}
/>
- {/* Main Game Shell */}
+ {/* Main Workspace Shell */}
<div className="flex-1 flex overflow-hidden">
- <KwantSidebar
+ <Sidebar
kwants={kwants}
channels={channels}
selectedId={selectedId}
@@ -235,17 +230,17 @@ export const App: React.FC = () => {
playSfx('click');
}}
onSummonKwant={() => {
- setIsSummonOpen(true);
- playSfx('coin');
+ setIsNewAgentOpen(true);
+ playSfx('click');
}}
/>
- <DialogueWindow
- title={isChannel ? `#${currentChannel?.name || 'guild'}` : currentKwant?.name || 'Kwant'}
+ <ChatView
+ title={isChannel ? `#${currentChannel?.name || 'general'}` : currentKwant?.name || 'Agent'}
subtitle={
isChannel
- ? currentChannel?.description || 'Guild party room'
- : `${currentKwant?.title || 'Agent'} [Model: ${currentKwant?.preferred_model || 'auto'}]`
+ ? currentChannel?.description || 'Team collaboration room'
+ : `${currentKwant?.title || 'Specialist'} [Laya Auto-Fleet]`
}
messages={messages}
streamingText={streamingText}
@@ -257,100 +252,18 @@ export const App: React.FC = () => {
/>
</div>
- {/* Summon Kwant Modal */}
- {isSummonOpen && (
- <div className="fixed inset-0 bg-black/80 flex items-center justify-center p-4 z-50">
- <div className="pixel-box-amber p-5 max-w-md w-full bg-arcade-panel">
- <div className="flex items-center justify-between border-b-2 border-arcade-amber pb-2 mb-4">
- <h3 className="font-pixel text-xs text-arcade-amber">⚔️ SUMMON NEW KWANT</h3>
- <button
- onClick={() => setIsSummonOpen(false)}
- className="text-zinc-400 hover:text-white font-pixel text-xs"
- >
- [X]
- </button>
- </div>
-
- <form onSubmit={handleCreateKwant} className="space-y-3 font-retro text-xs">
- <div>
- <label className="block text-zinc-400 font-pixel text-[9px] mb-1">NAME</label>
- <input
- type="text"
- required
- value={newKwantName}
- onChange={(e) => setNewKwantName(e.target.value)}
- placeholder="e.g. ChronoMage"
- className="w-full bg-black border border-zinc-700 px-2 py-1.5 text-arcade-cyan focus:outline-none focus:border-arcade-cyan"
- />
- </div>
-
- <div>
- <label className="block text-zinc-400 font-pixel text-[9px] mb-1">TITLE</label>
- <input
- type="text"
- value={newKwantTitle}
- onChange={(e) => setNewKwantTitle(e.target.value)}
- placeholder="e.g. Master of Time and Space"
- className="w-full bg-black border border-zinc-700 px-2 py-1.5 text-zinc-200 focus:outline-none focus:border-arcade-cyan"
- />
- </div>
-
- <div>
- <label className="block text-zinc-400 font-pixel text-[9px] mb-1">8-BIT SPRITE</label>
- <select
- value={newKwantSprite}
- onChange={(e) => setNewKwantSprite(e.target.value)}
- className="w-full bg-black border border-zinc-700 px-2 py-1.5 text-arcade-amber focus:outline-none"
- >
- <option value="cyber_mage">Cyber Mage (Sorcerer)</option>
- <option value="pixel_ninja">Pixel Ninja (Assassin)</option>
- <option value="terminal_knight">Terminal Knight (Paladin)</option>
- <option value="glitch_rogue">Glitch Rogue (Scout)</option>
- </select>
- </div>
-
- <div>
- <label className="block text-zinc-400 font-pixel text-[9px] mb-1">MODEL ROUTE</label>
- <select
- value={newKwantModel}
- onChange={(e) => setNewKwantModel(e.target.value)}
- className="w-full bg-black border border-zinc-700 px-2 py-1.5 text-arcade-amber focus:outline-none"
- >
- <option value="auto">Auto (Laya 33ms Decision Router)</option>
- <option value="grok">xAI Grok (Fast & Witty)</option>
- <option value="claude">Anthropic Claude (Architecture)</option>
- <option value="codex">OpenAI Codex / GPT (Coding)</option>
- <option value="local_ollama">Local Ollama (Private)</option>
- </select>
- </div>
-
- <div>
- <label className="block text-zinc-400 font-pixel text-[9px] mb-1">PERSONA / SYSTEM PROMPT</label>
- <textarea
- rows={3}
- value={newKwantPrompt}
- onChange={(e) => setNewKwantPrompt(e.target.value)}
- placeholder="You are an 8-bit AI agent specialized in..."
- className="w-full bg-black border border-zinc-700 px-2 py-1.5 text-zinc-200 focus:outline-none focus:border-arcade-cyan resize-none"
- />
- </div>
+ {/* New Agent Modal */}
+ <NewAgentModal
+ isOpen={isNewAgentOpen}
+ onClose={() => setIsNewAgentOpen(false)}
+ onCreateAgent={handleCreateAgent}
+ />
- <div className="flex justify-end gap-2 pt-2">
- <button
- type="button"
- onClick={() => setIsSummonOpen(false)}
- className="pixel-btn pixel-btn-dark text-[9px]"
- >
- CANCEL
- </button>
- <button type="submit" className="pixel-btn pixel-btn-amber text-[9px]">
- ✨ SUMMON
- </button>
- </div>
- </form>
- </div>
- </div>
- )}
+ {/* Settings Modal */}
+ <SettingsModal
+ isOpen={isSettingsOpen}
+ onClose={() => setIsSettingsOpen(false)}
+ />
</div>
);
};
diff --git a/frontend/src/audio/chiptune.ts b/frontend/src/audio/chiptune.ts
index bf4f6b2d..d8ec6b6d 100644
--- a/frontend/src/audio/chiptune.ts
+++ b/frontend/src/audio/chiptune.ts
@@ -45,82 +45,78 @@ export function playSfx(type: SfxType) {
case 'click': {
const osc = ctx.createOscillator();
const gain = ctx.createGain();
- osc.type = 'triangle';
- osc.frequency.setValueAtTime(400, now);
- osc.frequency.exponentialRampToValueAtTime(120, now + 0.03);
- gain.gain.setValueAtTime(0.12, now);
- gain.gain.exponentialRampToValueAtTime(0.001, now + 0.03);
+ osc.type = 'sine';
+ osc.frequency.setValueAtTime(600, now);
+ osc.frequency.exponentialRampToValueAtTime(200, now + 0.02);
+ gain.gain.setValueAtTime(0.04, now);
+ gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.02);
osc.connect(gain);
gain.connect(ctx.destination);
osc.start(now);
- osc.stop(now + 0.03);
+ osc.stop(now + 0.02);
break;
}
case 'blip': {
const osc = ctx.createOscillator();
const gain = ctx.createGain();
- osc.type = 'square';
- osc.frequency.setValueAtTime(880, now);
- gain.gain.setValueAtTime(0.06, now);
- gain.gain.exponentialRampToValueAtTime(0.001, now + 0.04);
+ osc.type = 'sine';
+ osc.frequency.setValueAtTime(480, now);
+ gain.gain.setValueAtTime(0.02, now);
+ gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.015);
osc.connect(gain);
gain.connect(ctx.destination);
osc.start(now);
- osc.stop(now + 0.04);
+ osc.stop(now + 0.015);
break;
}
case 'coin': {
+ const freqs = [523.25, 659.25];
+ freqs.forEach((freq, idx) => {
+ const osc = ctx.createOscillator();
+ const gain = ctx.createGain();
+ osc.type = 'sine';
+ osc.frequency.setValueAtTime(freq, now + idx * 0.06);
+ gain.gain.setValueAtTime(0.04, now + idx * 0.06);
+ gain.gain.exponentialRampToValueAtTime(0.0001, now + idx * 0.06 + 0.15);
+ osc.connect(gain);
+ gain.connect(ctx.destination);
+ osc.start(now + idx * 0.06);
+ osc.stop(now + idx * 0.06 + 0.15);
+ });
+ break;
+ }
+
+ case 'alert': {
const osc = ctx.createOscillator();
const gain = ctx.createGain();
- osc.type = 'square';
- osc.frequency.setValueAtTime(987.77, now); // B5
- osc.frequency.setValueAtTime(1318.51, now + 0.08); // E6
- gain.gain.setValueAtTime(0.15, now);
- gain.gain.setValueAtTime(0.15, now + 0.08);
- gain.gain.exponentialRampToValueAtTime(0.001, now + 0.28);
+ osc.type = 'sine';
+ osc.frequency.setValueAtTime(800, now);
+ osc.frequency.setValueAtTime(1000, now + 0.08);
+ gain.gain.setValueAtTime(0.05, now);
+ gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.2);
osc.connect(gain);
gain.connect(ctx.destination);
osc.start(now);
- osc.stop(now + 0.28);
- break;
- }
-
- case 'alert': {
- // 8-bit battle / approval needed siren
- for (let i = 0; i < 2; i++) {
- const osc = ctx.createOscillator();
- const gain = ctx.createGain();
- osc.type = 'sawtooth';
- const t = now + i * 0.12;
- osc.frequency.setValueAtTime(440, t);
- osc.frequency.setValueAtTime(880, t + 0.06);
- gain.gain.setValueAtTime(0.18, t);
- gain.gain.exponentialRampToValueAtTime(0.001, t + 0.11);
- osc.connect(gain);
- gain.connect(ctx.destination);
- osc.start(t);
- osc.stop(t + 0.11);
- }
+ osc.stop(now + 0.2);
break;
}
case 'fanfare': {
- // Victory fanfare arpeggio: G4, C5, E5, G5
- const notes = [392.00, 523.25, 659.25, 783.99];
+ const notes = [440, 554.37, 659.25, 880];
notes.forEach((freq, idx) => {
const osc = ctx.createOscillator();
const gain = ctx.createGain();
- osc.type = 'square';
- const t = now + idx * 0.09;
+ osc.type = 'sine';
+ const t = now + idx * 0.05;
osc.frequency.setValueAtTime(freq, t);
- gain.gain.setValueAtTime(0.16, t);
- gain.gain.exponentialRampToValueAtTime(0.001, t + (idx === 3 ? 0.35 : 0.08));
+ gain.gain.setValueAtTime(0.03, t);
+ gain.gain.exponentialRampToValueAtTime(0.0001, t + 0.12);
osc.connect(gain);
gain.connect(ctx.destination);
osc.start(t);
- osc.stop(t + (idx === 3 ? 0.35 : 0.08));
+ osc.stop(t + 0.12);
});
break;
}
diff --git a/frontend/src/components/AppHeader.tsx b/frontend/src/components/AppHeader.tsx
new file mode 100644
index 00000000..8ce9d36d
--- /dev/null
+++ b/frontend/src/components/AppHeader.tsx
@@ -0,0 +1,79 @@
+import React from 'react';
+import { Settings, Volume2, VolumeX, Cpu, Sparkles } from 'lucide-react';
+import { isSfxMuted, toggleSfxMute, playSfx } from '../audio/chiptune';
+
+interface AppHeaderProps {
+ onOpenSettings: () => void;
+ tokensUsed: number;
+ activeModel?: string;
+}
+
+export const AppHeader: React.FC<AppHeaderProps> = ({
+ onOpenSettings,
+ tokensUsed,
+ activeModel = 'auto',
+}) => {
+ const [sfxMuted, setSfxMuted] = React.useState(isSfxMuted());
+
+ const handleToggleSfx = () => {
+ const next = toggleSfxMute();
+ setSfxMuted(next);
+ };
+
+ return (
+ <header className="h-14 border-b border-zinc-800/80 bg-zinc-900/70 backdrop-blur-md px-4 flex items-center justify-between select-none z-30">
+ {/* Brand & Fleet status */}
+ <div className="flex items-center gap-3">
+ <div className="flex items-center gap-2 font-semibold text-sm tracking-tight text-zinc-100">
+ <div className="w-7 h-7 rounded-lg bg-gradient-to-br from-sky-500 to-indigo-600 flex items-center justify-center text-white shadow-sm">
+ <Sparkles size={16} />
+ </div>
+ <span>Kwants</span>
+ </div>
+ <span className="text-[11px] font-medium bg-zinc-800 text-zinc-300 px-2 py-0.5 rounded-full border border-zinc-700/60 hidden sm:inline-block">
+ AI Fleet
+ </span>
+ </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" />
+ <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>
+ </div>
+
+ {/* Right Controls */}
+ <div className="flex items-center gap-2">
+ {/* Token / Usage Counter */}
+ <div className="hidden lg:flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs text-zinc-400 bg-zinc-800/40 border border-zinc-800">
+ <span className="text-zinc-500 font-mono text-[11px]">Usage:</span>
+ <span className="font-mono text-zinc-200 font-medium">{tokensUsed} tk</span>
+ </div>
+
+ {/* Audio Toggle */}
+ <button
+ onClick={handleToggleSfx}
+ className="p-1.5 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800/80 transition-colors"
+ title={sfxMuted ? 'Unmute UI sounds' : 'Mute UI sounds'}
+ >
+ {sfxMuted ? <VolumeX size={17} /> : <Volume2 size={17} />}
+ </button>
+
+ {/* Settings Button */}
+ <button
+ onClick={() => {
+ playSfx('click');
+ onOpenSettings();
+ }}
+ className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium text-zinc-200 bg-zinc-800 hover:bg-zinc-700/80 border border-zinc-700/60 transition-all hover:border-zinc-600 shadow-sm"
+ >
+ <Settings size={14} className="text-zinc-400" />
+ <span>Settings</span>
+ </button>
+ </div>
+ </header>
+ );
+};
diff --git a/frontend/src/components/ApprovalCard.tsx b/frontend/src/components/ApprovalCard.tsx
deleted file mode 100644
index 7a6982a7..00000000
--- a/frontend/src/components/ApprovalCard.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-import React from 'react';
-import { playSfx } from '../audio/chiptune';
-
-export interface PendingApproval {
- id: string;
- tool_name: string;
- details: Record<string, unknown>;
-}
-
-interface ApprovalCardProps {
- approval: PendingApproval;
- onResolve: (id: string, decision: 'allow_once' | 'always_allow' | 'deny') => void;
-}
-
-export const ApprovalCard: React.FC<ApprovalCardProps> = ({ approval, onResolve }) => {
- React.useEffect(() => {
- playSfx('alert');
- }, [approval.id]);
-
- return (
- <div className="pixel-box-amber p-4 my-4 max-w-xl mx-auto animate-bounce-short">
- {/* Header */}
- <div className="flex items-center justify-between border-b-2 border-arcade-amber pb-2 mb-3">
- <div className="flex items-center gap-2">
- <span className="w-2.5 h-2.5 bg-arcade-magenta inline-block animate-ping" />
- <h4 className="font-pixel text-[10px] text-arcade-amber">
- ⚔️ BATTLE DECISION REQUIRED
- </h4>
- </div>
- <span className="font-pixel text-[8px] bg-black text-red-400 px-1.5 py-0.5 border border-red-900">
- GATE
- </span>
- </div>
-
- {/* Tool details */}
- <div className="font-retro text-xs text-zinc-300 space-y-2 mb-4 bg-black/60 p-3 border border-zinc-800">
- <div>
- <span className="text-zinc-500 font-pixel text-[9px]">TOOL: </span>
- <span className="text-arcade-cyan font-bold">{approval.tool_name}</span>
- </div>
-
- <div>
- <span className="text-zinc-500 font-pixel text-[9px]">PARAMETERS: </span>
- <pre className="font-terminal text-sm text-green-400 mt-1 whitespace-pre-wrap break-all max-h-32 overflow-y-auto">
- {JSON.stringify(approval.details, null, 2)}
- </pre>
- </div>
- </div>
-
- {/* Decision Buttons */}
- <div className="flex flex-wrap items-center gap-3 justify-end pt-1">
- <button
- onClick={() => {
- playSfx('click');
- onResolve(approval.id, 'deny');
- }}
- className="pixel-btn pixel-btn-magenta text-[9px]"
- >
- 🛑 FLEE (DENY)
- </button>
-
- <button
- onClick={() => {
- playSfx('coin');
- onResolve(approval.id, 'always_allow');
- }}
- className="pixel-btn pixel-btn-cyan text-[9px]"
- >
- 🛡️ ALWAYS ALLOW
- </button>
-
- <button
- onClick={() => {
- playSfx('coin');
- onResolve(approval.id, 'allow_once');
- }}
- className="pixel-btn pixel-btn-amber text-[9px]"
- >
- ⚔️ ALLOW ONCE
- </button>
- </div>
- </div>
- );
-};
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
new file mode 100644
index 00000000..1a9976ff
--- /dev/null
+++ b/frontend/src/components/ChatView.tsx
@@ -0,0 +1,283 @@
+import React, { useState, useRef, useEffect } from 'react';
+import { ArrowUp, Sparkles, ChevronDown, ChevronRight, Copy, Check, Cpu } from 'lucide-react';
+import { ModernAvatar } from './ModernAvatar';
+import { ModernApprovalCard, PendingApproval } from './ModernApprovalCard';
+import { playSfx } from '../audio/chiptune';
+
+export interface ChatMessage {
+ id: string;
+ sender_role: 'user' | 'kwant' | 'system';
+ sender_id: string;
+ text: string;
+ reasoning_content?: string | null;
+ tool_calls?: string | null;
+ tokens_used?: number;
+}
+
+interface ChatViewProps {
+ title: string;
+ subtitle: string;
+ messages: ChatMessage[];
+ streamingText: string;
+ streamingThinking: string;
+ pendingApproval: PendingApproval | null;
+ isStreaming: boolean;
+ onSendMessage: (text: string) => void;
+ onResolveApproval: (id: string, decision: 'allow_once' | 'always_allow' | 'deny') => void;
+}
+
+export const ChatView: React.FC<ChatViewProps> = ({
+ title,
+ subtitle,
+ messages,
+ streamingText,
+ streamingThinking,
+ pendingApproval,
+ isStreaming,
+ onSendMessage,
+ onResolveApproval,
+}) => {
+ const [inputVal, setInputVal] = useState('');
+ const [openThoughts, setOpenThoughts] = useState<Record<string, boolean>>({});
+ const [copiedId, setCopiedId] = useState<string | null>(null);
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+
+ // Auto-scroll on new tokens
+ useEffect(() => {
+ if (scrollRef.current) {
+ scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
+ }
+ }, [messages, streamingText, streamingThinking, pendingApproval]);
+
+ const toggleThought = (id: string) => {
+ setOpenThoughts((prev) => ({ ...prev, [id]: !prev[id] }));
+ };
+
+ const handleCopy = (text: string, id: string) => {
+ navigator.clipboard.writeText(text);
+ setCopiedId(id);
+ playSfx('click');
+ setTimeout(() => setCopiedId(null), 2000);
+ };
+
+ const handleSubmit = (e?: React.FormEvent) => {
+ if (e) e.preventDefault();
+ if (!inputVal.trim() || isStreaming) return;
+ playSfx('click');
+ onSendMessage(inputVal.trim());
+ setInputVal('');
+ if (textareaRef.current) {
+ textareaRef.current.style.height = 'auto';
+ }
+ };
+
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ handleSubmit();
+ }
+ };
+
+ const handlePromptSuggestion = (prompt: string) => {
+ setInputVal(prompt);
+ playSfx('click');
+ if (textareaRef.current) {
+ textareaRef.current.focus();
+ }
+ };
+
+ return (
+ <div className="flex-1 flex flex-col h-full bg-zinc-950 overflow-hidden">
+ {/* Channel / Agent Header */}
+ <div className="h-14 border-b border-zinc-800/80 px-6 flex items-center justify-between bg-zinc-900/30 backdrop-blur-sm select-none">
+ <div>
+ <h2 className="text-sm font-semibold text-zinc-100 flex items-center gap-2">
+ <span>{title}</span>
+ </h2>
+ <p className="text-[11px] text-zinc-400 truncate max-w-lg mt-0.5">{subtitle}</p>
+ </div>
+
+ <div className="flex items-center gap-2">
+ <div className="flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium text-sky-400 bg-sky-500/10 border border-sky-500/20 shadow-sm">
+ <Cpu size={13} />
+ <span>Laya Auto-Fleet</span>
+ </div>
+ </div>
+ </div>
+
+ {/* Messages Stream */}
+ <div ref={scrollRef} className="flex-1 overflow-y-auto p-6 space-y-6">
+ {messages.map((msg) => {
+ const isUser = msg.sender_role === 'user';
+ const isThoughtOpen = !!openThoughts[msg.id];
+ const displayName = isUser ? 'You' : (msg.sender_id && msg.sender_id.length > 20 ? title : msg.sender_id);
+
+ return (
+ <div
+ key={msg.id}
+ className={`flex items-start gap-3.5 max-w-4xl ${isUser ? 'ml-auto flex-row-reverse' : ''}`}
+ >
+ <ModernAvatar
+ role={isUser ? 'user' : title}
+ name={displayName}
+ size={34}
+ />
+
+ <div className={`flex flex-col min-w-0 max-w-2xl ${isUser ? 'items-end' : 'items-start'}`}>
+ {/* Header info */}
+ <div className="flex items-center gap-2 mb-1 text-[11px] text-zinc-400 font-medium">
+ <span className="text-zinc-200">{displayName}</span>
+ {msg.tokens_used ? (
+ <span className="text-zinc-500 font-mono text-[10px]">({msg.tokens_used} tokens)</span>
+ ) : null}
+ </div>
+
+ {/* Collapsible Reasoning Disclosure */}
+ {msg.reasoning_content && (
+ <div className="mb-2 w-full">
+ <button
+ onClick={() => toggleThought(msg.id)}
+ className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-mono text-zinc-400 hover:text-zinc-200 bg-zinc-900 border border-zinc-800 transition-colors"
+ >
+ <Sparkles size={12} className="text-violet-400" />
+ <span>{msg.reasoning_content.slice(0, 48)}...</span>
+ {isThoughtOpen ? <ChevronDown size={13} /> : <ChevronRight size={13} />}
+ </button>
+
+ {isThoughtOpen && (
+ <div className="mt-1.5 p-3 rounded-xl bg-zinc-900/90 border border-zinc-800 text-xs font-mono text-zinc-300 whitespace-pre-wrap leading-relaxed shadow-sm">
+ {msg.reasoning_content}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Message Body Bubble */}
+ <div
+ className={`p-4 rounded-2xl text-sm leading-relaxed whitespace-pre-wrap break-words ${
+ isUser
+ ? 'bg-zinc-800 text-zinc-100 rounded-tr-sm border border-zinc-700/60 shadow-sm'
+ : 'bg-zinc-900/90 text-zinc-200 rounded-tl-sm border border-zinc-800/90 shadow-sm'
+ }`}
+ >
+ {msg.text}
+ </div>
+
+ {/* Copy action */}
+ {!isUser && (
+ <div className="mt-1 flex items-center gap-2 text-zinc-500 text-xs">
+ <button
+ onClick={() => handleCopy(msg.text, msg.id)}
+ className="p-1 hover:text-zinc-300 transition-colors flex items-center gap-1"
+ title="Copy response"
+ >
+ {copiedId === msg.id ? (
+ <>
+ <Check size={12} className="text-emerald-400" />
+ <span className="text-[10px] text-emerald-400">Copied</span>
+ </>
+ ) : (
+ <Copy size={12} />
+ )}
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ })}
+
+ {/* Live Streaming Assistant Message */}
+ {isStreaming && (
+ <div className="flex items-start gap-3.5 max-w-4xl">
+ <ModernAvatar role={title} name={title} size={34} />
+ <div className="flex flex-col items-start min-w-0 max-w-2xl">
+ <div className="flex items-center gap-2 mb-1 text-[11px] text-zinc-400 font-medium">
+ <span className="text-zinc-200">{title}</span>
+ <span className="inline-flex items-center gap-1 text-sky-400 text-[10px]">
+ <span className="w-1.5 h-1.5 rounded-full bg-sky-400 animate-ping" />
+ Generating...
+ </span>
+ </div>
+
+ {streamingThinking && (
+ <div className="mb-2 p-2.5 rounded-xl bg-violet-950/20 border border-violet-500/20 text-xs font-mono text-violet-300/90 flex items-center gap-2 animate-pulse">
+ <Sparkles size={13} className="text-violet-400" />
+ <span>{streamingThinking}</span>
+ </div>
+ )}
+
+ <div className="p-4 rounded-2xl rounded-tl-sm bg-zinc-900 text-zinc-200 border border-zinc-800 text-sm leading-relaxed whitespace-pre-wrap break-words shadow-sm">
+ {streamingText}
+ <span className="inline-block w-1.5 h-4 bg-sky-400 ml-1 cursor-blink align-middle" />
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Pending Security Approval Ticket */}
+ {pendingApproval && (
+ <ModernApprovalCard
+ approval={pendingApproval}
+ onResolve={onResolveApproval}
+ />
+ )}
+ </div>
+
+ {/* Suggestion Prompts Pill Bar */}
+ {messages.length <= 1 && (
+ <div className="px-6 py-2 flex flex-wrap items-center gap-2 select-none">
+ <span className="text-[11px] font-medium text-zinc-500">Suggested:</span>
+ {[
+ "Analyze system architecture tradeoffs",
+ "Write a fast Python script for data processing",
+ "Review git status and security policies",
+ ].map((prompt, idx) => (
+ <button
+ key={idx}
+ onClick={() => handlePromptSuggestion(prompt)}
+ className="px-2.5 py-1 rounded-full text-xs text-zinc-400 bg-zinc-900 border border-zinc-800 hover:border-zinc-700 hover:text-zinc-200 transition-all shadow-sm"
+ >
+ {prompt}
+ </button>
+ ))}
+ </div>
+ )}
+
+ {/* Modern Composer Input Bar */}
+ <div className="p-4 border-t border-zinc-800/80 bg-zinc-900/30">
+ <form
+ onSubmit={handleSubmit}
+ className="max-w-4xl mx-auto flex items-end gap-2 bg-zinc-900 border border-zinc-800 focus-within:border-zinc-700 rounded-2xl p-2 shadow-sm transition-all"
+ >
+ <textarea
+ ref={textareaRef}
+ rows={1}
+ value={inputVal}
+ onChange={(e) => {
+ setInputVal(e.target.value);
+ e.target.style.height = 'auto';
+ e.target.style.height = `${Math.min(e.target.scrollHeight, 160)}px`;
+ }}
+ onKeyDown={handleKeyDown}
+ placeholder={`Message ${title}... (Enter to send, Shift+Enter for newline)`}
+ className="flex-1 bg-transparent px-3 py-1.5 text-sm text-zinc-100 placeholder-zinc-500 focus:outline-none resize-none max-h-40 leading-relaxed font-sans"
+ />
+
+ <button
+ type="submit"
+ disabled={!inputVal.trim() || isStreaming}
+ className={`w-8 h-8 rounded-xl flex items-center justify-center transition-all flex-shrink-0 ${
+ inputVal.trim() && !isStreaming
+ ? 'bg-sky-500 text-white hover:bg-sky-400 shadow-sm'
+ : 'bg-zinc-800 text-zinc-500 cursor-not-allowed'
+ }`}
+ >
+ <ArrowUp size={16} strokeWidth={2.4} />
+ </button>
+ </form>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/DialogueWindow.tsx b/frontend/src/components/DialogueWindow.tsx
deleted file mode 100644
index 4fe69714..00000000
--- a/frontend/src/components/DialogueWindow.tsx
+++ /dev/null
@@ -1,202 +0,0 @@
-import React from 'react';
-import { SpriteAvatar } from './SpriteAvatar';
-import { ApprovalCard, PendingApproval } from './ApprovalCard';
-import { playSfx } from '../audio/chiptune';
-
-export interface ChatMessage {
- id: string;
- sender_role: 'user' | 'kwant' | 'system';
- sender_id: string;
- text: string;
- reasoning_content?: string | null;
- tool_calls?: string | null;
- tokens_used?: number;
-}
-
-interface DialogueWindowProps {
- title: string;
- subtitle: string;
- messages: ChatMessage[];
- streamingText: string;
- streamingThinking: string;
- pendingApproval: PendingApproval | null;
- isStreaming: boolean;
- onSendMessage: (text: string) => void;
- onResolveApproval: (id: string, decision: 'allow_once' | 'always_allow' | 'deny') => void;
-}
-
-export const DialogueWindow: React.FC<DialogueWindowProps> = ({
- title,
- subtitle,
- messages,
- streamingText,
- streamingThinking,
- pendingApproval,
- isStreaming,
- onSendMessage,
- onResolveApproval,
-}) => {
- const [inputVal, setInputVal] = React.useState('');
- const scrollRef = React.useRef<HTMLDivElement>(null);
-
- // Auto-scroll on new tokens or messages
- React.useEffect(() => {
- if (scrollRef.current) {
- scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
- }
- }, [messages, streamingText, streamingThinking, pendingApproval]);
-
- const handleSubmit = (e: React.FormEvent) => {
- e.preventDefault();
- if (!inputVal.trim() || isStreaming) return;
- playSfx('click');
- onSendMessage(inputVal);
- setInputVal('');
- };
-
- const handleRollPrompt = () => {
- const funPrompts = [
- "Write a fast Rust macro to deserialize retro 8-bit packets",
- "Check the server status and report memory usage",
- "Refactor our SQLite schema with foreign key cascades",
- "Write a bash script to backup ~/.kwnt/ to a tarball",
- "What is the mana cost of training an agent with RLCD?"
- ];
- const picked = funPrompts[Math.floor(Math.random() * funPrompts.length)];
- setInputVal(picked);
- playSfx('coin');
- };
-
- return (
- <div className="flex-1 flex flex-col h-full bg-[#100e17] overflow-hidden">
- {/* Dialogue Header */}
- <div className="pixel-box bg-arcade-panel px-4 py-2 border-b-2 border-black flex items-center justify-between">
- <div>
- <h2 className="font-pixel text-xs text-arcade-cyan tracking-wide flex items-center gap-2">
- <span>⚔️</span>
- <span>{title}</span>
- </h2>
- <p className="font-retro text-[10px] text-zinc-400 mt-0.5">{subtitle}</p>
- </div>
- </div>
-
- {/* Messages Stream Area */}
- <div ref={scrollRef} className="flex-1 overflow-y-auto p-4 space-y-4">
- {messages.map((msg) => {
- const isUser = msg.sender_role === 'user';
- return (
- <div
- key={msg.id}
- className={`flex items-start gap-3 max-w-3xl ${
- isUser ? 'ml-auto flex-row-reverse' : ''
- }`}
- >
- <SpriteAvatar
- sprite={isUser ? 'user' : 'cyber_mage'}
- size={34}
- />
- <div
- className={`p-3 pixel-box ${
- isUser
- ? 'border-arcade-cyan bg-[#131b24]'
- : 'border-arcade-border bg-arcade-panel'
- }`}
- >
- <div className="flex items-center justify-between gap-4 mb-1 border-b border-zinc-800 pb-1">
- <span className="font-pixel text-[8px] text-zinc-400 uppercase">
- {isUser ? 'PLAYER HERO' : msg.sender_id}
- </span>
- {msg.tokens_used ? (
- <span className="font-pixel text-[7px] text-arcade-amber">
- [{msg.tokens_used} MP]
- </span>
- ) : null}
- </div>
-
- {/* Reasoning / Thinking accordion if present */}
- {msg.reasoning_content && (
- <div className="mb-2 p-2 bg-black/60 border-l-2 border-arcade-magenta font-retro text-[11px] text-zinc-400">
- <span className="text-arcade-magenta font-bold">🧠 THOUGHT PROCESS: </span>
- {msg.reasoning_content}
- </div>
- )}
-
- {/* Message Body */}
- <div className="font-retro text-xs sm:text-sm text-zinc-200 leading-relaxed whitespace-pre-wrap break-words">
- {msg.text}
- </div>
- </div>
- </div>
- );
- })}
-
- {/* Live Streaming Message */}
- {isStreaming && (
- <div className="flex items-start gap-3 max-w-3xl">
- <SpriteAvatar sprite="cyber_mage" size={34} />
- <div className="p-3 pixel-box border-arcade-amber bg-arcade-panel">
- <div className="flex items-center gap-2 mb-1 border-b border-zinc-800 pb-1">
- <span className="w-2 h-2 bg-arcade-amber inline-block animate-ping" />
- <span className="font-pixel text-[8px] text-arcade-amber">
- KWANT CASTING...
- </span>
- </div>
-
- {streamingThinking && (
- <div className="mb-2 p-2 bg-black/60 border-l-2 border-arcade-magenta font-retro text-[11px] text-arcade-magenta/90 animate-pulse">
- 🔮 {streamingThinking}
- </div>
- )}
-
- <div className="font-retro text-xs sm:text-sm text-zinc-200 leading-relaxed whitespace-pre-wrap break-words">
- {streamingText}
- <span className="inline-block w-2 h-4 bg-arcade-cyan ml-1 cursor-blink align-middle" />
- </div>
- </div>
- </div>
- )}
-
- {/* Pending Approval Ticket */}
- {pendingApproval && (
- <ApprovalCard
- approval={pendingApproval}
- onResolve={onResolveApproval}
- />
- )}
- </div>
-
- {/* Input Bar */}
- <form onSubmit={handleSubmit} className="p-3 border-t-4 border-black bg-arcade-panel flex items-center gap-2">
- <button
- type="button"
- onClick={handleRollPrompt}
- className="pixel-btn pixel-btn-dark text-[9px] hidden sm:flex"
- title="Roll random prompt"
- >
- 🎲 ROLL
- </button>
-
- <div className="flex-1 relative">
- <input
- type="text"
- value={inputVal}
- onChange={(e) => setInputVal(e.target.value)}
- placeholder="Type your quest command..."
- className="w-full bg-black border-2 border-zinc-700 px-3 py-2 text-xs sm:text-sm font-retro text-arcade-cyan placeholder-zinc-600 focus:outline-none focus:border-arcade-cyan"
- disabled={isStreaming}
- />
- </div>
-
- <button
- type="submit"
- disabled={!inputVal.trim() || isStreaming}
- className={`pixel-btn ${
- !inputVal.trim() || isStreaming ? 'pixel-btn-dark opacity-50 cursor-not-allowed' : 'pixel-btn-amber'
- }`}
- >
- ⚔️ SEND
- </button>
- </form>
- </div>
- );
-};
diff --git a/frontend/src/components/HudBar.tsx b/frontend/src/components/HudBar.tsx
deleted file mode 100644
index e9e9aadd..00000000
--- a/frontend/src/components/HudBar.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-import React from 'react';
-import { isSfxMuted, toggleSfxMute } from '../audio/chiptune';
-
-interface HudBarProps {
- crtEnabled: boolean;
- onToggleCrt: () => void;
- tokensUsed: number;
- totalTokensLimit?: number;
- activeModel?: string;
- isLayaOnline?: boolean;
-}
-
-export const HudBar: React.FC<HudBarProps> = ({
- crtEnabled,
- onToggleCrt,
- tokensUsed,
- totalTokensLimit = 4096,
- activeModel = 'grok',
- isLayaOnline = true,
-}) => {
- const [sfxMuted, setSfxMuted] = React.useState(isSfxMuted());
-
- const handleToggleSfx = () => {
- const nextState = toggleSfxMute();
- setSfxMuted(nextState);
- };
-
- const manaPercentage = Math.min(100, Math.round((tokensUsed / totalTokensLimit) * 100));
-
- return (
- <header className="pixel-box bg-arcade-panel px-4 py-3 border-b-4 border-black flex flex-wrap items-center justify-between gap-4 z-40">
- {/* Brand & Level */}
- <div className="flex items-center gap-3">
- <div className="bg-arcade-amber text-black font-pixel text-xs px-2 py-1 border-2 border-black shadow-pixel-sm">
- KWNTS
- </div>
- <div className="font-pixel text-[10px] text-arcade-cyan tracking-wider hidden sm:block">
- LVL. 99 PARTY
- </div>
- </div>
-
- {/* RPG Gauges */}
- <div className="flex items-center gap-6 font-pixel text-[9px]">
- {/* HP Gauge */}
- <div className="flex items-center gap-2">
- <span className="text-red-400">HP:</span>
- <div className="w-24 h-3 bg-black border border-zinc-700 relative overflow-hidden">
- <div className="h-full bg-arcade-green w-full animate-pulse" />
- </div>
- <span className="text-zinc-400 hidden md:inline">100%</span>
- </div>
-
- {/* MP (Mana / Token) Gauge */}
- <div className="flex items-center gap-2">
- <span className="text-arcade-cyan">MP:</span>
- <div className="w-24 h-3 bg-black border border-zinc-700 relative overflow-hidden">
- <div
- className="h-full bg-arcade-cyan transition-all duration-300"
- style={{ width: `${Math.max(8, manaPercentage)}%` }}
- />
- </div>
- <span className="text-zinc-400 hidden md:inline">{tokensUsed} TKN</span>
- </div>
-
- {/* Active Router indicator */}
- <div className="hidden lg:flex items-center gap-1 bg-black/60 px-2 py-1 border border-zinc-700">
- <span className="w-2 h-2 rounded-none bg-arcade-amber inline-block animate-ping mr-1" />
- <span className="text-zinc-400">ROUTER:</span>
- <span className="text-arcade-amber uppercase">{isLayaOnline ? 'LAYA (33ms)' : activeModel}</span>
- </div>
- </div>
-
- {/* Control Switches */}
- <div className="flex items-center gap-2">
- <button
- onClick={handleToggleSfx}
- className={`pixel-btn ${sfxMuted ? 'pixel-btn-dark' : 'pixel-btn-amber'} text-[9px]`}
- title="Toggle 8-bit sound effects"
- >
- {sfxMuted ? '🔇 MUTE' : '🔊 SFX'}
- </button>
-
- <button
- onClick={onToggleCrt}
- className={`pixel-btn ${crtEnabled ? 'pixel-btn-cyan' : 'pixel-btn-dark'} text-[9px]`}
- title="Toggle retro CRT scanlines"
- >
- {crtEnabled ? '📺 CRT: ON' : '📺 CRT: OFF'}
- </button>
- </div>
- </header>
- );
-};
diff --git a/frontend/src/components/KwantSidebar.tsx b/frontend/src/components/KwantSidebar.tsx
deleted file mode 100644
index bde48d93..00000000
--- a/frontend/src/components/KwantSidebar.tsx
+++ /dev/null
@@ -1,118 +0,0 @@
-import React from 'react';
-import { SpriteAvatar } from './SpriteAvatar';
-
-export interface Kwant {
- id: string;
- name: string;
- title: string;
- persona_prompt: string;
- avatar_sprite: string;
- preferred_model: string;
- driver_type: string;
-}
-
-export interface Channel {
- id: string;
- name: string;
- description: string | null;
- lead_kwant_id: string;
-}
-
-interface KwantSidebarProps {
- kwants: Kwant[];
- channels: Channel[];
- selectedId: string;
- isChannel: boolean;
- onSelectKwant: (kwant: Kwant) => void;
- onSelectChannel: (channel: Channel) => void;
- onSummonKwant: () => void;
-}
-
-export const KwantSidebar: React.FC<KwantSidebarProps> = ({
- kwants,
- channels,
- selectedId,
- isChannel,
- onSelectKwant,
- onSelectChannel,
- onSummonKwant,
-}) => {
- return (
- <aside className="w-64 bg-arcade-dark border-r-4 border-black flex flex-col h-full select-none">
- {/* Channels / Guild Section */}
- <div className="p-3 border-b-2 border-arcade-border">
- <div className="flex items-center justify-between text-arcade-amber font-pixel text-[9px] mb-2 px-1">
- <span># GUILD ROOMS</span>
- </div>
- <div className="space-y-1">
- {channels.map((chan) => {
- const active = isChannel && selectedId === chan.id;
- return (
- <button
- key={chan.id}
- onClick={() => onSelectChannel(chan)}
- className={`w-full text-left px-2 py-1.5 font-retro text-xs border border-transparent flex items-center gap-2 transition-all ${
- active
- ? 'bg-arcade-panel border-arcade-cyan text-arcade-cyan font-bold shadow-pixel-sm'
- : 'text-zinc-400 hover:text-white hover:bg-zinc-900'
- }`}
- >
- <span className="text-arcade-amber">#</span>
- <span className="truncate">{chan.name}</span>
- </button>
- );
- })}
- </div>
- </div>
-
- {/* Kwants Party Roster */}
- <div className="flex-1 overflow-y-auto p-3">
- <div className="flex items-center justify-between text-arcade-cyan font-pixel text-[9px] mb-3 px-1">
- <span>⚔️ PARTY ROSTER</span>
- <span className="text-zinc-500">[{kwants.length}]</span>
- </div>
-
- <div className="space-y-2">
- {kwants.map((k) => {
- const active = !isChannel && selectedId === k.id;
- return (
- <div
- key={k.id}
- onClick={() => onSelectKwant(k)}
- className={`p-2 border-2 cursor-pointer transition-all flex items-center gap-3 ${
- active
- ? 'bg-arcade-panel border-arcade-amber shadow-pixel-amber'
- : 'bg-zinc-900/60 border-zinc-800 hover:border-zinc-700'
- }`}
- >
- <SpriteAvatar sprite={k.avatar_sprite} size={36} />
- <div className="flex-1 min-w-0">
- <div className="flex items-center justify-between">
- <h3 className="font-pixel text-[10px] text-white truncate">{k.name}</h3>
- <span className="font-pixel text-[8px] text-arcade-green">[READY]</span>
- </div>
- <p className="font-retro text-[10px] text-zinc-400 truncate mt-0.5">{k.title}</p>
- <div className="flex items-center gap-1 mt-1">
- <span className="font-pixel text-[7px] bg-black text-arcade-amber px-1 border border-zinc-700">
- {k.preferred_model.toUpperCase()}
- </span>
- </div>
- </div>
- </div>
- );
- })}
- </div>
- </div>
-
- {/* Footer / Summon Button */}
- <div className="p-3 border-t-2 border-arcade-border bg-arcade-panel">
- <button
- onClick={onSummonKwant}
- className="w-full pixel-btn pixel-btn-cyan text-[9px]"
- >
- + SUMMON KWANT
- </button>
- </div>
- </aside>
- );
-};
diff --git a/frontend/src/components/ModernApprovalCard.tsx b/frontend/src/components/ModernApprovalCard.tsx
new file mode 100644
index 00000000..e8f603f3
--- /dev/null
+++ b/frontend/src/components/ModernApprovalCard.tsx
@@ -0,0 +1,68 @@
+import React from 'react';
+import { ShieldAlert, Check, CheckCheck, X } from 'lucide-react';
+import { playSfx } from '../audio/chiptune';
+
+export interface PendingApproval {
+ id: string;
+ tool_name: string;
+ details: Record<string, unknown>;
+}
+
+interface ModernApprovalCardProps {
+ approval: PendingApproval;
+ onResolve: (id: string, decision: 'allow_once' | 'always_allow' | 'deny') => void;
+}
+
+export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
+ approval,
+ onResolve,
+}) => {
+ const handleDecision = (decision: 'allow_once' | 'always_allow' | 'deny') => {
+ playSfx('click');
+ onResolve(approval.id, decision);
+ };
+
+ return (
+ <div className="my-3 border border-amber-500/30 bg-amber-950/20 rounded-xl p-4 text-zinc-100 max-w-2xl shadow-lg backdrop-blur-sm">
+ <div className="flex items-center gap-2 mb-2 text-amber-400 font-semibold text-xs tracking-wide">
+ <ShieldAlert size={16} />
+ <span>Action Approval Required</span>
+ </div>
+
+ <div className="bg-zinc-900/90 rounded-lg p-3 border border-zinc-800 text-xs font-mono space-y-1 mb-3">
+ <div className="text-zinc-400">
+ <span className="text-sky-400 font-semibold">Tool:</span> {approval.tool_name}
+ </div>
+ <div className="text-zinc-300 break-all overflow-x-auto max-h-36 py-1">
+ {JSON.stringify(approval.details, null, 2)}
+ </div>
+ </div>
+
+ <div className="flex items-center justify-end gap-2">
+ <button
+ onClick={() => handleDecision('deny')}
+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-zinc-300 bg-zinc-800 hover:bg-zinc-700 transition-colors"
+ >
+ <X size={14} />
+ <span>Deny</span>
+ </button>
+
+ <button
+ onClick={() => handleDecision('allow_once')}
+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-emerald-600 hover:bg-emerald-500 transition-colors shadow-sm"
+ >
+ <Check size={14} />
+ <span>Allow Once</span>
+ </button>
+
+ <button
+ onClick={() => handleDecision('always_allow')}
+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm"
+ >
+ <CheckCheck size={14} />
+ <span>Always Allow</span>
+ </button>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/ModernAvatar.tsx b/frontend/src/components/ModernAvatar.tsx
new file mode 100644
index 00000000..560fac2b
--- /dev/null
+++ b/frontend/src/components/ModernAvatar.tsx
@@ -0,0 +1,60 @@
+import React from 'react';
+import { Layers, Code2, Terminal, Shield, Zap, User, Bot } from 'lucide-react';
+
+interface ModernAvatarProps {
+ role?: string;
+ name?: string;
+ size?: number; // pixel diameter
+ isOnline?: boolean;
+}
+
+export const ModernAvatar: React.FC<ModernAvatarProps> = ({
+ role = 'default',
+ name = '',
+ size = 36,
+ isOnline,
+}) => {
+ const norm = (role + ' ' + name).toLowerCase();
+
+ let gradient = 'from-zinc-700 to-zinc-900 text-zinc-300';
+ let Icon = Bot;
+
+ if (norm.includes('user') || norm.includes('player')) {
+ gradient = 'from-blue-600 to-indigo-700 text-white';
+ Icon = User;
+ } else if (norm.includes('architect') || norm.includes('cyber_mage') || norm.includes('mage')) {
+ gradient = 'from-violet-600 to-purple-800 text-violet-100';
+ Icon = Layers;
+ } else if (norm.includes('tech') || norm.includes('ninja') || norm.includes('pixel') || norm.includes('lead')) {
+ gradient = 'from-sky-500 to-blue-700 text-sky-100';
+ Icon = Code2;
+ } else if (norm.includes('devops') || norm.includes('terminal') || norm.includes('knight') || norm.includes('shell')) {
+ gradient = 'from-emerald-500 to-teal-700 text-emerald-100';
+ Icon = Terminal;
+ } else if (norm.includes('security') || norm.includes('shield')) {
+ gradient = 'from-amber-500 to-orange-700 text-amber-100';
+ Icon = Shield;
+ } else if (norm.includes('fast') || norm.includes('grok')) {
+ gradient = 'from-rose-500 to-pink-700 text-rose-100';
+ Icon = Zap;
+ }
+
+ const iconSize = Math.max(14, Math.round(size * 0.48));
+
+ return (
+ <div className="relative inline-flex flex-shrink-0" style={{ width: size, height: size }}>
+ <div
+ className={`w-full h-full rounded-xl bg-gradient-to-br ${gradient} flex items-center justify-center shadow-sm border border-white/10`}
+ >
+ <Icon size={iconSize} strokeWidth={2.2} />
+ </div>
+ {isOnline !== undefined && (
+ <span
+ className={`absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full ring-2 ring-zinc-950 ${
+ isOnline ? 'bg-emerald-400' : 'bg-zinc-600'
+ }`}
+ />
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsx
new file mode 100644
index 00000000..fcc346e5
--- /dev/null
+++ b/frontend/src/components/NewAgentModal.tsx
@@ -0,0 +1,174 @@
+import React, { useState } from 'react';
+import { X, Sparkles, Layers, Code2, Terminal, Shield } from 'lucide-react';
+import { playSfx } from '../audio/chiptune';
+
+interface NewAgentModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ onCreateAgent: (data: {
+ name: string;
+ title: string;
+ persona_prompt: string;
+ avatar_sprite: string;
+ preferred_model: string;
+ }) => void;
+}
+
+export const NewAgentModal: React.FC<NewAgentModalProps> = ({
+ isOpen,
+ onClose,
+ onCreateAgent,
+}) => {
+ const [name, setName] = useState('');
+ const [title, setTitle] = useState('');
+ const [roleStyle, setRoleStyle] = useState('architect');
+ const [model, setModel] = useState('auto');
+ const [prompt, setPrompt] = useState('');
+ const [submitting, setSubmitting] = useState(false);
+
+ if (!isOpen) return null;
+
+ const handleSubmit = (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!name.trim()) return;
+
+ setSubmitting(true);
+ playSfx('click');
+
+ onCreateAgent({
+ name: name.trim(),
+ title: title.trim() || 'AI Specialist',
+ persona_prompt: prompt.trim() || 'You are an intelligent AI specialist ready to collaborate.',
+ avatar_sprite: roleStyle,
+ preferred_model: model,
+ });
+
+ setSubmitting(false);
+ onClose();
+ };
+
+ return (
+ <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4 select-none">
+ <div className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-md w-full p-6 text-zinc-100 shadow-2xl space-y-5">
+ <div className="flex items-center justify-between border-b border-zinc-800 pb-3">
+ <div className="flex items-center gap-2">
+ <div className="w-7 h-7 rounded-lg bg-sky-500/10 border border-sky-500/20 flex items-center justify-center text-sky-400">
+ <Sparkles size={15} />
+ </div>
+ <h3 className="text-sm font-semibold text-zinc-100">Create New AI Agent</h3>
+ </div>
+ <button
+ onClick={() => {
+ playSfx('click');
+ onClose();
+ }}
+ className="p-1 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors"
+ >
+ <X size={17} />
+ </button>
+ </div>
+
+ <form onSubmit={handleSubmit} className="space-y-4">
+ <div>
+ <label className="block text-xs font-medium text-zinc-400 mb-1">Agent Name</label>
+ <input
+ type="text"
+ required
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder="e.g. DataAnalyst, SecurityAuditor"
+ className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors"
+ />
+ </div>
+
+ <div>
+ <label className="block text-xs font-medium text-zinc-400 mb-1">Role & Title</label>
+ <input
+ type="text"
+ value={title}
+ onChange={(e) => setTitle(e.target.value)}
+ placeholder="e.g. Senior Security Auditor"
+ className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors"
+ />
+ </div>
+
+ <div>
+ <label className="block text-xs font-medium text-zinc-400 mb-1">Role Specialty</label>
+ <div className="grid grid-cols-2 gap-2">
+ {[
+ { id: 'architect', label: 'Architecture', icon: Layers },
+ { id: 'tech_lead', label: 'Coding & Prototyping', icon: Code2 },
+ { id: 'devops', label: 'DevOps & Shell', icon: Terminal },
+ { id: 'security', label: 'Security & Audit', icon: Shield },
+ ].map((item) => {
+ const Icon = item.icon;
+ const active = roleStyle === item.id;
+ return (
+ <button
+ key={item.id}
+ type="button"
+ onClick={() => setRoleStyle(item.id)}
+ className={`flex items-center gap-2 p-2 rounded-lg border text-left text-xs transition-all ${
+ active
+ ? 'border-sky-500/50 bg-sky-500/10 text-sky-300'
+ : 'border-zinc-800 bg-zinc-950/60 text-zinc-400 hover:border-zinc-700'
+ }`}
+ >
+ <Icon size={14} className={active ? 'text-sky-400' : 'text-zinc-500'} />
+ <span className="truncate">{item.label}</span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+
+ <div>
+ <label className="block text-xs font-medium text-zinc-400 mb-1">Model Engine</label>
+ <select
+ value={model}
+ onChange={(e) => setModel(e.target.value)}
+ className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 focus:border-sky-500 focus:outline-none transition-colors"
+ >
+ <option value="auto">Auto (Laya 33ms Decision Router - Recommended)</option>
+ <option value="claude">Anthropic Claude (Deep Architecture)</option>
+ <option value="grok">xAI Grok (Fast Technical Reasoning)</option>
+ <option value="codex">OpenAI Codex (Coding & Scripts)</option>
+ <option value="local_ollama">Local Ollama (Offline / Private)</option>
+ </select>
+ </div>
+
+ <div>
+ <label className="block text-xs font-medium text-zinc-400 mb-1">Persona & System Prompt</label>
+ <textarea
+ rows={3}
+ value={prompt}
+ onChange={(e) => setPrompt(e.target.value)}
+ placeholder="Define instructions, personality, tone, and domain expertise..."
+ className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors resize-none"
+ />
+ </div>
+
+ <div className="flex items-center justify-end gap-2.5 pt-2 border-t border-zinc-800">
+ <button
+ type="button"
+ onClick={() => {
+ playSfx('click');
+ onClose();
+ }}
+ className="px-3.5 py-2 rounded-lg text-xs font-medium text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 transition-colors"
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ disabled={submitting || !name.trim()}
+ className="px-4 py-2 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm disabled:opacity-50"
+ >
+ Create Agent
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
new file mode 100644
index 00000000..e0775e4e
--- /dev/null
+++ b/frontend/src/components/SettingsModal.tsx
@@ -0,0 +1,239 @@
+import React, { useState, useEffect } from 'react';
+import { Cpu, Key, Globe, X, Sparkles, Check } from 'lucide-react';
+import { playSfx } from '../audio/chiptune';
+
+interface SettingsData {
+ anthropic_api_key: string;
+ xai_api_key: string;
+ openai_api_key: string;
+ ollama_url: string;
+ claude_cli_found: boolean;
+ claude_cli_path: string | null;
+ grok_cli_found: boolean;
+ grok_cli_path: string | null;
+ codex_cli_found: boolean;
+ codex_cli_path: string | null;
+}
+
+interface SettingsModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+}
+
+export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose }) => {
+ const [settings, setSettings] = useState<SettingsData | null>(null);
+ const [anthropicKey, setAnthropicKey] = useState('');
+ const [xaiKey, setXaiKey] = useState('');
+ const [openaiKey, setOpenaiKey] = useState('');
+ const [ollamaUrl, setOllamaUrl] = useState('http://localhost:11434/v1');
+ const [saving, setSaving] = useState(false);
+ const [saveSuccess, setSaveSuccess] = useState(false);
+
+ useEffect(() => {
+ if (isOpen) {
+ fetch('/api/settings')
+ .then((r) => r.json())
+ .then((data: SettingsData) => {
+ setSettings(data);
+ setAnthropicKey(data.anthropic_api_key);
+ setXaiKey(data.xai_api_key);
+ setOpenaiKey(data.openai_api_key);
+ setOllamaUrl(data.ollama_url || 'http://localhost:11434/v1');
+ })
+ .catch((err) => console.error('Failed to load settings:', err));
+ }
+ }, [isOpen]);
+
+ if (!isOpen) return null;
+
+ const handleSave = async (e: React.FormEvent) => {
+ e.preventDefault();
+ setSaving(true);
+ playSfx('click');
+
+ try {
+ const res = await fetch('/api/settings', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ anthropic_api_key: anthropicKey,
+ xai_api_key: xaiKey,
+ openai_api_key: openaiKey,
+ ollama_url: ollamaUrl,
+ }),
+ });
+
+ if (res.ok) {
+ setSaveSuccess(true);
+ playSfx('coin');
+ setTimeout(() => setSaveSuccess(false), 2500);
+ }
+ } catch (err) {
+ console.error('Failed to save settings:', err);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4 select-none">
+ <div className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-lg w-full p-6 text-zinc-100 shadow-2xl space-y-6">
+ {/* Header */}
+ <div className="flex items-center justify-between border-b border-zinc-800 pb-4">
+ <div className="flex items-center gap-2.5">
+ <div className="w-8 h-8 rounded-lg bg-sky-500/10 border border-sky-500/20 flex items-center justify-center text-sky-400">
+ <Sparkles size={17} />
+ </div>
+ <div>
+ <h2 className="text-sm font-semibold text-zinc-100">Fleet & Engine Settings</h2>
+ <p className="text-xs text-zinc-400">Configure local CLI routing and cloud provider credentials</p>
+ </div>
+ </div>
+
+ <button
+ onClick={() => {
+ playSfx('click');
+ onClose();
+ }}
+ className="p-1.5 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors"
+ >
+ <X size={18} />
+ </button>
+ </div>
+
+ {/* Local CLI Auto-Detection Fleet */}
+ <div className="bg-zinc-950/60 p-4 rounded-xl border border-zinc-800 space-y-3">
+ <div className="flex items-center gap-2 text-xs font-medium text-zinc-300">
+ <Cpu size={15} className="text-sky-400" />
+ <span>Local Host CLI Engines (Auto-Detected)</span>
+ </div>
+ <p className="text-xs text-zinc-400 leading-relaxed">
+ Tasks auto-route through your authenticated local terminal CLIs without requiring cloud API keys.
+ </p>
+
+ <div className="grid grid-cols-1 gap-2 pt-1">
+ <div className="flex items-center justify-between bg-zinc-900/90 px-3 py-2 rounded-lg border border-zinc-800 text-xs">
+ <div className="flex items-center gap-2">
+ <span className={`w-2 h-2 rounded-full ${settings?.claude_cli_found ? 'bg-emerald-400 shadow-sm shadow-emerald-500/50' : 'bg-zinc-600'}`} />
+ <span className="font-medium text-zinc-200">Claude Code CLI</span>
+ </div>
+ <span className="text-[11px] font-mono text-zinc-400">
+ {settings?.claude_cli_found ? 'Connected' : 'Not installed'}
+ </span>
+ </div>
+
+ <div className="flex items-center justify-between bg-zinc-900/90 px-3 py-2 rounded-lg border border-zinc-800 text-xs">
+ <div className="flex items-center gap-2">
+ <span className={`w-2 h-2 rounded-full ${settings?.grok_cli_found ? 'bg-emerald-400 shadow-sm shadow-emerald-500/50' : 'bg-zinc-600'}`} />
+ <span className="font-medium text-zinc-200">xAI Grok CLI</span>
+ </div>
+ <span className="text-[11px] font-mono text-zinc-400">
+ {settings?.grok_cli_found ? 'Connected' : 'Not installed'}
+ </span>
+ </div>
+
+ <div className="flex items-center justify-between bg-zinc-900/90 px-3 py-2 rounded-lg border border-zinc-800 text-xs">
+ <div className="flex items-center gap-2">
+ <span className={`w-2 h-2 rounded-full ${settings?.codex_cli_found ? 'bg-emerald-400 shadow-sm shadow-emerald-500/50' : 'bg-zinc-600'}`} />
+ <span className="font-medium text-zinc-200">OpenAI Codex CLI</span>
+ </div>
+ <span className="text-[11px] font-mono text-zinc-400">
+ {settings?.codex_cli_found ? 'Connected' : 'Not installed'}
+ </span>
+ </div>
+ </div>
+ </div>
+
+ {/* Cloud API Keys Form */}
+ <form onSubmit={handleSave} className="space-y-4">
+ <div className="flex items-center gap-2 text-xs font-medium text-zinc-300">
+ <Key size={14} className="text-violet-400" />
+ <span>Direct Cloud API Keys (Optional)</span>
+ </div>
+
+ <div className="space-y-3">
+ <div>
+ <label className="block text-xs font-medium text-zinc-400 mb-1">
+ Anthropic API Key
+ </label>
+ <input
+ type="password"
+ value={anthropicKey}
+ onChange={(e) => setAnthropicKey(e.target.value)}
+ placeholder="sk-ant-api03-..."
+ className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors"
+ />
+ </div>
+
+ <div>
+ <label className="block text-xs font-medium text-zinc-400 mb-1">
+ xAI Grok API Key
+ </label>
+ <input
+ type="password"
+ value={xaiKey}
+ onChange={(e) => setXaiKey(e.target.value)}
+ placeholder="xai-..."
+ className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors"
+ />
+ </div>
+
+ <div>
+ <label className="block text-xs font-medium text-zinc-400 mb-1">
+ OpenAI API Key
+ </label>
+ <input
+ type="password"
+ value={openaiKey}
+ onChange={(e) => setOpenaiKey(e.target.value)}
+ placeholder="sk-..."
+ className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors"
+ />
+ </div>
+
+ <div>
+ <label className="block text-xs font-medium text-zinc-400 mb-1 flex items-center gap-1.5">
+ <Globe size={13} className="text-zinc-500" />
+ <span>Ollama Base URL</span>
+ </label>
+ <input
+ type="text"
+ value={ollamaUrl}
+ onChange={(e) => setOllamaUrl(e.target.value)}
+ placeholder="http://localhost:11434/v1"
+ className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors"
+ />
+ </div>
+ </div>
+
+ {saveSuccess && (
+ <div className="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 px-3 py-2 rounded-lg text-xs flex items-center gap-2">
+ <Check size={14} />
+ <span>Settings saved successfully to database</span>
+ </div>
+ )}
+
+ <div className="flex items-center justify-end gap-2.5 pt-2 border-t border-zinc-800">
+ <button
+ type="button"
+ onClick={() => {
+ playSfx('click');
+ onClose();
+ }}
+ className="px-3.5 py-2 rounded-lg text-xs font-medium text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 transition-colors"
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ disabled={saving}
+ className="px-4 py-2 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm"
+ >
+ {saving ? 'Saving...' : 'Save Settings'}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
new file mode 100644
index 00000000..69ce2103
--- /dev/null
+++ b/frontend/src/components/Sidebar.tsx
@@ -0,0 +1,132 @@
+import { Hash, Plus, CheckCircle2 } from 'lucide-react';
+import { ModernAvatar } from './ModernAvatar';
+
+export interface Kwant {
+ id: string;
+ name: string;
+ title: string;
+ persona_prompt: string;
+ avatar_sprite: string;
+ driver_type: string;
+ preferred_model: string;
+}
+
+export interface Channel {
+ id: string;
+ name: string;
+ description?: string;
+ lead_kwant_id: string;
+ member_kwants: string[];
+ routing_mode: string;
+}
+
+interface SidebarProps {
+ kwants: Kwant[];
+ channels: Channel[];
+ selectedId: string;
+ isChannel: boolean;
+ onSelectKwant: (kwant: Kwant) => void;
+ onSelectChannel: (channel: Channel) => void;
+ onSummonKwant: () => void;
+}
+
+export const Sidebar: React.FC<SidebarProps> = ({
+ kwants,
+ channels,
+ selectedId,
+ isChannel,
+ onSelectKwant,
+ onSelectChannel,
+ onSummonKwant,
+}) => {
+ return (
+ <aside className="w-64 border-r border-zinc-800/80 bg-zinc-900/40 flex flex-col h-full select-none flex-shrink-0">
+ {/* Top Header & New Agent Action */}
+ <div className="p-3 border-b border-zinc-800/60 flex items-center justify-between">
+ <span className="text-xs font-semibold uppercase tracking-wider text-zinc-400">Workspace</span>
+ <button
+ onClick={onSummonKwant}
+ className="flex items-center gap-1 px-2 py-1 text-xs font-medium text-sky-400 hover:text-sky-300 hover:bg-sky-500/10 rounded-md border border-sky-500/20 transition-all"
+ >
+ <Plus size={13} />
+ <span>New Agent</span>
+ </button>
+ </div>
+
+ <div className="flex-1 overflow-y-auto p-2 space-y-4">
+ {/* Channels Section */}
+ <div>
+ <div className="px-2 py-1 text-[11px] font-semibold text-zinc-500 uppercase tracking-wider">
+ Channels
+ </div>
+ <div className="mt-1 space-y-0.5">
+ {channels.map((c) => {
+ const active = isChannel && selectedId === c.id;
+ return (
+ <button
+ key={c.id}
+ onClick={() => onSelectChannel(c)}
+ className={`w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all text-left ${
+ active
+ ? 'bg-zinc-800 text-zinc-100 shadow-sm border border-zinc-700/50'
+ : 'text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800/50'
+ }`}
+ >
+ <Hash size={15} className={active ? 'text-sky-400' : 'text-zinc-500'} />
+ <span className="truncate">{c.name}</span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+
+ {/* AI Agents Fleet Section */}
+ <div>
+ <div className="px-2 py-1 flex items-center justify-between text-[11px] font-semibold text-zinc-500 uppercase tracking-wider">
+ <span>Agent Fleet ({kwants.length})</span>
+ </div>
+ <div className="mt-1 space-y-1">
+ {kwants.map((k) => {
+ const active = !isChannel && selectedId === k.id;
+ return (
+ <button
+ key={k.id}
+ onClick={() => onSelectKwant(k)}
+ className={`w-full flex items-center gap-3 p-2 rounded-xl text-left transition-all ${
+ active
+ ? 'bg-zinc-800/90 text-zinc-100 shadow-sm border border-zinc-700/60'
+ : 'text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800/40'
+ }`}
+ >
+ <ModernAvatar
+ role={k.avatar_sprite}
+ name={k.name}
+ size={32}
+ isOnline={true}
+ />
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center justify-between gap-1">
+ <span className="text-xs font-semibold text-zinc-200 truncate">{k.name}</span>
+ <span className="text-[10px] text-zinc-500 font-mono uppercase bg-zinc-900 px-1 py-0.2 rounded border border-zinc-800">
+ {k.preferred_model === 'auto' ? 'Laya' : k.preferred_model.split('-')[0]}
+ </span>
+ </div>
+ <p className="text-[11px] text-zinc-400 truncate mt-0.5">{k.title}</p>
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+
+ {/* Footer Host Bridge status */}
+ <div className="p-3 border-t border-zinc-800/60 bg-zinc-950/40 text-[11px] text-zinc-500 flex items-center justify-between">
+ <span className="flex items-center gap-1.5">
+ <CheckCircle2 size={13} className="text-emerald-400" />
+ <span>Local CLI Fleet Active</span>
+ </span>
+ </div>
+ </aside>
+ );
+};
diff --git a/frontend/src/components/SpriteAvatar.tsx b/frontend/src/components/SpriteAvatar.tsx
deleted file mode 100644
index fa040525..00000000
--- a/frontend/src/components/SpriteAvatar.tsx
+++ /dev/null
@@ -1,107 +0,0 @@
-import React from 'react';
-
-interface SpriteProps {
- sprite: string;
- size?: number;
- className?: string;
-}
-
-export const SpriteAvatar: React.FC<SpriteProps> = ({ sprite, size = 48, className = '' }) => {
- // 8-bit pixel art SVG sprites designed on a 16x16 grid
- const renderSpriteGrid = () => {
- switch (sprite) {
- case 'cyber_mage':
- return (
- <svg viewBox="0 0 16 16" width={size} height={size} className={className} style={{ imageRendering: 'pixelated' }}>
- <rect x="0" y="0" width="16" height="16" fill="#181622" />
- {/* Mage Hat */}
- <rect x="6" y="1" width="4" height="2" fill="#7209b7" />
- <rect x="5" y="3" width="6" height="2" fill="#7209b7" />
- <rect x="3" y="5" width="10" height="1" fill="#f72585" />
- {/* Face */}
- <rect x="5" y="6" width="6" height="4" fill="#ffd166" />
- {/* Glowing cyan eyes */}
- <rect x="6" y="7" width="1" height="1" fill="#00f5d4" />
- <rect x="9" y="7" width="1" height="1" fill="#00f5d4" />
- {/* Robe */}
- <rect x="4" y="10" width="8" height="5" fill="#3a0ca3" />
- {/* Staff */}
- <rect x="13" y="4" width="1" height="11" fill="#b5179e" />
- <rect x="12" y="3" width="3" height="2" fill="#00f5d4" />
- </svg>
- );
-
- case 'pixel_ninja':
- return (
- <svg viewBox="0 0 16 16" width={size} height={size} className={className} style={{ imageRendering: 'pixelated' }}>
- <rect x="0" y="0" width="16" height="16" fill="#181622" />
- {/* Ninja Hood */}
- <rect x="4" y="2" width="8" height="5" fill="#2b2d42" />
- {/* Mask Slit */}
- <rect x="5" y="5" width="6" height="2" fill="#ffd166" />
- {/* Sharp Eyes */}
- <rect x="6" y="5" width="1" height="1" fill="#ef233c" />
- <rect x="9" y="5" width="1" height="1" fill="#ef233c" />
- {/* Body */}
- <rect x="4" y="8" width="8" height="7" fill="#1b1c24" />
- <rect x="6" y="8" width="4" height="3" fill="#ef233c" />
- {/* Katana */}
- <rect x="2" y="3" width="1" height="10" fill="#e0e1dd" />
- <rect x="1" y="11" width="3" height="1" fill="#fca311" />
- </svg>
- );
-
- case 'terminal_knight':
- return (
- <svg viewBox="0 0 16 16" width={size} height={size} className={className} style={{ imageRendering: 'pixelated' }}>
- <rect x="0" y="0" width="16" height="16" fill="#181622" />
- {/* CRT Helmet */}
- <rect x="3" y="2" width="10" height="7" fill="#4a4e69" />
- <rect x="4" y="3" width="8" height="5" fill="#03045e" />
- {/* Screen readout */}
- <rect x="6" y="5" width="4" height="1" fill="#38b000" />
- <rect x="5" y="6" width="3" height="1" fill="#38b000" />
- {/* Armor */}
- <rect x="4" y="9" width="8" height="6" fill="#9a8c98" />
- <rect x="6" y="10" width="4" height="4" fill="#fca311" />
- {/* Shield */}
- <rect x="1" y="7" width="2" height="7" fill="#c9ada7" />
- </svg>
- );
-
- case 'user':
- return (
- <svg viewBox="0 0 16 16" width={size} height={size} className={className} style={{ imageRendering: 'pixelated' }}>
- <rect x="0" y="0" width="16" height="16" fill="#181622" />
- {/* Hair */}
- <rect x="4" y="2" width="8" height="3" fill="#8d5b4c" />
- {/* Red Headband */}
- <rect x="4" y="5" width="8" height="1" fill="#f72585" />
- <rect x="12" y="6" width="2" height="2" fill="#f72585" />
- {/* Face */}
- <rect x="4" y="6" width="8" height="4" fill="#ffd166" />
- <rect x="6" y="7" width="1" height="1" fill="#000" />
- <rect x="9" y="7" width="1" height="1" fill="#000" />
- {/* Jacket */}
- <rect x="4" y="10" width="8" height="5" fill="#00f5d4" />
- <rect x="6" y="10" width="4" height="4" fill="#ffffff" />
- </svg>
- );
-
- default:
- // Glitch Rogue / Bot
- return (
- <svg viewBox="0 0 16 16" width={size} height={size} className={className} style={{ imageRendering: 'pixelated' }}>
- <rect x="0" y="0" width="16" height="16" fill="#181622" />
- <rect x="4" y="3" width="8" height="8" fill="#fca311" />
- <rect x="6" y="5" width="1" height="2" fill="#000" />
- <rect x="9" y="5" width="1" height="2" fill="#000" />
- <rect x="6" y="9" width="4" height="1" fill="#000" />
- <rect x="4" y="11" width="8" height="4" fill="#2c283e" />
- </svg>
- );
- }
- };
-
- return <div className="inline-block p-1 pixel-box bg-arcade-panel">{renderSpriteGrid()}</div>;
-};
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index e291158f..8699ad90 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -1,7 +1,7 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { App } from './App';
-import './styles/pixel.css';
+import './styles/modern.css';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
diff --git a/frontend/src/styles/modern.css b/frontend/src/styles/modern.css
new file mode 100644
index 00000000..084ca26d
--- /dev/null
+++ b/frontend/src/styles/modern.css
@@ -0,0 +1,57 @@
+@tailwind base;
+@tailwind components;
+@tailwind utilities;
+
+@layer base {
+ * {
+ border-color: theme('colors.zinc.800');
+ }
+
+ body {
+ background-color: theme('colors.zinc.950');
+ color: theme('colors.zinc.100');
+ font-family: theme('fontFamily.sans');
+ }
+}
+
+/* Sleek minimalist scrollbar */
+::-webkit-scrollbar {
+ width: 6px;
+ height: 6px;
+}
+
+::-webkit-scrollbar-track {
+ background: transparent;
+}
+
+::-webkit-scrollbar-thumb {
+ background: theme('colors.zinc.800');
+ border-radius: 9999px;
+}
+
+::-webkit-scrollbar-thumb:hover {
+ background: theme('colors.zinc.700');
+}
+
+/* Subtle typing cursor */
+@keyframes blink {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0; }
+}
+
+.cursor-blink {
+ animation: blink 0.9s infinite;
+}
+
+/* Markdown styling */
+.prose pre {
+ background-color: theme('colors.zinc.900') !important;
+ border: 1px solid theme('colors.zinc.800') !important;
+ border-radius: 0.5rem !important;
+ padding: 0.85rem !important;
+}
+
+.prose code {
+ color: theme('colors.sky.300') !important;
+ font-family: theme('fontFamily.mono') !important;
+}
diff --git a/frontend/src/styles/pixel.css b/frontend/src/styles/pixel.css
deleted file mode 100644
index 01d50891..00000000
--- a/frontend/src/styles/pixel.css
+++ /dev/null
@@ -1,117 +0,0 @@
-@tailwind base;
-@tailwind components;
-@tailwind utilities;
-
-/* Custom 8-bit CRT and scanline overlay */
-.crt-overlay {
- position: relative;
-}
-
-.crt-overlay::after {
- content: " ";
- display: block;
- position: absolute;
- top: 0; left: 0; bottom: 0; right: 0;
- background: linear-gradient(rgba(18, 16, 16, 0) 50%, rgba(0, 0, 0, 0.25) 50%), linear-gradient(90deg, rgba(255, 0, 0, 0.03), rgba(0, 255, 0, 0.01), rgba(0, 0, 255, 0.03));
- z-index: 50;
- background-size: 100% 3px, 6px 100%;
- pointer-events: none;
-}
-
-/* Pixel chiseled box styling */
-.pixel-box {
- background-color: #181622;
- border: 3px solid #2c283e;
- box-shadow: 4px 4px 0px 0px #000000;
-}
-
-.pixel-box-amber {
- background-color: #181622;
- border: 3px solid #fca311;
- box-shadow: 4px 4px 0px 0px #000000;
-}
-
-.pixel-box-cyan {
- background-color: #181622;
- border: 3px solid #00f5d4;
- box-shadow: 4px 4px 0px 0px #000000;
-}
-
-/* Pixel button with press state */
-.pixel-btn {
- font-family: "Press Start 2P", monospace;
- font-size: 10px;
- text-transform: uppercase;
- padding: 8px 12px;
- border: 2px solid #000;
- box-shadow: 3px 3px 0px #000;
- transition: transform 0.05s ease, box-shadow 0.05s ease;
- cursor: pointer;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- gap: 6px;
-}
-
-.pixel-btn:active {
- transform: translate(2px, 2px);
- box-shadow: 1px 1px 0px #000;
-}
-
-.pixel-btn-amber {
- background-color: #fca311;
- color: #000;
-}
-.pixel-btn-amber:hover {
- background-color: #ffb703;
-}
-
-.pixel-btn-cyan {
- background-color: #00f5d4;
- color: #000;
-}
-.pixel-btn-cyan:hover {
- background-color: #38ef7d;
-}
-
-.pixel-btn-magenta {
- background-color: #f72585;
- color: #fff;
-}
-.pixel-btn-magenta:hover {
- background-color: #b5179e;
-}
-
-.pixel-btn-dark {
- background-color: #2c283e;
- color: #fff;
-}
-.pixel-btn-dark:hover {
- background-color: #3f3b56;
-}
-
-/* Retro scrollbar */
-::-webkit-scrollbar {
- width: 8px;
- height: 8px;
-}
-::-webkit-scrollbar-track {
- background: #0d0c13;
-}
-::-webkit-scrollbar-thumb {
- background: #2c283e;
- border: 1px solid #000;
-}
-::-webkit-scrollbar-thumb:hover {
- background: #fca311;
-}
-
-/* Blinking cursor */
-@keyframes blink {
- 0%, 49% { opacity: 1; }
- 50%, 100% { opacity: 0; }
-}
-
-.cursor-blink {
- animation: blink 1s infinite;
-}
diff --git a/frontend/tailwind.config.js b/frontend/tailwind.config.js
index 1cf41168..34690119 100644
--- a/frontend/tailwind.config.js
+++ b/frontend/tailwind.config.js
@@ -7,28 +7,18 @@ export default {
theme: {
extend: {
colors: {
- arcade: {
- dark: '#0d0c13',
- panel: '#181622',
- border: '#2c283e',
- amber: '#fca311',
- cyan: '#00f5d4',
- magenta: '#f72585',
- green: '#38b000',
- muted: '#8b8a9e',
- }
+ brand: {
+ 50: '#f0f9ff',
+ 100: '#e0f2fe',
+ 400: '#38bdf8',
+ 500: '#0ea5e9',
+ 600: '#0284c7',
+ },
},
fontFamily: {
- pixel: ['"Press Start 2P"', 'monospace'],
- retro: ['"Silkscreen"', 'monospace'],
- terminal: ['"VT323"', 'monospace'],
+ sans: ['Inter', '-apple-system', 'BlinkMacSystemFont', '"Segoe UI"', 'Roboto', 'sans-serif'],
+ mono: ['"JetBrains Mono"', 'monospace'],
},
- boxShadow: {
- 'pixel': '3px 3px 0px 0px #000000',
- 'pixel-sm': '2px 2px 0px 0px #000000',
- 'pixel-amber': '3px 3px 0px 0px #fca311',
- 'pixel-cyan': '3px 3px 0px 0px #00f5d4',
- }
},
},
plugins: [],
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 62054454..fabde879 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -61,26 +61,26 @@ impl Database {
if count.0 == 0 {
let starters = vec![
NewKwant {
- name: "CyberMage".into(),
- title: "Arcane Architect".into(),
- persona_prompt: "You are CyberMage, an ancient 8-bit digital sorcerer. You specialize in software architecture, clever problem solving, and complex refactoring. Speak with slight retro-game flair.".into(),
- avatar_sprite: "cyber_mage".into(),
+ name: "Architect".into(),
+ title: "Systems Architect".into(),
+ persona_prompt: "You are the Architect, an expert in deep systems architecture, software design, and complex multi-file engineering. You give structured, thorough, and highly insightful technical advice.".into(),
+ avatar_sprite: "architect".into(),
driver_type: "api".into(),
preferred_model: "auto".into(),
},
NewKwant {
- name: "PixelNinja".into(),
- title: "Swift Blade".into(),
- persona_prompt: "You are PixelNinja, a swift and precise coding assassin. You write razor-sharp, optimized algorithms, concise functions, and clean tests. You avoid unnecessary fluff.".into(),
- avatar_sprite: "pixel_ninja".into(),
+ name: "TechLead".into(),
+ title: "Staff Engineer & Prototyper".into(),
+ persona_prompt: "You are the Tech Lead, a sharp, pragmatic engineer who excels in fast reasoning, rapid prototyping, and clear technical communication.".into(),
+ avatar_sprite: "tech_lead".into(),
driver_type: "api".into(),
preferred_model: "auto".into(),
},
NewKwant {
- name: "TerminalKnight".into(),
- title: "Guardian of the Shell".into(),
- persona_prompt: "You are TerminalKnight, an armored defender of systems, bash commands, and infrastructure. You help automate server setups, review security, and manage files safely.".into(),
- avatar_sprite: "terminal_knight".into(),
+ name: "DevOps".into(),
+ title: "Systems & Security Engineer".into(),
+ persona_prompt: "You are the DevOps Engineer, specializing in shell commands, server infrastructure, containerization, security policies, and automation.".into(),
+ avatar_sprite: "devops".into(),
driver_type: "api".into(),
preferred_model: "auto".into(),
},
@@ -95,13 +95,18 @@ impl Database {
if let Some(lead) = kwants.first() {
let chan = NewChannel {
name: "general".into(),
- description: Some("The main Guild tavern for all Kwants".into()),
+ description: Some("Main collaboration hub for all agents".into()),
lead_kwant_id: lead.id.clone(),
member_kwants: kwants.iter().map(|k| k.id.clone()).collect(),
routing_mode: "auto".into(),
};
self.create_channel(&chan).await?;
}
+ } else {
+ // Smoothly migrate any legacy starter names and prompts
+ let _ = sqlx::query("UPDATE kwants SET name = 'Architect', title = 'Systems Architect', avatar_sprite = 'architect', persona_prompt = 'You are the Architect, an expert in deep systems architecture, software design, and complex multi-file engineering. You give structured, thorough, and highly insightful technical advice.' WHERE name IN ('CyberMage', 'Architect') AND persona_prompt LIKE '%CyberMage%'").execute(&self.pool).await;
+ let _ = sqlx::query("UPDATE kwants SET name = 'TechLead', title = 'Staff Engineer & Prototyper', avatar_sprite = 'tech_lead', persona_prompt = 'You are the Tech Lead, a sharp, pragmatic engineer who excels in fast reasoning, rapid prototyping, and clear technical communication.' WHERE name IN ('PixelNinja', 'TechLead') AND persona_prompt LIKE '%PixelNinja%'").execute(&self.pool).await;
+ let _ = sqlx::query("UPDATE kwants SET name = 'DevOps', title = 'Systems & Security Engineer', avatar_sprite = 'devops', persona_prompt = 'You are the DevOps Engineer, specializing in shell commands, server infrastructure, containerization, security policies, and automation.' WHERE name IN ('TerminalKnight', 'DevOps') AND persona_prompt LIKE '%TerminalKnight%'").execute(&self.pool).await;
}
Ok(())
diff --git a/src/drivers/api.rs b/src/drivers/api.rs
index 9245a3e5..c2d8671a 100644
--- a/src/drivers/api.rs
+++ b/src/drivers/api.rs
@@ -80,12 +80,19 @@ impl Driver for ApiDriver {
}
messages.push(json!({"role": "user", "content": input.prompt}));
+ let effort = input.effort_level.as_deref().unwrap_or("medium");
+ let max_tokens = match effort {
+ "low" => 512,
+ "high" => 4096,
+ _ => input.kwant.max_tokens,
+ };
+
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,
+ "max_tokens": max_tokens,
});
let mut req = self.client.post(&url).json(&body);
@@ -115,7 +122,7 @@ impl Driver for ApiDriver {
return Ok(TurnOutput {
text,
- reasoning: None,
+ reasoning: Some(format!("Model: {} [Effort: {}]", target_model, effort)),
tokens_used: tokens,
});
}
@@ -129,25 +136,25 @@ impl Driver for ApiDriver {
}
}
- // Offline / Sandbox Mode: Emulate retro 8-bit agent reply with typing effect
+ // Offline / Sandbox Mode: Inform user that no API key was configured
let _ = event_tx
.send(RuntimeEvent::ThinkingDelta(format!(
- "[{}] Channeling mana via {}...",
+ "[{}] Searching mana link for {}...",
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
+ "⚔️ [{}] \"No active API key or CLI connection detected for '{}'. Please enter your API key in ⚙️ Settings or authenticate your local CLI (claude / grok / codex). Received command: '{}'\"",
+ input.kwant.name, target_model, 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;
+ tokio::time::sleep(Duration::from_millis(15)).await;
}
let tokens = response_text.len() / 4 + 10;
@@ -162,7 +169,7 @@ impl Driver for ApiDriver {
Ok(TurnOutput {
text: response_text,
- reasoning: Some(format!("Model: {}", target_model)),
+ reasoning: Some(format!("Model: {} (Unauthenticated)", target_model)),
tokens_used: tokens,
})
}
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index 9abf194a..d30ed406 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -1,19 +1,71 @@
use super::{events::RuntimeEvent, Driver, DriverError, TurnInput, TurnOutput};
use async_trait::async_trait;
+use std::path::Path;
use std::process::Stdio;
use std::time::Instant;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
use tokio::sync::mpsc;
+pub fn find_cli_binary(name: &str) -> Option<String> {
+ // 1. Try standard which command
+ if let Ok(output) = std::process::Command::new("which").arg(name).output() {
+ if output.status.success() {
+ let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
+ if !path.is_empty() && Path::new(&path).exists() {
+ return Some(path);
+ }
+ }
+ }
+
+ // 2. Check ~/.local/bin and /opt/homebrew/bin
+ if let Ok(home) = std::env::var("HOME") {
+ let local_path = format!("{}/.local/bin/{}", home, name);
+ if Path::new(&local_path).exists() {
+ return Some(local_path);
+ }
+
+ // For grok / nvm node binaries
+ if name == "grok" {
+ let nvm_pattern = format!("{}/.nvm/versions/node", home);
+ if let Ok(entries) = std::fs::read_dir(&nvm_pattern) {
+ for entry in entries.flatten() {
+ let candidate = entry.path().join("bin").join("grok");
+ if candidate.exists() {
+ return Some(candidate.to_string_lossy().to_string());
+ }
+ }
+ }
+ }
+ }
+
+ let brew_path = format!("/opt/homebrew/bin/{}", name);
+ if Path::new(&brew_path).exists() {
+ return Some(brew_path);
+ }
+
+ let usr_path = format!("/usr/local/bin/{}", name);
+ if Path::new(&usr_path).exists() {
+ return Some(usr_path);
+ }
+
+ None
+}
+
#[derive(Clone, Debug, Default)]
pub struct CliDriver {
pub cli_binary: Option<String>,
+ pub tool_kind: String, // "claude", "codex", "grok"
}
impl CliDriver {
- pub fn new(cli_binary: Option<String>) -> Self {
- Self { cli_binary }
+ pub fn new(cli_binary: Option<String>, tool_kind: Option<String>) -> Self {
+ let kind = tool_kind.unwrap_or_else(|| "claude".into());
+ let bin = cli_binary.or_else(|| find_cli_binary(&kind));
+ Self {
+ cli_binary: bin,
+ tool_kind: kind,
+ }
}
}
@@ -25,10 +77,69 @@ impl Driver for CliDriver {
event_tx: mpsc::Sender<RuntimeEvent>,
) -> Result<TurnOutput, DriverError> {
let start = Instant::now();
- let bin = self.cli_binary.as_deref().unwrap_or("claude");
+ let bin_path = match &self.cli_binary {
+ Some(b) => b.clone(),
+ None => {
+ let msg = format!(
+ "⚠️ [{}] Local CLI for `{}` was not found on this system.",
+ input.kwant.name, self.tool_kind
+ );
+ let _ = event_tx.send(RuntimeEvent::TextDelta(msg.clone())).await;
+ let _ = event_tx
+ .send(RuntimeEvent::TurnComplete {
+ tokens: 10,
+ duration_ms: 10,
+ })
+ .await;
+ return Ok(TurnOutput {
+ text: msg,
+ reasoning: None,
+ tokens_used: 10,
+ });
+ }
+ };
+
+ let mut cmd = Command::new(&bin_path);
+ let mut codex_out_file: Option<String> = None;
+
+ let effort = input.effort_level.as_deref().unwrap_or("medium");
+
+ let _ = event_tx
+ .send(RuntimeEvent::ThinkingDelta(format!(
+ "Invoking local {} CLI (effort: {}, binary: {})...",
+ self.tool_kind, effort, bin_path
+ )))
+ .await;
+
+ 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());
+ let codex_effort = match effort {
+ "high" => "high",
+ "low" => "low",
+ _ => "medium",
+ };
+ cmd.arg("exec")
+ .arg("--ephemeral")
+ .arg("--skip-git-repo-check")
+ .arg("--color")
+ .arg("never")
+ .arg("-c")
+ .arg(format!("reasoning_effort=\"{}\"", codex_effort))
+ .arg("-o")
+ .arg(&out_file)
+ .arg(&input.prompt);
+ codex_out_file = Some(out_file);
+ }
+ "grok" => {
+ cmd.arg("-p").arg(&input.prompt);
+ }
+ _ => {
+ // claude default
+ cmd.arg("-p").arg(&input.prompt);
+ }
+ }
- let mut cmd = Command::new(bin);
- cmd.arg("--print").arg(&input.prompt);
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
@@ -38,16 +149,27 @@ impl Driver for CliDriver {
let mut output_str = String::new();
let mut buffer = [0u8; 1024];
- while let Ok(n) = stdout.read(&mut buffer).await {
- if n == 0 {
- break;
+ if codex_out_file.is_none() {
+ 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 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;
+
+ if let Some(ref out_file) = codex_out_file {
+ if let Ok(content) = tokio::fs::read_to_string(out_file).await {
+ output_str = content;
+ }
+ let _ = tokio::fs::remove_file(out_file).await;
+ let _ = event_tx.send(RuntimeEvent::TextDelta(output_str.clone())).await;
+ }
+
let duration = start.elapsed().as_millis() as u64;
let tokens = output_str.len() / 4;
@@ -60,15 +182,18 @@ impl Driver for CliDriver {
Ok(TurnOutput {
text: output_str,
- reasoning: Some(format!("Executed via {} CLI", bin)),
+ reasoning: Some(format!(
+ "Executed via {} CLI ({}) [Effort: {}]",
+ self.tool_kind, bin_path, effort
+ )),
tokens_used: tokens,
})
}
Err(e) => {
- tracing::warn!(error = %e, binary = %bin, "CLI binary execution failed");
+ tracing::warn!(error = %e, binary = %bin_path, "CLI binary execution failed");
let msg = format!(
- "⚠️ [{}] CLI `{}` is not installed or available on this host. ({})",
- input.kwant.name, bin, e
+ "⚠️ [{}] Execution error for CLI `{}`: {}",
+ input.kwant.name, bin_path, e
);
let _ = event_tx.send(RuntimeEvent::TextDelta(msg.clone())).await;
let _ = event_tx
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index 036da3cc..fbe5f6f1 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -3,7 +3,7 @@ pub mod cli;
pub mod events;
pub use api::ApiDriver;
-pub use cli::CliDriver;
+pub use cli::{find_cli_binary, CliDriver};
pub use events::RuntimeEvent;
use crate::db::models::{Kwant, Message};
@@ -31,6 +31,84 @@ pub struct TurnInput {
pub prompt: String,
pub history: Vec<Message>,
pub model_override: Option<String>,
+ pub effort_level: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct ModelDescriptor {
+ pub id: String,
+ pub display_name: String,
+ pub capability_desc: String,
+ pub is_cli: bool,
+}
+
+/// Automatically detects all currently available and functional models on the host
+pub async fn detect_available_models(db: &crate::db::Database) -> Vec<ModelDescriptor> {
+ let mut available = Vec::new();
+
+ // 1. Claude
+ let claude_cli = find_cli_binary("claude");
+ let claude_key = db.get_setting("anthropic_api_key").await.ok().flatten()
+ .or_else(|| std::env::var("ANTHROPIC_API_KEY").ok());
+ if claude_cli.is_some() || claude_key.is_some() {
+ available.push(ModelDescriptor {
+ id: "claude".into(),
+ display_name: "Claude 3.5 Sonnet".into(),
+ capability_desc: "deep architecture, multi-file refactoring, long complex analysis".into(),
+ is_cli: claude_key.is_none() && claude_cli.is_some(),
+ });
+ }
+
+ // 2. Grok
+ let grok_cli = find_cli_binary("grok");
+ let grok_key = db.get_setting("xai_api_key").await.ok().flatten()
+ .or_else(|| std::env::var("XAI_API_KEY").ok());
+ if grok_cli.is_some() || grok_key.is_some() {
+ available.push(ModelDescriptor {
+ id: "grok".into(),
+ display_name: "xAI Grok-2".into(),
+ capability_desc: "fast technical reasoning, witty banter, quick coding solutions".into(),
+ is_cli: grok_key.is_none() && grok_cli.is_some(),
+ });
+ }
+
+ // 3. Codex
+ let codex_cli = find_cli_binary("codex");
+ let codex_key = db.get_setting("openai_api_key").await.ok().flatten()
+ .or_else(|| std::env::var("OPENAI_API_KEY").ok());
+ if codex_cli.is_some() || codex_key.is_some() {
+ available.push(ModelDescriptor {
+ id: "codex".into(),
+ display_name: "OpenAI Codex".into(),
+ capability_desc: "direct code generation, standard algorithms, regex, JSON transforms".into(),
+ is_cli: codex_key.is_none() && codex_cli.is_some(),
+ });
+ }
+
+ // 4. Local Ollama
+ let ollama_url = db.get_setting("ollama_url").await.ok().flatten()
+ .or_else(|| std::env::var("OLLAMA_URL").ok());
+ let ollama_cli = find_cli_binary("ollama");
+ if ollama_url.is_some() || ollama_cli.is_some() {
+ available.push(ModelDescriptor {
+ id: "local_ollama".into(),
+ display_name: "Local Ollama".into(),
+ capability_desc: "private data, offline tasks, zero API cost".into(),
+ is_cli: false,
+ });
+ }
+
+ // Fallback: If host has zero configured, provide default fleet so system functions
+ if available.is_empty() {
+ available.push(ModelDescriptor {
+ id: "grok".into(),
+ display_name: "Grok (Arcade Default)".into(),
+ capability_desc: "fast technical reasoning, witty banter, quick coding solutions".into(),
+ is_cli: false,
+ });
+ }
+
+ available
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -49,11 +127,64 @@ pub trait Driver: Send + Sync {
) -> 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())))
+/// Creates a driver for a Kwant based on target model, configured API keys, and locally installed CLIs
+pub fn resolve_driver_for_model(
+ target_model: &str,
+ configured_key: Option<String>,
+ endpoint: Option<String>,
+) -> Box<dyn Driver> {
+ // 1. If an explicit API key is provided, use ApiDriver directly
+ if let Some(key) = configured_key {
+ return Box::new(ApiDriver::new(Some(key), endpoint));
+ }
+
+ // 2. Check environment variable for direct API key
+ let env_key = if target_model.contains("claude") {
+ std::env::var("ANTHROPIC_API_KEY").ok()
+ } else if target_model.contains("grok") {
+ std::env::var("XAI_API_KEY").ok()
+ } else if target_model.contains("codex") || target_model.contains("gpt") {
+ std::env::var("OPENAI_API_KEY").ok()
} else {
- Box::new(ApiDriver::new(None, None))
+ None
+ };
+
+ if let Some(key) = env_key {
+ return Box::new(ApiDriver::new(Some(key), endpoint));
+ }
+
+ // 3. Bring-Your-Own-Agent CLI auto-discovery (Claude, Grok, Codex)
+ if target_model.contains("claude") {
+ if let Some(bin) = find_cli_binary("claude") {
+ return Box::new(CliDriver::new(Some(bin), Some("claude".into())));
+ }
+ } else if target_model.contains("grok") {
+ if let Some(bin) = find_cli_binary("grok") {
+ return Box::new(CliDriver::new(Some(bin), Some("grok".into())));
+ }
+ } else if target_model.contains("codex") || target_model.contains("gpt") {
+ if let Some(bin) = find_cli_binary("codex") {
+ return Box::new(CliDriver::new(Some(bin), Some("codex".into())));
+ }
+ } else if target_model == "local_ollama" {
+ return Box::new(ApiDriver::new(None, Some("http://localhost:11434/v1".into())));
+ }
+
+ // 4. Fallback: check if ANY local agent CLI is installed on this host
+ if let Some(bin) = find_cli_binary("claude") {
+ return Box::new(CliDriver::new(Some(bin), Some("claude".into())));
+ }
+ if let Some(bin) = find_cli_binary("grok") {
+ return Box::new(CliDriver::new(Some(bin), Some("grok".into())));
}
+ if let Some(bin) = find_cli_binary("codex") {
+ return Box::new(CliDriver::new(Some(bin), Some("codex".into())));
+ }
+
+ // 5. Default to ApiDriver (which will prompt user to set an API key in Settings)
+ Box::new(ApiDriver::new(None, endpoint))
+}
+
+pub fn create_driver_for_kwant(kwant: &Kwant) -> Box<dyn Driver> {
+ resolve_driver_for_model(&kwant.preferred_model, None, None)
}
diff --git a/src/main.rs b/src/main.rs
index 1f2133d7..540b674d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -10,7 +10,7 @@ use kwnt::{
use std::path::PathBuf;
#[derive(Parser, Debug)]
-#[command(name = "kwnt", author, version, about = "Kwants: 8-Bit AI Agent Platform in Rust")]
+#[command(name = "kwnt", author, version, about = "Kwants: Multi-Agent AI Platform in Rust")]
pub struct Cli {
#[command(subcommand)]
pub command: Option<Commands>,
@@ -21,7 +21,7 @@ pub struct Cli {
#[derive(Subcommand, Debug)]
pub enum Commands {
- /// Start the Kwants HTTP/SSE server and embedded 8-bit arcade UI
+ /// Start the Kwants HTTP/SSE server and embedded web UI
Serve {
#[arg(long, help = "Server host interface to bind")]
host: Option<String>,
@@ -86,14 +86,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
"Starting Kwants engine..."
);
println!(
- "🕹️ Kwants 8-Bit AI Agent Platform listening at http://{}",
+ "⚡ Kwants Multi-Agent AI Platform listening at http://{}",
addr
);
axum::serve(listener, app).await?;
}
None => {
- println!("🕹️ Kwants: 8-Bit AI Agent Platform in Rust");
+ println!("⚡ Kwants: Multi-Agent AI Platform in Rust");
println!("Run `kwnt serve` to start the server, or `kwnt --help` for options.");
}
}
diff --git a/src/router/fallback.rs b/src/router/fallback.rs
index cf8e61a3..f55494ae 100644
--- a/src/router/fallback.rs
+++ b/src/router/fallback.rs
@@ -2,9 +2,51 @@ use super::RouteDecision;
/// Evaluates a prompt using local keyword scoring heuristics when Laya is offline.
pub fn heuristic_fallback(prompt: &str, context: &str) -> RouteDecision {
+ heuristic_fallback_with_models(prompt, context, &[])
+}
+
+/// Evaluates prompt and selects best model from available candidates along with required effort level.
+pub fn heuristic_fallback_with_models(
+ prompt: &str,
+ context: &str,
+ available_models: &[String],
+) -> RouteDecision {
let lower_prompt = prompt.to_lowercase();
let lower_context = context.to_lowercase();
let combined = format!("{} {}", lower_prompt, lower_context);
+ let word_count = prompt.split_whitespace().count();
+
+ // Determine effort level: low, medium, high
+ let is_high_effort = combined.contains("architecture")
+ || combined.contains("refactor")
+ || combined.contains("complex")
+ || combined.contains("deep")
+ || combined.contains("benchmark")
+ || combined.contains("security")
+ || combined.contains("optimize")
+ || combined.contains("investigate")
+ || word_count >= 30;
+
+ let is_low_effort = word_count <= 6
+ || lower_prompt.starts_with("hi")
+ || lower_prompt.starts_with("hello")
+ || lower_prompt.starts_with("hey")
+ || lower_prompt.starts_with("say ")
+ || lower_prompt.starts_with("ping")
+ || lower_prompt.contains("joke")
+ || lower_prompt.contains("who are you");
+
+ let effort_level = if is_high_effort {
+ "high".to_string()
+ } else if is_low_effort {
+ "low".to_string()
+ } else {
+ "medium".to_string()
+ };
+
+ let is_available = |model: &str| -> bool {
+ available_models.is_empty() || available_models.iter().any(|m| m == model)
+ };
// 1. Private / local check
if combined.contains("private")
@@ -13,13 +55,16 @@ pub fn heuristic_fallback(prompt: &str, context: &str) -> RouteDecision {
|| combined.contains("offline")
|| combined.contains("sensitive")
{
- return RouteDecision {
- selected_model: "local_ollama".into(),
- confidence: 0.85,
- provider_endpoint: Some("http://localhost:11434/v1".into()),
- is_fallback: true,
- reasoning: "Local privacy keywords detected in prompt".into(),
- };
+ if is_available("local_ollama") {
+ return RouteDecision {
+ selected_model: "local_ollama".into(),
+ effort_level: effort_level.clone(),
+ confidence: 0.85,
+ provider_endpoint: Some("http://localhost:11434/v1".into()),
+ is_fallback: true,
+ reasoning: format!("Local privacy keywords detected; effort={}", effort_level),
+ };
+ }
}
// 2. Complex architecture / multi-file / deep analysis check
@@ -31,13 +76,16 @@ pub fn heuristic_fallback(prompt: &str, context: &str) -> RouteDecision {
|| combined.contains("philosophy")
|| combined.contains("essay")
{
- return RouteDecision {
- selected_model: "claude".into(),
- confidence: 0.88,
- provider_endpoint: None,
- is_fallback: true,
- reasoning: "Architectural reasoning keywords detected in prompt".into(),
- };
+ if is_available("claude") {
+ return RouteDecision {
+ selected_model: "claude".into(),
+ effort_level: effort_level.clone(),
+ confidence: 0.88,
+ provider_endpoint: None,
+ is_fallback: true,
+ reasoning: format!("Architectural reasoning keywords detected; effort={}", effort_level),
+ };
+ }
}
// 3. Direct coding / script / regex check
@@ -51,21 +99,37 @@ pub fn heuristic_fallback(prompt: &str, context: &str) -> RouteDecision {
|| combined.contains("algorithm")
|| combined.contains("function")
{
- return RouteDecision {
- selected_model: "codex".into(),
- confidence: 0.82,
- provider_endpoint: None,
- is_fallback: true,
- reasoning: "Programming keywords detected in prompt".into(),
- };
+ if is_available("codex") {
+ return RouteDecision {
+ selected_model: "codex".into(),
+ effort_level: effort_level.clone(),
+ confidence: 0.82,
+ provider_endpoint: None,
+ is_fallback: true,
+ reasoning: format!("Programming keywords detected; effort={}", effort_level),
+ };
+ }
}
- // 4. Default: grok for speed, witty tone, and general queries
+ // 4. Default fast & general
+ let selected = if is_available("grok") {
+ "grok"
+ } else if is_available("claude") {
+ "claude"
+ } else if is_available("codex") {
+ "codex"
+ } else if !available_models.is_empty() {
+ &available_models[0]
+ } else {
+ "grok"
+ };
+
RouteDecision {
- selected_model: "grok".into(),
+ selected_model: selected.into(),
+ effort_level: effort_level.clone(),
confidence: 0.75,
provider_endpoint: None,
is_fallback: true,
- reasoning: "Default fast model selected".into(),
+ reasoning: format!("Optimal available model '{}' selected with effort={}", selected, effort_level),
}
}
diff --git a/src/router/laya.rs b/src/router/laya.rs
index d6d424ca..747474d2 100644
--- a/src/router/laya.rs
+++ b/src/router/laya.rs
@@ -1,4 +1,4 @@
-use super::{fallback::heuristic_fallback, RouteDecision, RouterError};
+use super::{RouteDecision, RouterError};
use reqwest::Client;
use serde_json::json;
use std::time::Duration;
@@ -22,6 +22,34 @@ impl LayaRouter {
/// Routes a prompt to the optimal model using Laya (/v1/systemone),
/// falling back gracefully to local heuristics if Laya is unreachable.
pub async fn route_prompt(&self, prompt: &str, context: &str) -> Result<RouteDecision, RouterError> {
+ self.route_prompt_with_models(prompt, context, &[]).await
+ }
+
+ /// Routes a prompt dynamically choosing from the detected available models and determining needed effort.
+ pub async fn route_prompt_with_models(
+ &self,
+ prompt: &str,
+ context: &str,
+ available: &[crate::drivers::ModelDescriptor],
+ ) -> Result<RouteDecision, RouterError> {
+ let mut criteria = serde_json::Map::new();
+ let candidate_models: Vec<String> = if available.is_empty() {
+ vec!["grok".into(), "claude".into(), "codex".into(), "local_ollama".into()]
+ } else {
+ available.iter().map(|m| m.id.clone()).collect()
+ };
+
+ if available.is_empty() {
+ criteria.insert("grok".into(), serde_json::json!("fast technical reasoning, witty banter, quick coding solutions"));
+ criteria.insert("claude".into(), serde_json::json!("deep architecture, multi-file refactoring, long complex analysis"));
+ criteria.insert("codex".into(), serde_json::json!("direct code generation, standard algorithms, regex, JSON transforms"));
+ criteria.insert("local_ollama".into(), serde_json::json!("private data, offline tasks, zero API cost"));
+ } else {
+ for m in available {
+ criteria.insert(m.id.clone(), serde_json::Value::String(m.capability_desc.clone()));
+ }
+ }
+
let payload = json!({
"state": {
"prompt": prompt,
@@ -30,12 +58,16 @@ impl LayaRouter {
"questions": {
"model_selection": {
"type": "choice",
- "instructions": "Which model is best suited for this task?",
+ "instructions": "Which available model is best suited for this task?",
+ "criteria": criteria
+ },
+ "effort_level": {
+ "type": "choice",
+ "instructions": "What reasoning effort / compute depth is needed for this task?",
"criteria": {
- "grok": "fast technical reasoning, witty banter, quick coding solutions",
- "claude": "deep architecture, multi-file refactoring, long complex analysis",
- "codex": "direct code generation, standard algorithms, regex, JSON transforms",
- "local_ollama": "private data, offline tasks, zero API cost"
+ "low": "quick answers, greetings, short definitions, simple edits",
+ "medium": "standard coding, explanations, moderate feature implementation",
+ "high": "deep architecture, difficult bug root cause analysis, complex refactoring"
}
}
}
@@ -51,21 +83,21 @@ impl LayaRouter {
return Ok(decision);
}
tracing::warn!("Laya response missing expected fields, using fallback");
- Ok(heuristic_fallback(prompt, context))
+ Ok(crate::router::fallback::heuristic_fallback_with_models(prompt, context, &candidate_models))
}
Err(e) => {
tracing::warn!(error = %e, "Failed to parse Laya response body, using fallback");
- Ok(heuristic_fallback(prompt, context))
+ Ok(crate::router::fallback::heuristic_fallback_with_models(prompt, context, &candidate_models))
}
}
}
Ok(resp) => {
tracing::warn!(status = %resp.status(), "Laya service returned error, using fallback");
- Ok(heuristic_fallback(prompt, context))
+ Ok(crate::router::fallback::heuristic_fallback_with_models(prompt, context, &candidate_models))
}
Err(e) => {
tracing::debug!(error = %e, "Laya service unreachable, using fallback");
- Ok(heuristic_fallback(prompt, context))
+ Ok(crate::router::fallback::heuristic_fallback_with_models(prompt, context, &candidate_models))
}
}
}
diff --git a/src/router/mod.rs b/src/router/mod.rs
index ac043e49..3affb532 100644
--- a/src/router/mod.rs
+++ b/src/router/mod.rs
@@ -18,6 +18,7 @@ pub enum RouterError {
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RouteDecision {
pub selected_model: String,
+ pub effort_level: String, // "low", "medium", "high"
pub confidence: f32,
pub provider_endpoint: Option<String>,
pub is_fallback: bool,
@@ -35,6 +36,13 @@ pub fn parse_laya_response(data: &serde_json::Value) -> Option<RouteDecision> {
.map(|f| f as f32)
.unwrap_or(0.9);
+ let effort_level = answers
+ .get("effort_level")
+ .and_then(|e| e.get("choice"))
+ .and_then(|c| c.as_str())
+ .unwrap_or("medium")
+ .to_string();
+
let provider_endpoint = if choice == "local_ollama" {
Some("http://localhost:11434/v1".to_string())
} else {
@@ -43,9 +51,10 @@ pub fn parse_laya_response(data: &serde_json::Value) -> Option<RouteDecision> {
Some(RouteDecision {
selected_model: choice.to_string(),
+ effort_level: effort_level.clone(),
confidence,
provider_endpoint,
is_fallback: false,
- reasoning: format!("Laya decision router selected {}", choice),
+ reasoning: format!("Laya decision router selected {} with {} effort", choice, effort_level),
})
}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 4ea548b9..7ec02373 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -57,6 +57,7 @@ pub fn create_router(state: AppState) -> Router {
.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/settings", get(routes::get_settings).post(routes::save_settings))
.route("/api/events", get(sse::sse_handler))
.fallback(crate::embedded::static_handler)
.layer(cors)
diff --git a/src/server/routes.rs b/src/server/routes.rs
index c897e633..3ed1cf0c 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1,7 +1,7 @@
use super::AppState;
use crate::broker::ApprovalDecision;
use crate::db::models::*;
-use crate::drivers::{create_driver_for_kwant, TurnInput};
+use crate::drivers::{find_cli_binary, resolve_driver_for_model, RuntimeEvent, TurnInput};
use axum::{
extract::{Path, State},
http::StatusCode,
@@ -132,17 +132,25 @@ pub async fn send_chat(
.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
- };
+ // 3. Automatically detect available models and route via Laya
+ let available_models = crate::drivers::detect_available_models(&state.db).await;
+ let route = state
+ .router
+ .route_prompt_with_models(&payload.prompt, "chat", &available_models)
+ .await
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
+
+ let target_model = route.selected_model;
+ let effort_level = route.effort_level;
+
+ // Broadcast Laya routing & effort decision to SSE
+ let _ = state.event_sender.send(RuntimeEvent::ThinkingDelta(format!(
+ "🔮 Laya Router: model='{}', effort='{}' ({:.0}% conf) — {}",
+ target_model,
+ effort_level,
+ route.confidence * 100.0,
+ route.reasoning
+ )));
// 4. Load recent conversation history
let context_id = payload
@@ -157,13 +165,30 @@ pub async fn send_chat(
.unwrap_or_default();
// 5. Build turn input and driver
- let driver = create_driver_for_kwant(&target_kwant);
+ let configured_key = if target_model.contains("claude") {
+ state.db.get_setting("anthropic_api_key").await.ok().flatten()
+ } else if target_model.contains("grok") {
+ state.db.get_setting("xai_api_key").await.ok().flatten()
+ } else if target_model.contains("openai") || target_model.contains("codex") || target_model.contains("gpt") {
+ state.db.get_setting("openai_api_key").await.ok().flatten()
+ } else {
+ None
+ };
+
+ let endpoint = if target_model == "local_ollama" {
+ state.db.get_setting("ollama_url").await.ok().flatten()
+ } else {
+ None
+ };
+
+ let driver = resolve_driver_for_model(&target_model, configured_key, endpoint);
let turn_input = TurnInput {
thread_id: context_id.to_string(),
kwant: target_kwant.clone(),
prompt: payload.prompt.clone(),
history,
- model_override,
+ model_override: Some(target_model.clone()),
+ effort_level: Some(effort_level),
};
// 6. Spawn driver execution in background, feeding events into the SSE event_sender
@@ -191,7 +216,7 @@ pub async fn send_chat(
channel_id,
direct_kwant_id: kwant_id,
sender_role: "kwant".into(),
- sender_id: target_kwant_clone.id,
+ sender_id: target_kwant_clone.name,
text: output.text,
reasoning_content: output.reasoning,
tool_calls: None,
@@ -239,3 +264,78 @@ pub async fn resolve_approval(
"status": status_str
})))
}
+
+#[derive(Serialize)]
+pub struct SettingsResponse {
+ pub anthropic_api_key: String,
+ pub xai_api_key: String,
+ pub openai_api_key: String,
+ pub ollama_url: String,
+ pub claude_cli_found: bool,
+ pub claude_cli_path: Option<String>,
+ pub grok_cli_found: bool,
+ pub grok_cli_path: Option<String>,
+ pub codex_cli_found: bool,
+ pub codex_cli_path: Option<String>,
+}
+
+#[derive(Deserialize)]
+pub struct SaveSettingsPayload {
+ pub anthropic_api_key: Option<String>,
+ pub xai_api_key: Option<String>,
+ pub openai_api_key: Option<String>,
+ pub ollama_url: Option<String>,
+}
+
+pub async fn get_settings(State(state): State<AppState>) -> Result<Json<SettingsResponse>, StatusCode> {
+ let anthropic = state.db.get_setting("anthropic_api_key").await.unwrap_or(None).unwrap_or_default();
+ let xai = state.db.get_setting("xai_api_key").await.unwrap_or(None).unwrap_or_default();
+ let openai = state.db.get_setting("openai_api_key").await.unwrap_or(None).unwrap_or_default();
+ let ollama = state.db.get_setting("ollama_url").await.unwrap_or(None).unwrap_or_else(|| "http://localhost:11434/v1".to_string());
+
+ let claude_bin = find_cli_binary("claude");
+ let grok_bin = find_cli_binary("grok");
+ let codex_bin = find_cli_binary("codex");
+
+ Ok(Json(SettingsResponse {
+ anthropic_api_key: if anthropic.is_empty() { String::new() } else { "••••••••".into() },
+ xai_api_key: if xai.is_empty() { String::new() } else { "••••••••".into() },
+ openai_api_key: if openai.is_empty() { String::new() } else { "••••••••".into() },
+ ollama_url: ollama,
+ claude_cli_found: claude_bin.is_some(),
+ claude_cli_path: claude_bin,
+ grok_cli_found: grok_bin.is_some(),
+ grok_cli_path: grok_bin,
+ codex_cli_found: codex_bin.is_some(),
+ codex_cli_path: codex_bin,
+ }))
+}
+
+pub async fn save_settings(
+ State(state): State<AppState>,
+ Json(payload): Json<SaveSettingsPayload>,
+) -> Result<Json<serde_json::Value>, StatusCode> {
+ if let Some(key) = payload.anthropic_api_key {
+ if !key.starts_with('•') && !key.is_empty() {
+ let _ = state.db.set_setting("anthropic_api_key", &key).await;
+ }
+ }
+ if let Some(key) = payload.xai_api_key {
+ if !key.starts_with('•') && !key.is_empty() {
+ let _ = state.db.set_setting("xai_api_key", &key).await;
+ }
+ }
+ if let Some(key) = payload.openai_api_key {
+ if !key.starts_with('•') && !key.is_empty() {
+ let _ = state.db.set_setting("openai_api_key", &key).await;
+ }
+ }
+ if let Some(url) = payload.ollama_url {
+ if !url.is_empty() {
+ let _ = state.db.set_setting("ollama_url", &url).await;
+ }
+ }
+
+ Ok(Json(json!({ "status": "saved" })))
+}
+
diff --git a/src/tools/web.rs b/src/tools/web.rs
index dbb83b42..93332b40 100644
--- a/src/tools/web.rs
+++ b/src/tools/web.rs
@@ -15,7 +15,7 @@ pub async fn web_fetch(args: &Value) -> Result<Value, ToolError> {
let resp = client
.get(url)
- .header("User-Agent", "KwantsBot/1.0 (8-bit-Agent-Platform)")
+ .header("User-Agent", "KwantsBot/1.0 (Multi-Agent-Platform)")
.send()
.await
.map_err(|e| ToolError::Execution(format!("Web request failed: {}", e)))?;
diff --git a/tests/driver_test.rs b/tests/driver_test.rs
index f80faac0..9682127d 100644
--- a/tests/driver_test.rs
+++ b/tests/driver_test.rs
@@ -82,6 +82,7 @@ async fn test_mock_driver_streaming() {
prompt: "Cast fireball".into(),
history: vec![],
model_override: None,
+ effort_level: None,
};
let handle = tokio::spawn(async move {
diff --git a/tests/router_test.rs b/tests/router_test.rs
index 74e96673..3d372bbc 100644
--- a/tests/router_test.rs
+++ b/tests/router_test.rs
@@ -14,6 +14,7 @@ async fn test_offline_fallback_routing() {
assert!(!decision.selected_model.is_empty());
// For coding, fallback routes to codex or grok
assert!(decision.selected_model == "codex" || decision.selected_model == "grok");
+ assert!(!decision.effort_level.is_empty());
}
#[tokio::test]
@@ -25,6 +26,13 @@ async fn test_fallback_heuristic_variety() {
.await
.unwrap();
assert_eq!(arch_decision.selected_model, "claude");
+ assert_eq!(arch_decision.effort_level, "high");
+
+ let low_decision = router
+ .route_prompt("hi there", "greeting")
+ .await
+ .unwrap();
+ assert_eq!(low_decision.effort_level, "low");
let privacy_decision = router
.route_prompt("Run private local query without sending to cloud, confidential data", "internal")
@@ -33,6 +41,33 @@ async fn test_fallback_heuristic_variety() {
assert_eq!(privacy_decision.selected_model, "local_ollama");
}
+#[tokio::test]
+async fn test_route_prompt_constrained_by_available_models() {
+ let router = LayaRouter::new("http://127.0.0.1:59999".into());
+
+ // Host only has grok available
+ let available = vec![kwnt::drivers::ModelDescriptor {
+ id: "grok".into(),
+ display_name: "xAI Grok".into(),
+ capability_desc: "fast technical reasoning".into(),
+ is_cli: true,
+ }];
+
+ // Prompt contains architecture keywords, but Claude is NOT available
+ let decision = router
+ .route_prompt_with_models(
+ "Analyze multi-region architecture tradeoffs",
+ "architecture",
+ &available,
+ )
+ .await
+ .unwrap();
+
+ // Must gracefully fall back to the available Grok model
+ assert_eq!(decision.selected_model, "grok");
+ assert_eq!(decision.effort_level, "high");
+}
+
#[test]
fn test_parse_laya_success_response() {
let mock_json = json!({
@@ -40,6 +75,9 @@ fn test_parse_laya_success_response() {
"model_selection": {
"choice": "grok",
"confidence": 0.94
+ },
+ "effort_level": {
+ "choice": "high"
}
},
"routing": {
@@ -49,6 +87,7 @@ fn test_parse_laya_success_response() {
let decision = parse_laya_response(&mock_json).unwrap();
assert_eq!(decision.selected_model, "grok");
+ assert_eq!(decision.effort_level, "high");
assert_eq!(decision.confidence, 0.94);
assert!(!decision.is_fallback);
}