Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
feat: LLM profiles with failover, API token lockdown, Anthropic API auth fix
Lin (kwant bot)0021141a161f
diff --git a/README.md b/README.mdindex 3bb83456..a8dfb523 100644--- a/README.md+++ b/README.md@@ -53,6 +53,8 @@ scp target/release/kwnt user@your-vps-ip:/usr/local/bin/kwntssh user@your-vps-ip "kwnt serve --host 0.0.0.0 --port 8799"```+Requests from other machines need the API token: run `kwnt token` on the VPS and open `http://your-vps-ip:8799/#kwnt_token=<token>` once. Through `ssh -L 8799:127.0.0.1:8799` no token is needed. See [LLM profiles and API access](docs/llm-profiles.md).+### Systemd Service (`/etc/systemd/system/kwnt.service`)```ini[Unit]@@ -112,6 +114,7 @@ kwnt only starts Laya for loopback URLs. If Laya already answers, for example fr```bashdocker compose up -d --build # UI on http://127.0.0.1:8799+docker compose exec kwnt kwnt token # open http://127.0.0.1:8799/#kwnt_token=<token> once```The `laya` image (`docker/laya.Dockerfile`) uses CPU PyTorch and preloads the checkpoints listed in the `LAYA_MODELS` build arg. kwnt runs with `KWNT_LAYA_MANAGED=0` and `LAYA_URL=http://laya:8000`; data persists in the `kwnt-data` volume. Put a TLS reverse proxy in front as described in [browser service and VPS hosting](docs/browser-service.md).diff --git a/docs/llm-profiles.md b/docs/llm-profiles.mdnew file mode 100644index 00000000..35ee8f8f--- /dev/null+++ b/docs/llm-profiles.md@@ -0,0 +1,127 @@+# LLM profiles and API access++## Profiles++A profile is one account for an engine (`claude`, `codex` or `grok`), for example a work Claude+subscription and a personal one. Every engine starts with a **system** profile, "This machine",+which runs exactly as kwnt did before profiles: the CLI's own login, or the key from Settings or+the environment. Existing setups keep working without any change.++| Kind | Runs with | Signed in by |+|---|---|---|+| `system` | the CLI's default config dir, Settings/env key | whatever you did on the host |+| `cli_home` | its own config dir (`CLAUDE_CONFIG_DIR`, `CODEX_HOME` or `GROK_HOME`); host credential env vars are removed | the in-app sign-in, or your own dir |+| `api_key` | the provider API with the profile's key only (never a host env key) | the key you paste |++A `cli_home` profile without `home_dir` gets a kwnt-managed dir, `<data_dir>/profiles/<id>`+(mode 0700). A chosen `home_dir` must be an existing, absolute, non-symlinked directory owned by+kwnt's user, and must not be `/`, `$HOME`, the engine's default dir or another profile's dir.+Deleting a profile never deletes its dir.++**Sign-in.** `POST /api/profiles/:id/login` runs the CLI's own login with the profile's home:+`claude auth login --claudeai` (open the link, then paste the code shown back into kwnt),+`codex login --device-auth` and `grok login --device-auth` (open the link and enter the code).+Only links to the providers' sign-in hosts are passed on, one sign-in runs per home at a time and+it expires after 10 minutes.++**Which profile a turn uses.** A kwant may be pinned to a profile (`profile_id`); otherwise the+engine's default profile runs. When that profile is out of usage or signed out, and nothing has+been shown or done yet in the turn, the turn moves to the engine's next enabled profile by+priority (at most 3 attempts), the chat shows a notice and a `profile_switched` event is sent.+Set `profile_failover: false` on a kwant to stay on its profile and get an explanation instead.+A profile that ran out of usage is skipped until its reset time (or one hour when the provider+didn't say). Overloads and rate limits are retried, not failed over.++Keys are write-only: no API response contains one, only `has_key`. Provider error text is kept+only as a class (`quota`, `auth`).++## API access (token)++Browsers may call `/api` only from kwnt's own page: requests with an `Origin` other than+`http://127.0.0.1|localhost|[::1]` on kwnt's port or 5199 (Vite), the page's own host, or an entry+in `KWNT_ALLOWED_ORIGINS` (comma separated) get `403`.++Requests that don't come from this machine need the API token. "This machine" means a loopback+peer, a loopback `Host` and no proxy headers (`X-Forwarded-*`, `Forwarded`, `X-Real-IP`). So:++- `kwnt serve` on your laptop, or a VPS reached through `ssh -L`: nothing changes.+- A VPS reached directly or through a reverse proxy, and Docker (the published port arrives from+ the bridge network): the token is needed.++Get the token with `kwnt token` (Docker: `docker compose exec kwnt kwnt token`). It lives in+`<data_dir>/api-token` (mode 0600), or set `KWNT_API_TOKEN` (16+ characters). Open+`http://<host>:<port>/#kwnt_token=<token>` once: the UI posts it to `/api/auth/session`, which sets an+HttpOnly, SameSite=Strict cookie for a year, and clears the address bar. Scripts can send+`Authorization: Bearer <token>` instead.++`KWNT_REQUIRE_TOKEN=always` requires the token for local requests too; `never` turns the check+off (only behind your own authentication). Always open: `/api/health`, `/api/auth/*`, the MCP+OAuth callback and the MCP endpoints, which carry their own per-turn tokens.++## API reference++Errors are `{"error": "<message>"}`. Bodies with unknown fields are refused.++### Auth++- `GET /api/auth/status` → `{"auth_required": bool, "authenticated": bool}`+- `POST /api/auth/session` `{"token": "..."}` → `204` + `Set-Cookie: kwnt_token=...`; `401` when wrong+- `DELETE /api/auth/session` → `204`, clears the cookie++### Profiles++- `GET /api/profiles` → `[Profile]`, by engine, default first, then priority+- `POST /api/profiles` `{"engine", "name", "kind": "cli_home"|"api_key", "home_dir"?, "priority"?, "enabled"?, "is_default"?, "api_key"?}` → `201 Profile`; `409` on a duplicate name or home+- `PATCH /api/profiles/:id` `{"name"?, "priority"?, "enabled"?, "is_default"?}` → `Profile`+- `DELETE /api/profiles/:id` → `204` (not for system profiles; pinned kwants go back to the default)+- `PUT /api/profiles/:id/key` `{"api_key"}` → `204` (api_key profiles)+- `DELETE /api/profiles/:id/key` → `204`+- `POST /api/profiles/:id/login` → `Login` (cli_home profiles; returns the running one if any)+- `GET /api/profiles/:id/login/:flow_id` → `Login`+- `POST /api/profiles/:id/login/:flow_id/code` `{"code"}` → `Login` (Claude)+- `DELETE /api/profiles/:id/login/:flow_id` → `204`+- `POST /api/profiles/:id/logout` → `204`++```jsonc+// Profile+{+ "id": "prf_…" | "prf_system_claude",+ "engine": "claude" | "codex" | "grok",+ "name": "Work",+ "kind": "system" | "cli_home" | "api_key",+ "enabled": true,+ "is_default": false,+ "priority": 100,+ "home_dir": "/home/me/.kwnt/profiles/prf_…" | null,+ "has_key": false,+ "signed_in": true | false | null, // null: couldn't tell (CLI missing)+ "account_label": "[email protected]" | "API key" | null,+ "limited_until": "2026-10-16T17:00:00Z" | null,+ "last_error": "quota" | "auth" | null+}+// Login+{+ "flow_id": "login_…",+ "profile_id": "prf_…",+ "status": "starting" | "waiting" | "succeeded" | "failed" | "expired" | "cancelled",+ "url": "https://claude.ai/oauth/authorize?…" | null,+ "user_code": "ABCD-1234" | null,+ "needs_code": true, // Claude: paste the code from the page+ "error": null,+ "expires_at": "2026-10-16T12:10:00Z"+}+```++### Kwants++`GET /api/kwants`, `POST /api/kwants` and `PUT /api/kwants/:id` return kwants with two more+fields, and the writes accept them: `"profile_id": "prf_…" | null` (null: engine default; omit to+leave unchanged) and `"profile_failover": bool`. A profile for another engine than the kwant's+model gets `400`.++### Events (`/api/events`)++- `turn_started` `{"kwant_id", "context_id"}`: the kwant is working+- `turn_ended` `{"kwant_id", "context_id", "outcome": "completed"|"failed"|"cancelled"}`: always follows `turn_started`+- `profile_switched` `{"kwant_id", "from_profile_id", "from_name", "to_profile_id", "to_name", "class": "quota"|"auth", "retry_at"?}`+- `TurnComplete` gains `"kwant_id"` and `"profile_id"`; `Error` gains `"kwant_id"`diff --git a/src/db/mod.rs b/src/db/mod.rsindex dcc9411b..b31d2333 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -1,4 +1,5 @@pub mod models;+pub mod profiles;use models::*;use sqlx::{sqlite::SqlitePoolOptions, Pool, Sqlite};@@ -78,6 +79,7 @@ impl Database {let _ = sqlx::query("ALTER TABLE kwants ADD COLUMN soul TEXT NOT NULL DEFAULT '';").execute(&pool).await;let db = Self { pool };+ db.migrate_profiles().await?;db.seed_defaults().await?;Ok(db)diff --git a/src/db/models.rs b/src/db/models.rsindex 440d7f90..0e5eeac3 100644--- a/src/db/models.rs+++ b/src/db/models.rs@@ -276,3 +276,69 @@ impl std::fmt::Debug for McpOAuthToken {.finish()}}++/// A kwant plus its LLM profile binding, as the kwant routes return it.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct KwantView {+ #[serde(flatten)]+ pub kwant: Kwant,+ /// `None` uses the engine's default profile.+ pub profile_id: Option<String>,+ /// Whether a turn may move to the engine's next profile when this one is out of quota or signed out.+ pub profile_failover: bool,+}++/// One LLM account for an engine. Holds no secret: API keys live in `llm_profile_secrets`.+#[derive(Debug, Clone, Serialize, Deserialize, FromRow, PartialEq)]+pub struct LlmProfile {+ pub id: String,+ /// "claude", "codex" or "grok".+ pub engine: String,+ pub name: String,+ /// "system", "cli_home" or "api_key".+ pub kind: String,+ /// The CLI config dir of a `cli_home` profile.+ pub home_dir: Option<String>,+ pub priority: i64,+ pub enabled: bool,+ pub is_default: bool,+ pub created_at: Option<DateTime<Utc>>,+}++#[derive(Debug, Clone)]+pub struct NewLlmProfile {+ pub engine: String,+ pub name: String,+ pub kind: String,+ pub home_dir: Option<String>,+ pub priority: i64,+ pub enabled: bool,+ pub is_default: bool,+}++#[derive(Debug, Clone, Default)]+pub struct LlmProfilePatch {+ pub name: Option<String>,+ pub priority: Option<i64>,+ pub enabled: Option<bool>,+ /// Only `Some(true)` does anything: a profile stops being the default when another becomes it.+ pub is_default: Option<bool>,+}++/// Failover state of a profile. `last_error` is a class ("quota", "auth"), never provider text.+#[derive(Debug, Clone, Default, FromRow, PartialEq)]+pub struct LlmProfileState {+ pub profile_id: String,+ pub limited_until: Option<DateTime<Utc>>,+ pub last_error: Option<String>,+}++/// A stored provider API key. Never prints its value.+#[derive(Clone)]+pub struct ProfileKey(pub String);++impl std::fmt::Debug for ProfileKey {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str("ProfileKey(<redacted>)")+ }+}diff --git a/src/db/profiles.rs b/src/db/profiles.rsnew file mode 100644index 00000000..1970a383--- /dev/null+++ b/src/db/profiles.rs@@ -0,0 +1,307 @@+//! LLM profiles: several accounts per engine, which kwants are bound to and fail over between.++use super::models::*;+use super::{Database, DbError};+use chrono::{DateTime, Utc};+use std::collections::{HashMap, HashSet};+use uuid::Uuid;++/// Engines that have profiles.+pub const PROFILE_ENGINES: [&str; 3] = ["claude", "codex", "grok"];++/// Id of an engine's built-in profile: the CLI's own login or the Settings key, as before profiles.+pub fn system_profile_id(engine: &str) -> String {+ format!("prf_system_{engine}")+}++const PROFILE_COLUMNS: &str =+ "id, engine, name, kind, home_dir, priority, enabled, is_default, created_at";++impl Database {+ /// Adds the kwant binding columns and one system profile per engine. Existing setups end up+ /// with every kwant on its engine's system profile, which runs exactly as kwnt did before.+ pub(super) async fn migrate_profiles(&self) -> Result<(), DbError> {+ let _ = sqlx::query("ALTER TABLE kwants ADD COLUMN profile_id TEXT;")+ .execute(&self.pool)+ .await;+ let _ = sqlx::query(+ "ALTER TABLE kwants ADD COLUMN profile_failover INTEGER NOT NULL DEFAULT 1;",+ )+ .execute(&self.pool)+ .await;+ for engine in PROFILE_ENGINES {+ sqlx::query(+ "INSERT OR IGNORE INTO llm_profiles (id, engine, name, kind, home_dir, priority, enabled, is_default)+ VALUES (?, ?, 'This machine', 'system', NULL, 0, 1,+ NOT EXISTS (SELECT 1 FROM llm_profiles WHERE engine = ? AND is_default = 1))",+ )+ .bind(system_profile_id(engine))+ .bind(engine)+ .bind(engine)+ .execute(&self.pool)+ .await?;+ }+ Ok(())+ }++ /// All profiles, an engine's default first and then by priority.+ pub async fn list_profiles(&self) -> Result<Vec<LlmProfile>, DbError> {+ let rows = sqlx::query_as::<_, LlmProfile>(&format!(+ "SELECT {PROFILE_COLUMNS} FROM llm_profiles ORDER BY engine, is_default DESC, priority, created_at, id"+ ))+ .fetch_all(&self.pool)+ .await?;+ Ok(rows)+ }++ pub async fn get_profile(&self, id: &str) -> Result<Option<LlmProfile>, DbError> {+ let row = sqlx::query_as::<_, LlmProfile>(&format!(+ "SELECT {PROFILE_COLUMNS} FROM llm_profiles WHERE id = ?"+ ))+ .bind(id)+ .fetch_optional(&self.pool)+ .await?;+ Ok(row)+ }++ /// Fails with a unique-constraint error on a duplicate name or home dir.+ pub async fn create_profile(&self, input: &NewLlmProfile) -> Result<LlmProfile, DbError> {+ let id = format!("prf_{}", Uuid::new_v4().simple());+ let mut tx = self.pool.begin().await?;+ if input.is_default {+ sqlx::query("UPDATE llm_profiles SET is_default = 0 WHERE engine = ?")+ .bind(&input.engine)+ .execute(&mut *tx)+ .await?;+ }+ sqlx::query(+ "INSERT INTO llm_profiles (id, engine, name, kind, home_dir, priority, enabled, is_default)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)",+ )+ .bind(&id)+ .bind(&input.engine)+ .bind(&input.name)+ .bind(&input.kind)+ .bind(&input.home_dir)+ .bind(input.priority)+ .bind(input.enabled)+ .bind(input.is_default)+ .execute(&mut *tx)+ .await?;+ tx.commit().await?;+ self.get_profile(&id)+ .await?+ .ok_or(DbError::Sqlx(sqlx::Error::RowNotFound))+ }++ pub async fn update_profile(+ &self,+ id: &str,+ patch: &LlmProfilePatch,+ ) -> Result<Option<LlmProfile>, DbError> {+ let Some(existing) = self.get_profile(id).await? else {+ return Ok(None);+ };+ let mut tx = self.pool.begin().await?;+ if patch.is_default == Some(true) && !existing.is_default {+ sqlx::query("UPDATE llm_profiles SET is_default = 0 WHERE engine = ?")+ .bind(&existing.engine)+ .execute(&mut *tx)+ .await?;+ sqlx::query("UPDATE llm_profiles SET is_default = 1 WHERE id = ?")+ .bind(id)+ .execute(&mut *tx)+ .await?;+ }+ sqlx::query("UPDATE llm_profiles SET name = ?, priority = ?, enabled = ? WHERE id = ?")+ .bind(patch.name.as_ref().unwrap_or(&existing.name))+ .bind(patch.priority.unwrap_or(existing.priority))+ .bind(patch.enabled.unwrap_or(existing.enabled))+ .bind(id)+ .execute(&mut *tx)+ .await?;+ tx.commit().await?;+ self.get_profile(id).await+ }++ /// Deletes a profile, its key and state. Kwants bound to it go back to the engine default,+ /// and a deleted default hands that role to the system profile. Never touches the home dir.+ pub async fn delete_profile(&self, id: &str) -> Result<bool, DbError> {+ let Some(existing) = self.get_profile(id).await? else {+ return Ok(false);+ };+ let mut tx = self.pool.begin().await?;+ for sql in [+ "DELETE FROM llm_profile_secrets WHERE profile_id = ?",+ "DELETE FROM llm_profile_state WHERE profile_id = ?",+ "UPDATE kwants SET profile_id = NULL WHERE profile_id = ?",+ "DELETE FROM llm_profiles WHERE id = ?",+ ] {+ sqlx::query(sql).bind(id).execute(&mut *tx).await?;+ }+ if existing.is_default {+ sqlx::query("UPDATE llm_profiles SET is_default = 1 WHERE id = ?")+ .bind(system_profile_id(&existing.engine))+ .execute(&mut *tx)+ .await?;+ }+ tx.commit().await?;+ Ok(true)+ }++ pub async fn set_profile_key(&self, id: &str, key: &ProfileKey) -> Result<(), DbError> {+ sqlx::query(+ "INSERT INTO llm_profile_secrets (profile_id, api_key, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)+ ON CONFLICT(profile_id) DO UPDATE SET api_key = excluded.api_key, updated_at = CURRENT_TIMESTAMP",+ )+ .bind(id)+ .bind(&key.0)+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ pub async fn delete_profile_key(&self, id: &str) -> Result<bool, DbError> {+ let res = sqlx::query("DELETE FROM llm_profile_secrets WHERE profile_id = ?")+ .bind(id)+ .execute(&self.pool)+ .await?;+ Ok(res.rows_affected() > 0)+ }++ pub async fn get_profile_key(&self, id: &str) -> Result<Option<ProfileKey>, DbError> {+ let row: Option<(String,)> =+ sqlx::query_as("SELECT api_key FROM llm_profile_secrets WHERE profile_id = ?")+ .bind(id)+ .fetch_optional(&self.pool)+ .await?;+ Ok(row.map(|(k,)| ProfileKey(k)))+ }++ /// Ids of profiles with a stored key, without reading the keys.+ pub async fn profile_ids_with_key(&self) -> Result<HashSet<String>, DbError> {+ let rows: Vec<(String,)> = sqlx::query_as("SELECT profile_id FROM llm_profile_secrets")+ .fetch_all(&self.pool)+ .await?;+ Ok(rows.into_iter().map(|(id,)| id).collect())+ }++ pub async fn list_profile_states(&self) -> Result<HashMap<String, LlmProfileState>, DbError> {+ let rows = sqlx::query_as::<_, LlmProfileState>(+ "SELECT profile_id, limited_until, last_error FROM llm_profile_state",+ )+ .fetch_all(&self.pool)+ .await?;+ Ok(rows+ .into_iter()+ .map(|s| (s.profile_id.clone(), s))+ .collect())+ }++ /// Records why a profile failed. `limited_until` skips it in failover until then.+ pub async fn record_profile_failure(+ &self,+ id: &str,+ class: &str,+ limited_until: Option<DateTime<Utc>>,+ ) -> Result<(), DbError> {+ sqlx::query(+ "INSERT INTO llm_profile_state (profile_id, limited_until, last_error, updated_at)+ VALUES (?, ?, ?, CURRENT_TIMESTAMP)+ ON CONFLICT(profile_id) DO UPDATE SET limited_until = excluded.limited_until,+ last_error = excluded.last_error, updated_at = CURRENT_TIMESTAMP",+ )+ .bind(id)+ .bind(limited_until)+ .bind(class)+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// Forgets a profile's failure after it served a turn, or after a new login or key.+ pub async fn clear_profile_state(&self, id: &str) -> Result<(), DbError> {+ sqlx::query("DELETE FROM llm_profile_state WHERE profile_id = ?")+ .bind(id)+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// A kwant's profile binding: its profile (`None` = engine default) and whether it may fail over.+ pub async fn get_kwant_binding(+ &self,+ kwant_id: &str,+ ) -> Result<Option<(Option<String>, bool)>, DbError> {+ let row: Option<(Option<String>, bool)> =+ sqlx::query_as("SELECT profile_id, profile_failover FROM kwants WHERE id = ?")+ .bind(kwant_id)+ .fetch_optional(&self.pool)+ .await?;+ Ok(row)+ }++ pub async fn list_kwant_bindings(+ &self,+ ) -> Result<HashMap<String, (Option<String>, bool)>, DbError> {+ let rows: Vec<(String, Option<String>, bool)> =+ sqlx::query_as("SELECT id, profile_id, profile_failover FROM kwants")+ .fetch_all(&self.pool)+ .await?;+ Ok(rows.into_iter().map(|(id, p, f)| (id, (p, f))).collect())+ }++ /// `profile_id`: `None` leaves it, `Some(None)` clears it. `failover`: `None` leaves it.+ pub async fn set_kwant_binding(+ &self,+ kwant_id: &str,+ profile_id: Option<Option<&str>>,+ failover: Option<bool>,+ ) -> Result<(), DbError> {+ if let Some(profile_id) = profile_id {+ sqlx::query("UPDATE kwants SET profile_id = ? WHERE id = ?")+ .bind(profile_id)+ .bind(kwant_id)+ .execute(&self.pool)+ .await?;+ }+ if let Some(failover) = failover {+ sqlx::query("UPDATE kwants SET profile_failover = ? WHERE id = ?")+ .bind(failover)+ .bind(kwant_id)+ .execute(&self.pool)+ .await?;+ }+ Ok(())+ }++ pub async fn kwant_views(&self) -> Result<Vec<KwantView>, DbError> {+ let kwants = self.list_kwants().await?;+ let mut bindings = self.list_kwant_bindings().await?;+ Ok(kwants+ .into_iter()+ .map(|kwant| {+ let (profile_id, profile_failover) =+ bindings.remove(&kwant.id).unwrap_or((None, true));+ KwantView {+ kwant,+ profile_id,+ profile_failover,+ }+ })+ .collect())+ }++ pub async fn kwant_view(&self, id: &str) -> Result<Option<KwantView>, DbError> {+ let Some(kwant) = self.get_kwant(id).await? else {+ return Ok(None);+ };+ let (profile_id, profile_failover) =+ self.get_kwant_binding(id).await?.unwrap_or((None, true));+ Ok(Some(KwantView {+ kwant,+ profile_id,+ profile_failover,+ }))+ }+}diff --git a/src/db/schema.sql b/src/db/schema.sqlindex 4fa41b83..077f9047 100644--- a/src/db/schema.sql+++ b/src/db/schema.sql@@ -126,3 +126,37 @@ CREATE TABLE IF NOT EXISTS mcp_oauth_tokens (updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,FOREIGN KEY(server_id) REFERENCES mcp_servers(id) ON DELETE CASCADE);++-- LLM accounts per engine (claude, codex, grok). kind: system = the CLI's own login or the+-- Settings key (how kwnt always worked), cli_home = a separate CLI config dir, api_key = a stored key+CREATE TABLE IF NOT EXISTS llm_profiles (+ id TEXT PRIMARY KEY,+ engine TEXT NOT NULL CHECK (engine IN ('claude', 'codex', 'grok')),+ name TEXT NOT NULL,+ kind TEXT NOT NULL CHECK (kind IN ('system', 'cli_home', 'api_key')),+ home_dir TEXT UNIQUE,+ priority INTEGER NOT NULL DEFAULT 100,+ enabled INTEGER NOT NULL DEFAULT 1,+ is_default INTEGER NOT NULL DEFAULT 0,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ UNIQUE (engine, name COLLATE NOCASE)+);++CREATE UNIQUE INDEX IF NOT EXISTS llm_profiles_one_default ON llm_profiles (engine) WHERE is_default = 1;++-- Write-only API keys. Never serialized, never logged+CREATE TABLE IF NOT EXISTS llm_profile_secrets (+ profile_id TEXT PRIMARY KEY,+ api_key TEXT NOT NULL,+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ FOREIGN KEY(profile_id) REFERENCES llm_profiles(id) ON DELETE CASCADE+);++-- Failover state: a quota-limited profile is skipped until limited_until. last_error is a class, never provider text+CREATE TABLE IF NOT EXISTS llm_profile_state (+ profile_id TEXT PRIMARY KEY,+ limited_until TIMESTAMP,+ last_error TEXT,+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ FOREIGN KEY(profile_id) REFERENCES llm_profiles(id) ON DELETE CASCADE+)diff --git a/src/drivers/api.rs b/src/drivers/api.rsindex 5e8bfe04..153d0d6e 100644--- a/src/drivers/api.rs+++ b/src/drivers/api.rs@@ -22,6 +22,90 @@ async fn api_model_name(target_model: &str, url: &str) -> String {target_model.to_string()}+/// Anthropic Messages API version sent with every request.+pub const ANTHROPIC_VERSION: &str = "2023-06-01";+/// What the bare "claude" routing id runs on the Anthropic API.+pub const DEFAULT_CLAUDE_MODEL: &str = "claude-opus-5-5";++fn is_anthropic(url: &str) -> bool {+ url.ends_with("/v1/messages")+}++/// A failed model call: HTTP status when there was a response, and a short redacted message.+#[derive(Debug, Clone)]+pub struct ApiError {+ pub status: Option<u16>,+ pub message: String,+ /// Seconds from a `retry-after` header.+ pub retry_after: Option<u64>,+}++impl std::fmt::Display for ApiError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self.status {+ Some(s) => write!(f, "API returned {s}: {}", self.message),+ None => write!(f, "{}", self.message),+ }+ }+}++/// The provider's own error message out of an error body (OpenAI and Anthropic shapes), redacted.+fn error_message(body: &str) -> String {+ let parsed = serde_json::from_str::<Value>(body).ok();+ let msg = parsed.as_ref().and_then(|v| {+ let err = &v["error"];+ let kind = err["type"].as_str().or_else(|| err["code"].as_str());+ let text = err["message"].as_str().or_else(|| err.as_str());+ match (kind, text) {+ (Some(k), Some(t)) => Some(format!("{k}: {t}")),+ (None, Some(t)) | (Some(t), None) => Some(t.to_string()),+ _ => None,+ }+ });+ crate::profiles::classify::redact_detail(&msg.unwrap_or_else(|| body.to_string()), 300)+}++/// Turns the OpenAI-style message list into an Anthropic Messages body: system prompts move to+/// the top-level `system`, same-role neighbours are merged and the first message is the user's.+fn anthropic_body(model: &str, messages: &[Value], max_tokens: i64) -> Value {+ let mut system = Vec::new();+ let mut turns: Vec<(String, String)> = Vec::new();+ for m in messages {+ let role = m["role"].as_str().unwrap_or("user");+ let content = m["content"].as_str().unwrap_or_default().to_string();+ if role == "system" {+ system.push(content);+ continue;+ }+ let role = if role == "assistant" {+ "assistant"+ } else {+ "user"+ };+ match turns.last_mut() {+ Some((r, c)) if r == role => {+ c.push_str("\n\n");+ c.push_str(&content);+ }+ _ => turns.push((role.to_string(), content)),+ }+ }+ if turns.first().is_some_and(|(r, _)| r == "assistant") {+ turns.insert(0, ("user".into(), "(conversation so far)".into()));+ }+ let model = if model == "claude" {+ DEFAULT_CLAUDE_MODEL+ } else {+ model+ };+ json!({+ "model": model,+ "max_tokens": max_tokens.max(1),+ "system": system.join("\n\n"),+ "messages": turns.into_iter().map(|(role, content)| json!({"role": role, "content": content})).collect::<Vec<_>>(),+ })+}+struct ChatRequest<'a> {url: &'a str,api_key: Option<&'a str>,@@ -37,6 +121,8 @@ pub struct ApiDriver {client: Client,api_key: Option<String>,endpoint: Option<String>,+ /// Whether a missing key may come from the provider's env var (not for profiles).+ env_keys: bool,}impl ApiDriver {@@ -45,9 +131,28 @@ impl ApiDriver {client: Client::new(),api_key,endpoint,+ env_keys: true,+ }+ }++ /// An `api_key` profile's driver: only ever its own key, never the host's env key.+ pub fn for_profile(api_key: Option<String>) -> Self {+ Self {+ env_keys: false,+ ..Self::new(api_key, None)}}+ fn key_or_env(&self, var: &str) -> Option<String> {+ self.api_key.clone().or_else(|| {+ if self.env_keys {+ std::env::var(var).ok()+ } else {+ None+ }+ })+ }+fn resolve_endpoint_and_key(&self, model: &str) -> (String, Option<String>) {if is_ollama(model) {let root = super::ollama_root(self.endpoint.as_deref());@@ -58,43 +163,93 @@ impl ApiDriver {}if model.contains("claude") {- let key = self- .api_key- .clone()- .or_else(|| std::env::var("ANTHROPIC_API_KEY").ok());+ let key = self.key_or_env("ANTHROPIC_API_KEY");("https://api.anthropic.com/v1/messages".to_string(), key)} else if model.contains("grok") {- let key = self- .api_key- .clone()- .or_else(|| std::env::var("XAI_API_KEY").ok());+ let key = self.key_or_env("XAI_API_KEY");("https://api.x.ai/v1/chat/completions".to_string(), key)} else {- let key = self- .api_key- .clone()- .or_else(|| std::env::var("OPENAI_API_KEY").ok());+ let key = self.key_or_env("OPENAI_API_KEY");("https://api.openai.com/v1/chat/completions".to_string(), key)}}}impl ApiDriver {- async fn post_chat(&self, request: &ChatRequest<'_>, body: &Value) -> Result<Value, String> {- let mut req = self.client.post(request.url).json(body);+ async fn post_chat(&self, request: &ChatRequest<'_>, body: &Value) -> Result<Value, ApiError> {+ let mut req = self+ .client+ .post(request.url)+ .json(body)+ .timeout(Duration::from_secs(300));if let Some(key) = request.api_key {- req = req.header("Authorization", format!("Bearer {}", key));+ req = if is_anthropic(request.url) {+ req.header("x-api-key", key)+ .header("anthropic-version", ANTHROPIC_VERSION)+ } else {+ req.header("Authorization", format!("Bearer {}", key))+ };}- let resp = req.send().await.map_err(|e| format!("connection failed: {e}"))?;- if !resp.status().is_success() {- return Err(format!("API returned {}", resp.status()));+ let resp = req.send().await.map_err(|e| ApiError {+ status: None,+ message: if e.is_timeout() {+ "request timed out".into()+ } else {+ "connection failed".into()+ },+ retry_after: None,+ })?;+ let status = resp.status();+ if !status.is_success() {+ let retry_after = resp+ .headers()+ .get("retry-after")+ .and_then(|v| v.to_str().ok())+ .and_then(|v| v.trim().parse::<u64>().ok());+ let body = resp.text().await.unwrap_or_default();+ return Err(ApiError {+ status: Some(status.as_u16()),+ message: error_message(&body),+ retry_after,+ });+ }+ resp.json::<Value>().await.map_err(|_| ApiError {+ status: None,+ message: "invalid response from the model API".into(),+ retry_after: None,+ })+ }++ /// `post_chat`, retrying overloads, rate limits and timeouts twice before giving up.+ async fn post_with_retry(+ &self,+ request: &ChatRequest<'_>,+ body: &Value,+ ) -> Result<Value, ApiError> {+ let mut attempt = 0;+ loop {+ match self.post_chat(request, body).await {+ Ok(v) => return Ok(v),+ Err(e) => {+ let class = crate::profiles::classify(e.status, &e.message, chrono::Utc::now())+ .map(|c| c.0);+ if attempt >= 2 || class != Some(crate::profiles::FailClass::Transient) {+ return Err(e);+ }+ let wait = e+ .retry_after+ .filter(|s| *s <= 30)+ .unwrap_or(if attempt == 0 { 1 } else { 4 });+ tokio::time::sleep(Duration::from_secs(wait)).await;+ attempt += 1;+ }+ }}- resp.json::<Value>().await.map_err(|e| format!("invalid response: {e}"))}/// Calls the model, running any MCP tool calls it asks for and calling it again with the- /// results, up to `max_calls` model calls. Returns the final text and tokens used, or- /// `None` when the very first call fails (the caller then falls back to the offline reply).+ /// results, up to `max_calls` model calls. Returns the final text and tokens used, or the+ /// error when the very first call fails.async fn chat_loop(&self,request: &ChatRequest<'_>,@@ -102,39 +257,65 @@ impl ApiDriver {session: Option<&McpToolSession>,caller: &Caller,event_tx: &mpsc::Sender<RuntimeEvent>,- ) -> Option<(String, usize)> {+ ) -> Result<(String, usize), ApiError> {let tools = session.map(|s| s.openai_tools()).unwrap_or_default();let max_calls = request.max_calls.max(1);let mut tokens = 0usize;for round in 0..max_calls {- let mut body = json!({- "model": request.model,- "messages": messages,- "stream": false,- "temperature": request.temperature,- "max_tokens": request.max_tokens,- });- if !tools.is_empty() {- body["tools"] = json!(tools);- }- let reply = match self.post_chat(request, &body).await {+ let body = if is_anthropic(request.url) {+ anthropic_body(request.model, &messages, request.max_tokens)+ } else {+ let mut body = json!({+ "model": request.model,+ "messages": messages,+ "stream": false,+ "temperature": request.temperature,+ "max_tokens": request.max_tokens,+ });+ if !tools.is_empty() {+ body["tools"] = json!(tools);+ }+ body+ };+ let reply = match self.post_with_retry(request, &body).await {Ok(v) => v,- Err(e) if round == 0 => {- tracing::warn!(error = %e, "API call failed, using arcade emulation");- return None;+ Err(e) if round == 0 => return Err(e),+ Err(e) => {+ return Ok((+ format!("⚠️ The model request failed after running tools: {e}"),+ tokens,+ ))}- Err(e) => return Some((format!("⚠️ The model request failed after running tools: {e}"), tokens)),};- tokens += reply["usage"]["total_tokens"].as_u64().unwrap_or(45) as usize;+ let usage = &reply["usage"];+ tokens += usage["total_tokens"]+ .as_u64()+ .or_else(|| {+ Some(+ usage["input_tokens"].as_u64()?+ + usage["output_tokens"].as_u64().unwrap_or(0),+ )+ })+ .unwrap_or(45) as usize;let message = &reply["choices"][0]["message"];+ let anthropic_text = reply["content"].as_array().map(|blocks| {+ blocks+ .iter()+ .filter_map(|b| b["text"].as_str())+ .collect::<Vec<_>>()+ .join("")+ });let content = message["content"].as_str()- .or_else(|| reply["content"][0]["text"].as_str())- .map(str::to_string);+ .map(str::to_string)+ .or(anthropic_text);let calls = message["tool_calls"].as_array().filter(|c| !c.is_empty());let (Some(calls), Some(session)) = (calls, session) else {- return Some((content.unwrap_or_else(|| "No response content".into()), tokens));+ return Ok((+ content.unwrap_or_else(|| "No response content".into()),+ tokens,+ ));};if round + 1 == max_calls {let note = format!("(Stopped: reached the limit of {max_calls} model calls for MCP tools this turn.)");@@ -142,7 +323,7 @@ impl ApiDriver {Some(c) => format!("{c}\n\n{note}"),None => note,};- return Some((text, tokens));+ return Ok((text, tokens));}if let Some(c) = content.as_deref().filter(|c| !c.trim().is_empty()) {@@ -182,7 +363,11 @@ impl ApiDriver {messages.push(json!({"role": "tool", "tool_call_id": id, "content": outcome.text}));}}- None+ Err(ApiError {+ status: None,+ message: "no model calls were allowed".into(),+ retry_after: None,+ })}}@@ -200,6 +385,13 @@ impl Driver for ApiDriver {.unwrap_or(&input.kwant.preferred_model);let (url, api_key) = self.resolve_endpoint_and_key(target_model);+ if !self.env_keys && api_key.is_none() {+ return Ok(TurnOutput::refused(crate::profiles::ProviderFailure {+ class: crate::profiles::FailClass::Auth,+ retry_at: None,+ detail: "this profile has no API key".into(),+ }));+ }// If target is a real live API endpoint with API key or local Ollama, call HTTP streamingif api_key.is_some() || is_ollama(target_model) {@@ -226,7 +418,7 @@ impl Driver for ApiDriver {};let model = api_model_name(target_model, &url).await;- // The Anthropic Messages API has a different tool format; it is not given MCP tools+ // The Anthropic Messages API has a different tool format; it is not given MCP tools yetlet mcp = input.mcp.as_ref().filter(|_| !url.ends_with("/v1/messages"));if input.mcp.is_some() && mcp.is_none() {let _ = event_tx@@ -261,18 +453,41 @@ impl Driver for ApiDriver {if let Some(session) = session {session.shutdown().await;}- if let Some((text, tokens)) = outcome {+ let (text, tokens) = match outcome {+ Ok(done) => done,+ Err(e) => {+ let now = chrono::Utc::now();+ match crate::profiles::classify(e.status, &e.message, now) {+ Some((class, retry_at)) if class.fails_over() => {+ tracing::warn!(status = ?e.status, class = class.as_str(), "model API refused the turn");+ return Ok(TurnOutput::refused(crate::profiles::ProviderFailure {+ class,+ retry_at,+ detail: e.message.clone(),+ }));+ }+ _ => {+ tracing::warn!(status = ?e.status, "model API call failed");+ (format!("⚠️ The model request failed: {e}"), 0)+ }+ }+ }+ };+ {let _ = event_tx.send(RuntimeEvent::TextDelta(text.clone())).await;let _ = event_tx.send(RuntimeEvent::TurnComplete {tokens,duration_ms: start.elapsed().as_millis() as u64,+ kwant_id: None,+ profile_id: None,}).await;return Ok(TurnOutput {text,reasoning: Some(format!("Model: {} [Effort: {}]", target_model, effort)),tokens_used: tokens,+ ..Default::default()});}}@@ -305,6 +520,8 @@ impl Driver for ApiDriver {.send(RuntimeEvent::TurnComplete {tokens,duration_ms: duration,+ kwant_id: None,+ profile_id: None,}).await;@@ -312,6 +529,129 @@ impl Driver for ApiDriver {text: response_text,reasoning: Some(format!("Model: {} (Unauthenticated)", target_model)),tokens_used: tokens,+ ..Default::default()})}}++#[cfg(test)]+mod tests {+ use super::*;+ use axum::{extract::State, http::HeaderMap, routing::post, Json, Router};+ use std::sync::{Arc, Mutex};++ type Seen = Arc<Mutex<Vec<(HeaderMap, Value)>>>;++ async fn mock(status: u16, reply: Value) -> (String, Seen) {+ let seen: Seen = Arc::default();+ let app = Router::new()+ .route(+ "/v1/messages",+ post(+ |State((seen, status, reply)): State<(Seen, u16, Value)>,+ headers: HeaderMap,+ Json(body): Json<Value>| async move {+ seen.lock().unwrap().push((headers, body));+ (+ axum::http::StatusCode::from_u16(status).unwrap(),+ Json(reply),+ )+ },+ ),+ )+ .with_state((seen.clone(), status, reply));+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let url = format!("http://{}/v1/messages", listener.local_addr().unwrap());+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ (url, seen)+ }++ fn request<'a>(url: &'a str, key: &'a str) -> ChatRequest<'a> {+ ChatRequest {+ url,+ api_key: Some(key),+ model: "claude",+ temperature: 0.7,+ max_tokens: 100,+ max_calls: 1,+ }+ }++ #[tokio::test]+ async fn anthropic_calls_use_x_api_key_and_version() {+ let reply = json!({"content": [{"type": "text", "text": "Hi"}, {"type": "text", "text": " there"}], "usage": {"input_tokens": 5, "output_tokens": 2}});+ let (url, seen) = mock(200, reply).await;+ let driver = ApiDriver::new(Some("sk-ant-test-key".into()), Some(url.clone()));+ let messages = vec![+ json!({"role": "system", "content": "be brief"}),+ json!({"role": "assistant", "content": "earlier"}),+ json!({"role": "user", "content": "a"}),+ json!({"role": "user", "content": "b"}),+ ];+ let (tx, _rx) = mpsc::channel(8);+ let caller = Caller {+ kwant_id: "k".into(),+ kwant_name: "K".into(),+ turn_id: "t".into(),+ };+ let (text, tokens) = driver+ .chat_loop(+ &request(&url, "sk-ant-test-key"),+ messages,+ None,+ &caller,+ &tx,+ )+ .await+ .unwrap();+ assert_eq!(text, "Hi there");+ assert_eq!(tokens, 7);++ let (headers, body) = seen.lock().unwrap()[0].clone();+ assert_eq!(headers["x-api-key"], "sk-ant-test-key");+ assert_eq!(headers["anthropic-version"], ANTHROPIC_VERSION);+ assert!(headers.get("authorization").is_none());+ assert_eq!(body["model"], DEFAULT_CLAUDE_MODEL);+ assert_eq!(body["system"], "be brief");+ assert!(body.get("temperature").is_none());+ let roles: Vec<&str> = body["messages"]+ .as_array()+ .unwrap()+ .iter()+ .map(|m| m["role"].as_str().unwrap())+ .collect();+ assert_eq!(roles, ["user", "assistant", "user"]);+ assert_eq!(body["messages"][2]["content"], "a\n\nb");+ }++ #[tokio::test]+ async fn quota_errors_are_returned_redacted_without_retry() {+ let err = json!({"type": "error", "error": {"type": "billing_error", "message": "Your credit balance is too low for key sk-ant-api03-abcdefghijklmnop0123456789"}});+ let (url, seen) = mock(400, err).await;+ let driver = ApiDriver::new(Some("k".repeat(20)), Some(url.clone()));+ let e = driver+ .post_with_retry(&request(&url, "kkkkkkkkkkkkkkkkkkkk"), &json!({}))+ .await+ .unwrap_err();+ assert_eq!(e.status, Some(400));+ assert!(e.message.contains("credit balance is too low"), "{e}");+ assert!(!e.message.contains("abcdefghij"), "{e}");+ assert_eq!(seen.lock().unwrap().len(), 1);+ let class = crate::profiles::classify(e.status, &e.message, chrono::Utc::now())+ .unwrap()+ .0;+ assert_eq!(class, crate::profiles::FailClass::Quota);+ }++ #[test]+ fn profile_drivers_never_use_env_keys() {+ std::env::set_var("XAI_API_KEY", "xai-host-key");+ let (_, key) = ApiDriver::for_profile(None).resolve_endpoint_and_key("grok-4");+ assert!(key.is_none());+ let (_, key) =+ ApiDriver::for_profile(Some("xai-profile".into())).resolve_endpoint_and_key("grok-4");+ assert_eq!(key.as_deref(), Some("xai-profile"));+ let (_, key) = ApiDriver::new(None, None).resolve_endpoint_and_key("grok-4");+ assert_eq!(key.as_deref(), Some("xai-host-key"));+ }+}diff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex ce46684f..c003615e 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -135,9 +135,16 @@ pub const CODEX_SHELL_POLICY: [&str; 4] = [/// Names of the MCP servers codex would load for this turn, as codex itself resolves them:/// `$CODEX_HOME`/`~/.codex` config, its active profile, a trusted project's `.codex/config.toml`/// for `cwd`, and system config. The listing holds server env values, so it is never logged.-pub async fn codex_user_mcp_servers(bin: &str, cwd: Option<&Path>) -> Result<Vec<String>, String> {+pub async fn codex_user_mcp_servers(+ bin: &str,+ cwd: Option<&Path>,+ profile_env: Option<&crate::profiles::CliEnv>,+) -> Result<Vec<String>, String> {let mut cmd = Command::new(bin);cmd.args(["mcp", "list", "--json"]);+ if let Some(env) = profile_env {+ env.apply(&mut cmd);+ }if let Some(dir) = cwd.filter(|d| d.exists()) {cmd.current_dir(dir);}@@ -194,6 +201,9 @@ pub struct CliDriver {/// The user's grok home to take model settings and login from; `None` means `$GROK_HOME`/// or `~/.grok`. Only read, never written.pub grok_home: Option<std::path::PathBuf>,+ /// Set when the turn runs on a `cli_home` profile: points the CLI at the profile's home and+ /// removes credential variables that would override its login.+ pub profile_env: Option<crate::profiles::CliEnv>,}impl CliDriver {@@ -204,7 +214,22 @@ impl CliDriver {cli_binary: bin,tool_kind: kind,grok_home: None,+ profile_env: None,+ }+ }++ /// Runs the CLI on a profile's own home (its login and settings) instead of the user's.+ /// grok still runs in a private temp home, taking settings and login from this one only.+ pub fn with_profile_home(+ mut self,+ engine: crate::profiles::Engine,+ home: std::path::PathBuf,+ ) -> Self {+ self.profile_env = Some(crate::profiles::CliEnv::for_home(engine, &home));+ if engine == crate::profiles::Engine::Grok {+ self.grok_home = Some(home);}+ self}pub fn with_grok_home(mut self, dir: std::path::PathBuf) -> Self {@@ -236,6 +261,8 @@ struct GrokLaunch<'a> {auth_file: Option<std::path::PathBuf>,/// This turn's gateway token, handed over in grok's env only.gateway_token: Option<String>,+ /// Credential variables a profile run removes.+ removed_env: Vec<String>,}/// What one grok process left behind.@@ -248,6 +275,8 @@ struct GrokRun {stop_reason: Option<String>,/// `None` if grok was killed by a signal.exit_code: Option<i32>,+ /// grok called at least one tool.+ tool_calls: bool,}/// Reads a pipe to the end, keeping at most the last `max` bytes.@@ -288,6 +317,9 @@ impl CliDriver {for key in super::grok::REMOVED_ENV {cmd.env_remove(key);}+ for key in &launch.removed_env {+ cmd.env_remove(key);+ }match (launch.auth_file.as_deref(), auth) {(Some(file), GrokAuth::InPlace) => {cmd.env("GROK_AUTH_PATH", file);@@ -320,6 +352,7 @@ impl CliDriver {errors: Vec::new(),stop_reason: None,exit_code: None,+ tool_calls: false,};let mut parser = super::grok::StreamParser::default();let mut buffer = [0u8; 4096];@@ -375,6 +408,7 @@ impl CliDriver {}super::grok::StreamEvent::Error(message) => run.errors.push(message),super::grok::StreamEvent::End { stop_reason } => run.stop_reason = stop_reason,+ super::grok::StreamEvent::ToolCall => run.tool_calls = true,}}@@ -392,8 +426,10 @@ impl CliDriver {.map(|text| super::grok::model_settings(&text)).unwrap_or_default();super::grok::restrict_shell_env(&mut config);- let auth_file = std::env::var_os("GROK_AUTH_PATH")- .filter(|p| !p.is_empty())+ // A profile's login is its home's auth.json and nothing else+ let env_auth = std::env::var_os("GROK_AUTH_PATH")+ .filter(|p| !p.is_empty() && self.profile_env.is_none());+ let auth_file = env_auth.map(std::path::PathBuf::from).or_else(|| user_home.map(|h| h.join("auth.json"))).filter(|p| p.is_file());@@ -422,6 +458,11 @@ impl CliDriver {config,auth_file,gateway_token,+ removed_env: self+ .profile_env+ .as_ref()+ .map(|e| e.remove.clone())+ .unwrap_or_default(),};let run = Self::run_grok_once(&launch, GrokAuth::InPlace, event_tx).await?;if launch.auth_file.is_some()@@ -438,6 +479,121 @@ impl CliDriver {}}+/// A provider refusal (quota, auth) in a CLI's error output, if that's what stopped it.+fn refusal(text: &str) -> Option<crate::profiles::ProviderFailure> {+ let (class, retry_at) = crate::profiles::classify(None, text, chrono::Utc::now())?;+ class+ .fails_over()+ .then(|| crate::profiles::ProviderFailure {+ class,+ retry_at,+ detail: crate::profiles::classify::redact_detail(text, 300),+ })+}++/// The error lines of codex's stderr. Its stderr also echoes the prompt, which must not be+/// mistaken for an error message.+fn codex_error_lines(stderr: &str) -> String {+ stderr+ .lines()+ .filter(|l| {+ let t = l.trim_start();+ t.starts_with("ERROR")+ || t.starts_with("Error:")+ || t.contains("unexpected status")+ || t.contains("stream error")+ })+ .collect::<Vec<_>>()+ .join("\n")+}++/// Whether codex's stderr shows it ran a command, edited a file or called a tool.+fn codex_had_effects(stderr: &str) -> bool {+ stderr.lines().any(|l| {+ let t = l.trim();+ t == "exec"+ || t.starts_with("exec ")+ || t.contains("apply_patch")+ || t.starts_with("tool ")+ || t == "file update"+ })+}++/// Says why grok gave no reply, so the chat never shows an empty message.+async fn empty_grok_reply(+ input: &TurnInput,+ run: &GrokRun,+ event_tx: &mpsc::Sender<RuntimeEvent>,+) -> (String, usize) {+ let mut secrets = input+ .mcp+ .as_ref()+ .map(|c| c.secret_values())+ .unwrap_or_default();+ secrets.extend(+ input+ .mcp+ .as_ref()+ .and_then(|c| c.gateway.as_ref())+ .map(|g| g.token.clone()),+ );+ let notice = super::grok::empty_reply_notice(+ &super::grok::EmptyRun {+ stderr: &run.stderr,+ errors: &run.errors,+ stop_reason: run.stop_reason.as_deref(),+ exit_code: run.exit_code,+ },+ &secrets,+ );+ tracing::warn!(exit_code = ?run.exit_code, stop_reason = ?run.stop_reason, "grok gave no reply");+ let msg = format!("⚠️ [{}] {notice}", input.kwant.name);+ let _ = event_tx.send(RuntimeEvent::TextDelta(msg.clone())).await;+ (msg, 0)+}++/// What `claude -p --output-format json` reports.+#[derive(Debug, Default, serde::Deserialize)]+struct ClaudeResult {+ #[serde(default)]+ is_error: bool,+ #[serde(default)]+ num_turns: u64,+ #[serde(default)]+ result: String,+ #[serde(default)]+ usage: Option<serde_json::Value>,+}++impl ClaudeResult {+ /// The result line of claude's JSON output, if it printed one.+ fn parse(stdout: &str) -> Option<Self> {+ stdout+ .lines()+ .rev()+ .find_map(|l| {+ serde_json::from_str::<serde_json::Value>(l.trim())+ .ok()+ .filter(|v| v["type"] == "result")+ })+ .and_then(|v| serde_json::from_value(v).ok())+ }++ fn tokens(&self) -> Option<usize> {+ let u = self.usage.as_ref()?;+ let sum = [+ "input_tokens",+ "output_tokens",+ "cache_creation_input_tokens",+ "cache_read_input_tokens",+ ]+ .iter()+ .filter_map(|k| u[*k].as_u64())+ .sum::<u64>();+ (sum > 0).then_some(sum as usize)+ }+}+#[async_trait]impl Driver for CliDriver {async fn stream_turn(@@ -458,12 +614,15 @@ impl Driver for CliDriver {.send(RuntimeEvent::TurnComplete {tokens: 10,duration_ms: 10,+ kwant_id: None,+ profile_id: None,}).await;return Ok(TurnOutput {text: msg,reasoning: None,tokens_used: 10,+ ..Default::default()});}};@@ -506,7 +665,7 @@ impl Driver for CliDriver {// Fail closed: without the names, the user's own servers would run with no// approval card (and despite a per-kwant opt-out). Same for a user server named// like the gateway, which can't be switched off while the gateway uses its name.- let listed = codex_user_mcp_servers(&bin_path, input.workspace_dir.as_deref()).await.map_err(|e| {+ let listed = codex_user_mcp_servers(&bin_path, input.workspace_dir.as_deref(), self.profile_env.as_ref()).await.map_err(|e| {tracing::warn!(error = %e, "could not list codex's own MCP servers; not running codex");format!("kwnt couldn't check which MCP servers your codex config would start ({e}), so it didn't run codex. Check that `codex mcp list` works."@@ -522,9 +681,19 @@ impl Driver for CliDriver {let msg = format!("⚠️ [{}] {reason}", input.kwant.name);let _ = event_tx.send(RuntimeEvent::TextDelta(msg.clone())).await;let _ = event_tx- .send(RuntimeEvent::TurnComplete { tokens: 0, duration_ms: start.elapsed().as_millis() as u64 })+ .send(RuntimeEvent::TurnComplete {+ tokens: 0,+ duration_ms: start.elapsed().as_millis() as u64,+ kwant_id: None,+ profile_id: None,+ }).await;- return Ok(TurnOutput { text: msg, reasoning: None, tokens_used: 0 });+ return Ok(TurnOutput {+ text: msg,+ reasoning: None,+ tokens_used: 0,+ ..Default::default()+ });}};cmd.arg("exec")@@ -569,33 +738,14 @@ impl Driver for CliDriver {effective_prompt.clone(),];let (text, tokens) = match self.run_grok(&bin_path, &input, args, &event_tx).await {+ Ok(run) if run.stdout.trim().is_empty() && !run.tool_calls => {+ match refusal(&format!("{}\n{}", run.errors.join("\n"), run.stderr)) {+ Some(failure) => return Ok(TurnOutput::refused(failure)),+ None => empty_grok_reply(&input, &run, &event_tx).await,+ }+ }Ok(run) if run.stdout.trim().is_empty() => {- // Never an empty reply: say why grok gave none- let mut secrets = input- .mcp- .as_ref()- .map(|c| c.secret_values())- .unwrap_or_default();- secrets.extend(- input- .mcp- .as_ref()- .and_then(|c| c.gateway.as_ref())- .map(|g| g.token.clone()),- );- let notice = super::grok::empty_reply_notice(- &super::grok::EmptyRun {- stderr: &run.stderr,- errors: &run.errors,- stop_reason: run.stop_reason.as_deref(),- exit_code: run.exit_code,- },- &secrets,- );- tracing::warn!(exit_code = ?run.exit_code, stop_reason = ?run.stop_reason, "grok gave no reply");- let msg = format!("⚠️ [{}] {notice}", input.kwant.name);- let _ = event_tx.send(RuntimeEvent::TextDelta(msg.clone())).await;- (msg, 0)+ empty_grok_reply(&input, &run, &event_tx).await}Ok(run) => {let tokens = run.stdout.len() / 4;@@ -615,6 +765,8 @@ impl Driver for CliDriver {.send(RuntimeEvent::TurnComplete {tokens,duration_ms: start.elapsed().as_millis() as u64,+ kwant_id: None,+ profile_id: None,}).await;return Ok(TurnOutput {@@ -624,6 +776,7 @@ impl Driver for CliDriver {self.tool_kind, bin_path, effort)),tokens_used: tokens,+ ..Default::default()});}_ => {@@ -661,50 +814,91 @@ impl Driver for CliDriver {}}cmd.arg("--append-system-prompt").arg(&system_prompt);+ // One JSON result: tells a usage limit or sign-out apart from a reply+ cmd.arg("--output-format").arg("json");cmd.arg("-p").arg(&effective_prompt);}}+ if let Some(env) = &self.profile_env {+ env.apply(&mut cmd);+ }// codex's reply comes from its -o file; an unread pipe could fill up and stall the CLIcmd.stdin(Stdio::null());- cmd.stdout(if codex_out_file.is_some() { Stdio::null() } else { Stdio::piped() });- cmd.stderr(Stdio::null());+ cmd.stdout(if codex_out_file.is_some() {+ Stdio::null()+ } else {+ Stdio::piped()+ });+ // codex reports a usage limit or sign-out only on stderr+ cmd.stderr(if codex_out_file.is_some() {+ Stdio::piped()+ } else {+ Stdio::null()+ });// A cancelled turn aborts this task; the CLI must not outlive itcmd.kill_on_drop(true);match cmd.spawn() {Ok(mut child) => {- let mut output_str = String::new();- let mut buffer = [0u8; 1024];+ let stdout_pipe = child.stdout.take();+ let stderr_pipe = child.stderr.take();+ let read_stdout = async {+ match stdout_pipe {+ Some(stdout) => read_tail(stdout, 8 * 1024 * 1024).await,+ None => String::new(),+ }+ };+ let read_stderr = async {+ match stderr_pipe {+ Some(stderr) => read_tail(stderr, GROK_STDERR_MAX).await,+ None => String::new(),+ }+ };+ let (stdout, stderr) = tokio::join!(read_stdout, read_stderr);+ let exit = child.wait().await.ok();- if let Some(mut stdout) = child.stdout.take() {- while let Ok(n) = stdout.read(&mut buffer).await {- if n == 0 {- break;+ let mut tokens = None;+ let output_str = if let Some(ref out_file) = codex_out_file {+ let content = tokio::fs::read_to_string(out_file)+ .await+ .unwrap_or_default();+ let _ = tokio::fs::remove_file(out_file).await;+ let failed = !exit.is_some_and(|s| s.success());+ if content.trim().is_empty() && failed && !codex_had_effects(&stderr) {+ if let Some(failure) = refusal(&codex_error_lines(&stderr)) {+ return Ok(TurnOutput::refused(failure));}- 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;+ content+ } else {+ match ClaudeResult::parse(&stdout) {+ Some(result) => {+ if result.is_error && result.num_turns <= 1 {+ if let Some(failure) = refusal(&result.result) {+ return Ok(TurnOutput::refused(failure));+ }+ }+ tokens = result.tokens();+ result.result+ }+ // Not JSON (an older claude): its plain text is the reply+ None => stdout,}- let _ = tokio::fs::remove_file(out_file).await;- let _ = event_tx.send(RuntimeEvent::TextDelta(output_str.clone())).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;+ let tokens = tokens.unwrap_or(output_str.len() / 4);let _ = event_tx.send(RuntimeEvent::TurnComplete {tokens,duration_ms: duration,+ kwant_id: None,+ profile_id: None,}).await;@@ -715,6 +909,7 @@ impl Driver for CliDriver {self.tool_kind, bin_path, effort)),tokens_used: tokens,+ ..Default::default()})}Err(e) => {@@ -728,6 +923,8 @@ impl Driver for CliDriver {.send(RuntimeEvent::TurnComplete {tokens: 15,duration_ms: start.elapsed().as_millis() as u64,+ kwant_id: None,+ profile_id: None,}).await;@@ -735,6 +932,7 @@ impl Driver for CliDriver {text: msg,reasoning: None,tokens_used: 15,+ ..Default::default()})}}diff --git a/src/drivers/events.rs b/src/drivers/events.rsindex 6e8556be..d75ea0a0 100644--- a/src/drivers/events.rs+++ b/src/drivers/events.rs@@ -27,6 +27,38 @@ pub enum RuntimeEvent {TurnComplete {tokens: usize,duration_ms: u64,+ /// Kwant whose turn ended; set on the events the server broadcasts.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ kwant_id: Option<String>,+ /// Profile that served the turn, when the engine has profiles.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ profile_id: Option<String>,+ },+ /// A kwant started working on a turn (its avatar can show it's busy until `turn_ended`).+ #[serde(rename = "turn_started", alias = "TurnStarted")]+ TurnStarted {+ kwant_id: String,+ context_id: Option<String>,+ },+ /// A kwant's turn is over, however it ended: "completed", "failed" or "cancelled".+ #[serde(rename = "turn_ended", alias = "TurnEnded")]+ TurnEnded {+ kwant_id: String,+ context_id: Option<String>,+ outcome: String,+ },+ /// A turn moved to another profile of the same engine because the first ran out of quota+ /// or was signed out. `class` is "quota" or "auth".+ #[serde(rename = "profile_switched", alias = "ProfileSwitched")]+ ProfileSwitched {+ kwant_id: String,+ from_profile_id: String,+ from_name: String,+ to_profile_id: String,+ to_name: String,+ class: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ retry_at: Option<chrono::DateTime<chrono::Utc>>,},#[serde(rename = "discussion_started", alias = "DiscussionStarted")]DiscussionStarted {@@ -95,6 +127,8 @@ pub enum RuntimeEvent {Error {code: String,message: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ kwant_id: Option<String>,},}diff --git a/src/drivers/grok.rs b/src/drivers/grok.rsindex 2d694363..3a978e82 100644--- a/src/drivers/grok.rs+++ b/src/drivers/grok.rs@@ -332,6 +332,8 @@ pub enum StreamEvent {Error(String),/// The run ended; `stop_reason` is e.g. `end_turn`, `refusal`, `cancelled`.End { stop_reason: Option<String> },+ /// grok called a tool: the turn has had effects, so it must not be retried elsewhere.+ ToolCall,}/// Splits grok's NDJSON output into events. Lines that aren't JSON are passed on as text, so@@ -380,6 +382,7 @@ fn parse_line(line: &str) -> Option<StreamEvent> {Some("end") => Some(StreamEvent::End {stop_reason: value["stopReason"].as_str().map(str::to_string),}),+ Some("tool_call") | Some("tool_call_update") => Some(StreamEvent::ToolCall),Some(_) => None,None => Some(StreamEvent::Text(line.to_string())),}@@ -554,6 +557,7 @@ include_only = ["*"][StreamEvent::Text("Hel".into()),StreamEvent::Text("lo\n".into()),+ StreamEvent::ToolCall,StreamEvent::Text("plain line\n".into()),StreamEvent::Error("boom".into()),StreamEvent::End {diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex fca986a8..60e6605c 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -275,11 +275,22 @@ pub async fn detect_available_models(db: &crate::db::Database) -> Vec<ModelDescravailable}-#[derive(Debug, Clone, Serialize, Deserialize)]+#[derive(Debug, Clone, Default, Serialize, Deserialize)]pub struct TurnOutput {pub text: String,pub reasoning: Option<String>,pub tokens_used: usize,+ /// Set when the provider refused the turn (quota, auth) before the model did anything; the+ /// driver then emitted no text and no `TurnComplete`, so the turn can move to another profile.+ #[serde(skip)]+ pub failure: Option<crate::profiles::ProviderFailure>,+}++impl TurnOutput {+ /// A turn the provider refused before anything visible happened.+ pub fn refused(failure: crate::profiles::ProviderFailure) -> Self {+ Self { failure: Some(failure), ..Default::default() }+ }}#[async_trait]diff --git a/src/lib.rs b/src/lib.rsindex 606829b3..e688792a 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -4,6 +4,7 @@ pub mod db;pub mod drivers;pub mod embedded;pub mod mcp;+pub mod profiles;pub mod router;pub mod sandbox;pub mod server;diff --git a/src/main.rs b/src/main.rsindex 3333002d..ec991608 100644--- a/src/main.rs+++ b/src/main.rs@@ -56,6 +56,9 @@ pub enum Commands {/// List channels stored in the local databaseChannels,+ /// Print the API token that browsers and scripts on other machines need+ Token,+/// Run a tiny MCP test server on stdin/stdout (for tests and smoke checks)#[command(hide = true)]McpEchoServer,@@ -119,6 +122,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {}let db = Database::init(&config.data_dir).await?;+ restrict_data_dir(&config.data_dir);let tools = ToolRunner::new(config.data_dir.join("workspace"));let broker = PermissionBroker::new();let router = LayaRouter::new(config.laya_url.clone());@@ -159,7 +163,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {"⚡ Kwant: your team of super-intelligent bots (kwants), listening at http://{}",addr);+ if !is_loopback_bind(&config.host) {+ println!(+ "🔒 Requests from other machines need the API token: run `kwnt token` and open http://<this-host>:{}/#kwnt_token=<token>",+ config.port+ );+ }+ let app = app.into_make_service_with_connect_info::<std::net::SocketAddr>();tokio::select! {res = axum::serve(listener, app) => res?,_ = shutdown_signal() => println!("Shutting down…"),@@ -171,6 +182,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {Some(Commands::Agents) => print_agents(&config).await?,Some(Commands::Teams) => print_teams(&config).await?,Some(Commands::Channels) => print_channels(&config).await?,+ Some(Commands::Token) => {+ let token = std::env::var("KWNT_API_TOKEN")+ .ok()+ .map(|t| t.trim().to_string())+ .filter(|t| t.len() >= 16)+ .unwrap_or_else(|| kwnt::server::auth::load_or_create(&config.data_dir));+ println!("{token}");+ }Some(Commands::McpEchoServer) => unreachable!("handled before config loading"),Some(Commands::McpOauthMockServer { .. }) => unreachable!("handled before config loading"),None => {@@ -182,6 +201,31 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {Ok(())}+fn is_loopback_bind(host: &str) -> bool {+ host == "localhost"+ || host+ .trim_matches(['[', ']'])+ .parse::<std::net::IpAddr>()+ .is_ok_and(|ip| ip.is_loopback())+}++/// The data dir holds the database (keys, MCP tokens) and profile logins: owner only.+fn restrict_data_dir(dir: &std::path::Path) {+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));+ for name in ["kwnt.db", "kwnt.db-wal", "kwnt.db-shm"] {+ let path = dir.join(name);+ if path.exists() {+ let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));+ }+ }+ }+ #[cfg(not(unix))]+ let _ = dir;+}+fn print_status(config: &Config) {let config_path = config.data_dir.join("config.toml");let db_path = config.data_dir.join("kwnt.db");diff --git a/src/profiles/classify.rs b/src/profiles/classify.rsnew file mode 100644index 00000000..0980fc6d--- /dev/null+++ b/src/profiles/classify.rs@@ -0,0 +1,378 @@+//! Sorts a failed provider call into quota, auth or transient, from its status and error text.++use chrono::{DateTime, Duration, TimeZone, Utc};+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum FailClass {+ /// Usage limit, out of credits or billing: another account may still work.+ Quota,+ /// Signed out, bad or expired key: another account may still work.+ Auth,+ /// Overloaded, rate limited, timeouts: retry the same account, don't fail over.+ Transient,+}++impl FailClass {+ pub fn as_str(self) -> &'static str {+ match self {+ FailClass::Quota => "quota",+ FailClass::Auth => "auth",+ FailClass::Transient => "transient",+ }+ }++ /// Whether moving to another account of the same engine can help.+ pub fn fails_over(self) -> bool {+ matches!(self, FailClass::Quota | FailClass::Auth)+ }+}++/// A provider call that failed before the model did anything visible.+#[derive(Debug, Clone, PartialEq)]+pub struct ProviderFailure {+ pub class: FailClass,+ /// When a quota resets, if the provider said.+ pub retry_at: Option<DateTime<Utc>>,+ /// A short, redacted excerpt of the provider's message, for the chat notice only.+ pub detail: String,+}++/// How long a quota-limited profile is skipped when the provider gave no reset time.+pub const DEFAULT_QUOTA_COOLDOWN_MINS: i64 = 60;++const QUOTA_PATTERNS: &[&str] = &[+ "usage limit",+ "hit your limit",+ "reached your limit",+ "out of credits",+ "insufficient_quota",+ "exceeded your current quota",+ "usage_limit_exceeded",+ "credit balance is too low",+ "billing_error",+ "payment required",+ "quota",+];++const AUTH_PATTERNS: &[&str] = &[+ "not logged in",+ "not signed in",+ "please run /login",+ "please log in",+ "invalid api key",+ "invalid x-api-key",+ "incorrect api key",+ "invalid_api_key",+ "authentication_error",+ "401 unauthorized",+ "missing bearer",+ "oauth token has expired",+ "token has expired",+ "permission_error",+];++const TRANSIENT_PATTERNS: &[&str] = &[+ "overloaded",+ "rate limit",+ "rate_limit",+ "too many requests",+ "timed out",+ "timeout",+ "temporarily unavailable",+ "internal server error",+ "bad gateway",+ "service unavailable",+ "connection reset",+ "connection refused",+];++/// Classifies a failed call. `status` is the HTTP status when there was one. Returns `None` when+/// nothing marks it as a provider failure (then it's an ordinary error and nothing fails over).+pub fn classify(+ status: Option<u16>,+ text: &str,+ now: DateTime<Utc>,+) -> Option<(FailClass, Option<DateTime<Utc>>)> {+ let lower = text.to_lowercase();+ let quota = QUOTA_PATTERNS.iter().any(|p| lower.contains(p)) || status == Some(402);+ if quota {+ return Some((FailClass::Quota, Some(quota_reset(text, &lower, now))));+ }+ if AUTH_PATTERNS.iter().any(|p| lower.contains(p)) || matches!(status, Some(401) | Some(403)) {+ return Some((FailClass::Auth, None));+ }+ let transient_status =+ matches!(status, Some(408) | Some(429) | Some(529)) || status.is_some_and(|s| s >= 500);+ if transient_status || TRANSIENT_PATTERNS.iter().any(|p| lower.contains(p)) {+ return Some((FailClass::Transient, None));+ }+ None+}++/// When a quota resets: Claude's `...limit reached|<epoch>`, "try again in 3 hours 20 minutes",+/// "resets in 45m", else now plus the default cooldown. Never more than 7 days out.+fn quota_reset(text: &str, lower: &str, now: DateTime<Utc>) -> DateTime<Utc> {+ let fallback = now + Duration::minutes(DEFAULT_QUOTA_COOLDOWN_MINS);+ let at = epoch_after_pipe(text, now).or_else(|| relative_reset(lower).map(|d| now + d));+ match at {+ Some(t) if t > now && t <= now + Duration::days(7) => t,+ _ => fallback,+ }+}++fn epoch_after_pipe(text: &str, now: DateTime<Utc>) -> Option<DateTime<Utc>> {+ let (_, rest) = text.split_once('|')?;+ let digits: String = rest+ .trim()+ .chars()+ .take_while(|c| c.is_ascii_digit())+ .collect();+ let secs: i64 = digits.parse().ok()?;+ // Seconds or milliseconds+ let secs = if secs > 100_000_000_000 {+ secs / 1000+ } else {+ secs+ };+ let at = Utc.timestamp_opt(secs, 0).single()?;+ (at > now - Duration::days(1)).then_some(at)+}++/// Sums "<n> day(s)/hour(s)/minute(s)/second(s)" (also "3h 20m", "3h20m") after "in ".+fn relative_reset(lower: &str) -> Option<Duration> {+ let start = [+ "try again in ",+ "resets in ",+ "reset in ",+ "again in ",+ "available in ",+ ]+ .iter()+ .find_map(|k| lower.find(k).map(|i| i + k.len()))?;+ let tail: String = lower[start..].chars().take(60).collect();+ // "3 hours" and "3hours" both become "3hours"; "and" and commas are skipped+ let mut glued: Vec<String> = Vec::new();+ for word in tail.split(|c: char| c.is_whitespace() || c == ',') {+ let word = word.trim_end_matches(['.', ';', ')']);+ if word.is_empty() || word == "and" {+ continue;+ }+ match glued.last_mut() {+ Some(prev)+ if prev.chars().all(|c| c.is_ascii_digit())+ && word.starts_with(|c: char| c.is_ascii_alphabetic()) =>+ {+ prev.push_str(word)+ }+ _ => glued.push(word.to_string()),+ }+ }+ let mut total = Duration::zero();+ let mut found = false;+ for word in glued {+ let mut rest = word.as_str();+ let mut any = false;+ while !rest.is_empty() {+ let digits = rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_digit()).len();+ if digits == 0 {+ break;+ }+ let n: i64 = rest[..digits].parse().ok()?;+ rest = &rest[digits..];+ let letters = rest.len()+ - rest+ .trim_start_matches(|c: char| c.is_ascii_alphabetic())+ .len();+ let unit = &rest[..letters];+ rest = &rest[letters..];+ total += match unit {+ u if u.starts_with('d') => Duration::days(n),+ u if u.starts_with('h') => Duration::hours(n),+ u if u.starts_with("ms") => break,+ u if u.starts_with('m') => Duration::minutes(n),+ u if u.starts_with('s') => Duration::seconds(n),+ _ => break,+ };+ any = true;+ }+ if !any {+ break;+ }+ found = true;+ }+ found.then_some(total)+}++/// Shortens provider error text for a chat notice: one line, at most `max` chars, with anything+/// that looks like a key or token masked.+pub fn redact_detail(text: &str, max: usize) -> String {+ let line = text+ .lines()+ .map(str::trim)+ .find(|l| !l.is_empty())+ .unwrap_or_default();+ let masked: Vec<String> = line+ .split(' ')+ .map(|w| {+ let looks_secret = w.len() >= 20+ && w.chars()+ .all(|c| c.is_ascii_alphanumeric() || "-_.=/+".contains(c))+ && w.chars().any(|c| c.is_ascii_digit())+ && !w.starts_with("http");+ let prefixed = ["sk-", "xai-", "sess-", "Bearer"]+ .iter()+ .any(|p| w.starts_with(p))+ && w.len() > 8;+ if looks_secret || prefixed {+ "[redacted]".to_string()+ } else {+ w.to_string()+ }+ })+ .collect();+ let joined = masked.join(" ");+ if joined.chars().count() > max {+ let cut: String = joined.chars().take(max).collect();+ format!("{cut}…")+ } else {+ joined+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn now() -> DateTime<Utc> {+ Utc.with_ymd_and_hms(2026, 10, 16, 12, 0, 0).unwrap()+ }++ #[test]+ fn quota_messages_from_each_cli() {+ for text in [+ "Claude AI usage limit reached|1792162800",+ "You've hit your limit · resets 5pm",+ "You've hit your usage limit. Upgrade to Pro or try again in 3 hours 20 minutes.",+ "Error: insufficient_quota: You exceeded your current quota",+ "Your credit balance is too low to access the Anthropic API",+ "usage_limit_exceeded",+ ] {+ let (class, at) = classify(None, text, now()).unwrap();+ assert_eq!(class, FailClass::Quota, "{text}");+ assert!(at.unwrap() > now(), "{text}");+ }+ assert_eq!(classify(Some(402), "", now()).unwrap().0, FailClass::Quota);+ }++ #[test]+ fn quota_reset_times() {+ let (_, at) = classify(None, "Claude AI usage limit reached|1792162800", now()).unwrap();+ assert_eq!(at.unwrap().timestamp(), 1792162800);+ let (_, at) =+ classify(None, "usage limit. try again in 3 hours 20 minutes", now()).unwrap();+ assert_eq!(at.unwrap(), now() + Duration::minutes(200));+ let (_, at) = classify(None, "usage limit; try again in 2h15m.", now()).unwrap();+ assert_eq!(at.unwrap(), now() + Duration::minutes(135));+ let (_, at) = classify(+ None,+ "quota exceeded, try again in 1 day and 2 hours",+ now(),+ )+ .unwrap();+ assert_eq!(at.unwrap(), now() + Duration::hours(26));+ // No time, a past time, or one absurdly far out: the default cooldown+ let default = now() + Duration::minutes(DEFAULT_QUOTA_COOLDOWN_MINS);+ assert_eq!(+ classify(None, "usage limit reached", now())+ .unwrap()+ .1+ .unwrap(),+ default+ );+ assert_eq!(+ classify(None, "usage limit reached|1000", now())+ .unwrap()+ .1+ .unwrap(),+ default+ );+ assert_eq!(+ classify(None, "usage limit, try again in 90 days", now())+ .unwrap()+ .1+ .unwrap(),+ default+ );+ }++ #[test]+ fn auth_messages_from_each_cli() {+ for text in [+ "Not logged in · Please run /login",+ "Not signed in. Run `grok login`.",+ "unexpected status 401 Unauthorized: Missing bearer or basic authentication in header",+ "invalid x-api-key",+ "{\"type\":\"error\",\"error\":{\"type\":\"authentication_error\"}}",+ "OAuth token has expired",+ ] {+ assert_eq!(+ classify(None, text, now()).unwrap().0,+ FailClass::Auth,+ "{text}"+ );+ }+ assert_eq!(classify(Some(401), "", now()).unwrap().0, FailClass::Auth);+ assert_eq!(classify(Some(403), "", now()).unwrap().0, FailClass::Auth);+ }++ #[test]+ fn transient_is_not_failover() {+ for (status, text) in [+ (Some(529), "Overloaded"),+ (+ Some(429),+ "rate_limit_error: Number of requests has exceeded your rate limit",+ ),+ (Some(500), ""),+ (None, "request timed out"),+ ] {+ let (class, at) = classify(status, text, now()).unwrap();+ assert_eq!(class, FailClass::Transient, "{text}");+ assert!(!class.fails_over());+ assert!(at.is_none());+ }+ }++ #[test]+ fn quota_wins_over_auth_and_transient() {+ // A 429 that is about quota, not request rate+ assert_eq!(+ classify(Some(429), "insufficient_quota", now()).unwrap().0,+ FailClass::Quota+ );+ }++ #[test]+ fn ordinary_errors_are_not_classified() {+ assert!(classify(None, "error: file not found: foo.rs", now()).is_none());+ assert!(classify(None, "", now()).is_none());+ assert!(classify(+ Some(400),+ "invalid_request_error: messages: field required",+ now()+ )+ .is_none());+ }++ #[test]+ fn redaction_masks_keys_and_shortens() {+ let text = "invalid x-api-key sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789 for org\nsecond line";+ let out = redact_detail(text, 200);+ assert!(!out.contains("abcdefghij"), "{out}");+ assert!(!out.contains("second line"));+ assert!(out.contains("[redacted]"));+ assert_eq!(redact_detail(&"x".repeat(300), 10).chars().count(), 11);+ }+}diff --git a/src/profiles/login.rs b/src/profiles/login.rsnew file mode 100644index 00000000..9365dad8--- /dev/null+++ b/src/profiles/login.rs@@ -0,0 +1,572 @@+//! In-app sign-in for `cli_home` profiles: runs the engine CLI's own login with its config dir+//! pointed at the profile home and shows the user the sign-in link (and device code).+//! Claude prints a link and then waits for the code the user pastes back; Codex and Grok use a+//! device code and finish on their own once the user approves it in the browser.++use super::{CliEnv, Engine};+use serde::Serialize;+use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::process::Stdio;+use std::sync::{Arc, Mutex};+use std::time::Duration;+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};+use tokio::process::ChildStdin;+use tokio::sync::Notify;++/// A login nobody finishes is killed after this long.+pub const LOGIN_TIMEOUT: Duration = Duration::from_secs(600);++/// Hosts a sign-in link may point at. Anything else ends the login: kwnt never shows the user+/// a link a compromised or unexpected binary printed.+pub const LOGIN_HOSTS: &[&str] = &[+ "claude.ai",+ "claude.com",+ "console.anthropic.com",+ "platform.claude.com",+ "auth.openai.com",+ "chatgpt.com",+ "accounts.x.ai",+ "auth.x.ai",+];++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum LoginStatus {+ /// Started, no link yet.+ Starting,+ /// Link shown; waiting for the user (and, for Claude, the pasted code).+ Waiting,+ Succeeded,+ Failed,+ Expired,+ Cancelled,+}++impl LoginStatus {+ pub fn is_active(self) -> bool {+ matches!(self, LoginStatus::Starting | LoginStatus::Waiting)+ }+}++/// What the UI shows for a login. Holds no secrets: the link and device code are meant for the user.+#[derive(Debug, Clone, Serialize)]+pub struct LoginView {+ pub flow_id: String,+ pub profile_id: String,+ pub status: LoginStatus,+ pub url: Option<String>,+ pub user_code: Option<String>,+ /// Whether the user must paste a code back (Claude).+ pub needs_code: bool,+ pub error: Option<String>,+ pub expires_at: chrono::DateTime<chrono::Utc>,+}++struct Flow {+ view: Mutex<LoginView>,+ home: PathBuf,+ stdin: tokio::sync::Mutex<Option<ChildStdin>>,+ cancel: Notify,+}++/// Login flows by id, at most one active per profile home.+#[derive(Default, Clone)]+pub struct LoginManager {+ flows: Arc<Mutex<HashMap<String, Arc<Flow>>>>,+}++/// Called with the profile id when a login succeeds.+pub type OnSuccess = Arc<dyn Fn(String) + Send + Sync>;++impl LoginManager {+ /// Starts a login, or returns the active one for this home.+ pub async fn start(+ &self,+ engine: Engine,+ bin: &str,+ profile_id: &str,+ home: &Path,+ on_success: OnSuccess,+ ) -> Result<LoginView, String> {+ {+ let mut flows = self.flows.lock().unwrap();+ flows.retain(|_, f| f.view.lock().unwrap().status.is_active() || !expired_long_ago(f));+ if let Some(f) = flows+ .values()+ .find(|f| f.home == home && f.view.lock().unwrap().status.is_active())+ {+ return Ok(f.view.lock().unwrap().clone());+ }+ }+ let mut cmd = tokio::process::Command::new(bin);+ match engine {+ Engine::Claude => cmd.args(["auth", "login", "--claudeai"]),+ Engine::Codex => cmd.args(["login", "--device-auth"]),+ Engine::Grok => cmd.args(["login", "--device-auth"]),+ };+ CliEnv::for_home(engine, home).apply(&mut cmd);+ // CLIs print plain links without a terminal; keep them from opening a host browser+ cmd.env("BROWSER", "true")+ .env("NO_COLOR", "1")+ .env_remove("DISPLAY")+ .env_remove("WAYLAND_DISPLAY")+ .current_dir(home)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .kill_on_drop(true);+ let mut child = cmd+ .spawn()+ .map_err(|e| format!("could not start {} login: {e}", engine.as_str()))?;+ let flow_id = format!("login_{}", uuid::Uuid::new_v4().simple());+ let flow = Arc::new(Flow {+ view: Mutex::new(LoginView {+ flow_id: flow_id.clone(),+ profile_id: profile_id.to_string(),+ status: LoginStatus::Starting,+ url: None,+ user_code: None,+ needs_code: engine == Engine::Claude,+ error: None,+ expires_at: chrono::Utc::now() + chrono::Duration::from_std(LOGIN_TIMEOUT).unwrap(),+ }),+ home: home.to_path_buf(),+ stdin: tokio::sync::Mutex::new(child.stdin.take()),+ cancel: Notify::new(),+ });+ self.flows+ .lock()+ .unwrap()+ .insert(flow_id.clone(), flow.clone());++ let (line_tx, mut line_rx) = tokio::sync::mpsc::channel::<String>(64);+ if let Some(out) = child.stdout.take() {+ tokio::spawn(read_lines(BufReader::new(out), line_tx.clone()));+ }+ if let Some(err) = child.stderr.take() {+ tokio::spawn(read_lines(BufReader::new(err), line_tx));+ }+ let profile_id = profile_id.to_string();+ tokio::spawn(async move {+ let deadline = tokio::time::sleep(LOGIN_TIMEOUT);+ tokio::pin!(deadline);+ let mut lines_open = true;+ let end = loop {+ tokio::select! {+ line = line_rx.recv(), if lines_open => match line {+ Some(line) => {+ if let Err(e) = flow.take_line(&line) {+ break (LoginStatus::Failed, Some(e));+ }+ }+ None => lines_open = false,+ },+ status = child.wait() => {+ // Read what's left so a link printed right before exit isn't lost+ while let Ok(line) = line_rx.try_recv() {+ let _ = flow.take_line(&line);+ }+ break match status {+ Ok(s) if s.success() => (LoginStatus::Succeeded, None),+ Ok(s) => (LoginStatus::Failed, Some(format!("sign-in did not finish (exit {})", s.code().unwrap_or(-1)))),+ Err(_) => (LoginStatus::Failed, Some("sign-in process failed".into())),+ };+ }+ _ = &mut deadline => break (LoginStatus::Expired, Some("sign-in timed out".into())),+ _ = flow.cancel.notified() => break (LoginStatus::Cancelled, None),+ }+ };+ let _ = child.kill().await;+ flow.stdin.lock().await.take();+ {+ let mut view = flow.view.lock().unwrap();+ view.status = end.0;+ view.error = end.1;+ }+ if end.0 == LoginStatus::Succeeded {+ on_success(profile_id);+ }+ });+ // Give the CLI a moment to print its link so the first response usually has it+ for _ in 0..30 {+ match self.get(&flow_id) {+ Some(view) if view.url.is_none() && view.status.is_active() => {}+ Some(view) => return Ok(view),+ None => break,+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ self.get(&flow_id)+ .ok_or_else(|| "sign-in vanished".to_string())+ }++ pub fn get(&self, flow_id: &str) -> Option<LoginView> {+ self.flows+ .lock()+ .unwrap()+ .get(flow_id)+ .map(|f| f.view.lock().unwrap().clone())+ }++ /// Hands the code the user pasted to Claude's login. Only once per flow.+ pub async fn submit_code(&self, flow_id: &str, code: &str) -> Result<LoginView, String> {+ let flow = self+ .flows+ .lock()+ .unwrap()+ .get(flow_id)+ .cloned()+ .ok_or("no such sign-in")?;+ let code = code.trim();+ let valid = (8..=512).contains(&code.len())+ && code+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || "._#~-".contains(c));+ if !valid {+ return Err("that doesn't look like a sign-in code".into());+ }+ {+ let view = flow.view.lock().unwrap();+ if !view.needs_code || view.status != LoginStatus::Waiting {+ return Err("this sign-in is not waiting for a code".into());+ }+ }+ let mut stdin = flow.stdin.lock().await;+ let pipe = stdin.as_mut().ok_or("a code was already sent")?;+ pipe.write_all(format!("{code}\n").as_bytes())+ .await+ .map_err(|_| "sign-in process is gone")?;+ let _ = pipe.flush().await;+ stdin.take();+ drop(stdin);+ let view = flow.view.lock().unwrap().clone();+ Ok(view)+ }++ pub fn cancel(&self, flow_id: &str) -> bool {+ match self.flows.lock().unwrap().get(flow_id) {+ Some(f) if f.view.lock().unwrap().status.is_active() => {+ f.cancel.notify_one();+ true+ }+ _ => false,+ }+ }++ /// Cancels every active login of a profile, e.g. before it is deleted.+ pub fn cancel_profile(&self, profile_id: &str) {+ for f in self.flows.lock().unwrap().values() {+ let view = f.view.lock().unwrap();+ if view.profile_id == profile_id && view.status.is_active() {+ f.cancel.notify_one();+ }+ }+ }+}++fn expired_long_ago(f: &Flow) -> bool {+ f.view.lock().unwrap().expires_at + chrono::Duration::minutes(30) < chrono::Utc::now()+}++async fn read_lines<R: tokio::io::AsyncRead + Unpin>(+ reader: BufReader<R>,+ tx: tokio::sync::mpsc::Sender<String>,+) {+ let mut lines = reader.lines();+ while let Ok(Some(line)) = lines.next_line().await {+ if tx.send(line).await.is_err() {+ break;+ }+ }+}++impl Flow {+ /// Picks the sign-in link and device code out of a line of CLI output.+ fn take_line(&self, raw: &str) -> Result<(), String> {+ let line = strip_ansi(raw);+ let mut view = self.view.lock().unwrap();+ if view.url.is_none() {+ if let Some(url) = first_https_url(&line) {+ let url = check_login_url(&url)?;+ if view.user_code.is_none() {+ view.user_code = user_code_in_query(&url);+ }+ view.url = Some(url);+ view.status = LoginStatus::Waiting;+ return Ok(());+ }+ }+ if view.user_code.is_none() && view.url.is_some() {+ view.user_code = device_code(&line);+ }+ Ok(())+ }+}++/// Removes terminal escape sequences (colors, cursor moves, OSC hyperlinks).+pub fn strip_ansi(s: &str) -> String {+ let mut out = String::with_capacity(s.len());+ let mut chars = s.chars().peekable();+ while let Some(c) = chars.next() {+ if c != '\u{1b}' {+ if !c.is_control() || c == '\t' {+ out.push(c);+ }+ continue;+ }+ match chars.next() {+ Some('[') => {+ for c in chars.by_ref() {+ if ('@'..='~').contains(&c) {+ break;+ }+ }+ }+ Some(']') => {+ // OSC: ends at BEL or ESC \+ while let Some(c) = chars.next() {+ if c == '\u{7}' {+ break;+ }+ if c == '\u{1b}' {+ chars.next();+ break;+ }+ }+ }+ _ => {}+ }+ }+ out+}++fn first_https_url(line: &str) -> Option<String> {+ let start = line.find("https://")?;+ let url: String = line[start..]+ .chars()+ .take_while(|c| !c.is_whitespace() && !matches!(c, '"' | '\'' | '<' | '>' | ')' | ']'))+ .collect();+ Some(url.trim_end_matches(['.', ',']).to_string())+}++/// Accepts a sign-in link only on an allowed host, over https, with no credentials or odd port.+pub fn check_login_url(raw: &str) -> Result<String, String> {+ let url =+ url::Url::parse(raw).map_err(|_| "the sign-in link was not a valid URL".to_string())?;+ let host = url.host_str().unwrap_or_default().to_ascii_lowercase();+ let ok = url.scheme() == "https"+ && url.username().is_empty()+ && url.password().is_none()+ && url.port().is_none()+ && LOGIN_HOSTS.contains(&host.as_str());+ if !ok {+ return Err(format!(+ "refused a sign-in link to an unexpected host ({host})"+ ));+ }+ Ok(url.to_string())+}++fn user_code_in_query(url: &str) -> Option<String> {+ let url = url::Url::parse(url).ok()?;+ let code = url+ .query_pairs()+ .find(|(k, _)| k == "user_code")?+ .1+ .into_owned();+ is_device_code(&code).then_some(code)+}++/// A device code like `ABCD-EFGH` or `ABCD-12345` printed on its own.+fn device_code(line: &str) -> Option<String> {+ line.split(|c: char| c.is_whitespace() || matches!(c, ':' | '"' | '\''))+ .map(|w| w.trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '-'))+ .find(|w| is_device_code(w))+ .map(str::to_string)+}++fn is_device_code(w: &str) -> bool {+ let Some((a, b)) = w.split_once('-') else {+ return false;+ };+ let part = |s: &str, lens: std::ops::RangeInclusive<usize>| {+ lens.contains(&s.len())+ && s.chars()+ .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())+ };+ part(a, 4..=4) && part(b, 4..=5)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn login_url_allowlist() {+ assert!(+ check_login_url("https://claude.com/cai/oauth/authorize?code=true&client_id=x").is_ok()+ );+ assert!(check_login_url("https://auth.openai.com/codex/device").is_ok());+ assert!(check_login_url("https://accounts.x.ai/oauth2/device?user_code=ABCD-EFGH").is_ok());+ for bad in [+ "http://claude.com/cai/oauth",+ "https://claude.com.evil.example/x",+ "https://evil.example/claude.com",+ "https://user:[email protected]/x",+ "https://claude.com:8443/x",+ "https://sub.claude.ai.attacker.io/",+ "not a url",+ ] {+ assert!(check_login_url(bad).is_err(), "{bad}");+ }+ }++ #[test]+ fn strips_ansi_and_finds_links_and_codes() {+ let line = "\u{1b}[94mhttps://auth.openai.com/codex/device\u{1b}[0m";+ assert_eq!(+ first_https_url(&strip_ansi(line)).unwrap(),+ "https://auth.openai.com/codex/device"+ );+ assert_eq!(+ device_code(&strip_ansi(" \u{1b}[94mABCD-12345\u{1b}[0m")).as_deref(),+ Some("ABCD-12345")+ );+ assert_eq!(+ user_code_in_query("https://accounts.x.ai/oauth2/device?user_code=WXYZ-1234")+ .as_deref(),+ Some("WXYZ-1234")+ );+ assert_eq!(device_code("Paste code here if prompted > "), None);+ assert_eq!(+ first_https_url("Browser didn't open? Use the url below: https://claude.com/cai/oauth/authorize?a=b.").unwrap(),+ "https://claude.com/cai/oauth/authorize?a=b"+ );+ }++ #[cfg(unix)]+ fn fake_cli(dir: &Path, script: &str) -> String {+ use std::os::unix::fs::PermissionsExt;+ let path = dir.join("fake-cli");+ std::fs::write(&path, format!("#!/bin/sh\n{script}\n")).unwrap();+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();+ path.to_string_lossy().into_owned()+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn claude_style_login_takes_pasted_code() {+ let dir = tempfile::tempdir().unwrap();+ let home = dir.path().join("home");+ std::fs::create_dir(&home).unwrap();+ // Prints a link, reads the code, records it in the home and exits 0 only for the right one+ let bin = fake_cli(+ dir.path(),+ r#"echo "Visit: https://claude.com/cai/oauth/authorize?code=true"+printf 'Paste code here if prompted > '+read code+echo "$CLAUDE_CONFIG_DIR" > "$CLAUDE_CONFIG_DIR/seen-home"+[ "$code" = "abcDEF123#state" ]"#,+ );+ let mgr = LoginManager::default();+ let done = Arc::new(Mutex::new(None));+ let done2 = done.clone();+ let view = mgr+ .start(+ Engine::Claude,+ &bin,+ "prf_x",+ &home,+ Arc::new(move |id| *done2.lock().unwrap() = Some(id)),+ )+ .await+ .unwrap();+ assert_eq!(view.status, LoginStatus::Waiting);+ assert!(view.needs_code);+ assert!(view.url.unwrap().starts_with("https://claude.com/"));+ // The same home gets the same flow back+ let again = mgr+ .start(Engine::Claude, &bin, "prf_x", &home, Arc::new(|_| {}))+ .await+ .unwrap();+ assert_eq!(again.flow_id, view.flow_id);+ assert!(mgr.submit_code(&view.flow_id, "bad code!").await.is_err());+ mgr.submit_code(&view.flow_id, "abcDEF123#state")+ .await+ .unwrap();+ assert!(mgr+ .submit_code(&view.flow_id, "abcDEF123#state")+ .await+ .is_err());+ for _ in 0..50 {+ if !mgr.get(&view.flow_id).unwrap().status.is_active() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ assert_eq!(+ mgr.get(&view.flow_id).unwrap().status,+ LoginStatus::Succeeded+ );+ assert_eq!(done.lock().unwrap().as_deref(), Some("prf_x"));+ let seen = std::fs::read_to_string(home.join("seen-home")).unwrap();+ assert_eq!(seen.trim(), home.to_str().unwrap());+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn unexpected_link_kills_the_login() {+ let dir = tempfile::tempdir().unwrap();+ let bin = fake_cli(+ dir.path(),+ "echo 'Go to https://evil.example/device'\nsleep 30",+ );+ let mgr = LoginManager::default();+ let view = mgr+ .start(Engine::Codex, &bin, "prf_y", dir.path(), Arc::new(|_| {}))+ .await+ .unwrap();+ assert_eq!(view.status, LoginStatus::Failed);+ assert!(view.url.is_none());+ assert!(view.error.unwrap().contains("unexpected host"));+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn device_login_shows_code_and_can_be_cancelled() {+ let dir = tempfile::tempdir().unwrap();+ let bin = fake_cli(+ dir.path(),+ "echo 'Open https://auth.openai.com/codex/device' >&2\necho ' ABCD-12345' >&2\nsleep 30",+ );+ let mgr = LoginManager::default();+ let view = mgr+ .start(Engine::Codex, &bin, "prf_z", dir.path(), Arc::new(|_| {}))+ .await+ .unwrap();+ assert_eq!(view.status, LoginStatus::Waiting);+ assert!(!view.needs_code);+ for _ in 0..20 {+ if mgr.get(&view.flow_id).unwrap().user_code.is_some() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ assert_eq!(+ mgr.get(&view.flow_id).unwrap().user_code.as_deref(),+ Some("ABCD-12345")+ );+ assert!(mgr.cancel(&view.flow_id));+ for _ in 0..20 {+ if !mgr.get(&view.flow_id).unwrap().status.is_active() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ assert_eq!(+ mgr.get(&view.flow_id).unwrap().status,+ LoginStatus::Cancelled+ );+ }+}diff --git a/src/profiles/mod.rs b/src/profiles/mod.rsnew file mode 100644index 00000000..20a8d942--- /dev/null+++ b/src/profiles/mod.rs@@ -0,0 +1,576 @@+//! LLM profiles: several accounts per engine (say a work and a personal Claude), how a turn+//! launches with one, and which one a turn moves to when an account runs out of quota.++pub mod classify;+pub mod login;+pub mod status;++use crate::db::models::{LlmProfile, LlmProfileState, ProfileKey};+use chrono::{DateTime, Utc};+use std::collections::{HashMap, HashSet};+use std::path::{Path, PathBuf};++pub use classify::{classify, FailClass, ProviderFailure};+pub use status::{ProfileManager, ProfileStatus};++/// Most profiles one turn may try.+pub const MAX_ATTEMPTS: usize = 3;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum Engine {+ Claude,+ Codex,+ Grok,+}++impl Engine {+ pub fn parse(s: &str) -> Option<Self> {+ match s {+ "claude" => Some(Engine::Claude),+ "codex" => Some(Engine::Codex),+ "grok" => Some(Engine::Grok),+ _ => None,+ }+ }++ /// The engine a routed model id runs on, matching how drivers pick a CLI or API.+ /// Models of other providers (Ollama) have no profiles.+ pub fn from_model(model: &str) -> Option<Self> {+ if model.contains("claude") {+ Some(Engine::Claude)+ } else if model.contains("grok") {+ Some(Engine::Grok)+ } else if model.contains("codex") || model.contains("gpt") || model.contains("openai") {+ Some(Engine::Codex)+ } else {+ None+ }+ }++ pub fn as_str(self) -> &'static str {+ match self {+ Engine::Claude => "claude",+ Engine::Codex => "codex",+ Engine::Grok => "grok",+ }+ }++ /// Env variable that points the CLI at a config dir holding its login.+ pub fn home_env(self) -> &'static str {+ match self {+ Engine::Claude => "CLAUDE_CONFIG_DIR",+ Engine::Codex => "CODEX_HOME",+ Engine::Grok => "GROK_HOME",+ }+ }++ /// Credentials in kwnt's env that would override a profile's login, removed for its CLI.+ pub fn credential_env(self) -> &'static [&'static str] {+ match self {+ Engine::Claude => &[+ "ANTHROPIC_API_KEY",+ "ANTHROPIC_AUTH_TOKEN",+ "CLAUDE_CODE_OAUTH_TOKEN",+ "CLAUDE_CODE_OAUTH_REFRESH_TOKEN",+ ],+ Engine::Codex => &["OPENAI_API_KEY", "CODEX_API_KEY"],+ Engine::Grok => &["XAI_API_KEY", "GROK_AUTH_PATH"],+ }+ }++ /// The Settings key the system profile uses, as before profiles.+ pub fn key_setting(self) -> &'static str {+ match self {+ Engine::Claude => "anthropic_api_key",+ Engine::Codex => "openai_api_key",+ Engine::Grok => "xai_api_key",+ }+ }++ /// Model id handed to the API driver, which picks the provider endpoint from it.+ pub fn api_model(self) -> &'static str {+ match self {+ Engine::Claude => "claude",+ Engine::Codex => "codex",+ Engine::Grok => "grok",+ }+ }++ /// The CLI's own config dir when kwnt doesn't set one: what the system profile uses.+ pub fn system_home(self) -> Option<PathBuf> {+ let from_env = std::env::var_os(self.home_env())+ .filter(|v| !v.is_empty())+ .map(PathBuf::from);+ from_env.or_else(|| {+ dirs::home_dir().map(|h| {+ h.join(match self {+ Engine::Claude => ".claude",+ Engine::Codex => ".codex",+ Engine::Grok => ".grok",+ })+ })+ })+ }+}++/// How a turn runs with a profile.+#[derive(Debug, Clone)]+pub enum Launch {+ /// Exactly as before profiles: Settings key, then env key, then the CLI's own login.+ System,+ /// The API driver with this profile's stored key.+ ApiKey(ProfileKey),+ /// The engine's CLI with its config dir pointed at this home.+ CliHome(PathBuf),+}++/// Env changes that run a CLI on a profile's home: its home variable set and every credential+/// variable that would override the home's login removed.+#[derive(Debug, Clone, Default, PartialEq)]+pub struct CliEnv {+ pub set: Vec<(String, std::ffi::OsString)>,+ pub remove: Vec<String>,+}++impl CliEnv {+ pub fn for_home(engine: Engine, home: &Path) -> Self {+ Self {+ set: vec![(engine.home_env().to_string(), home.as_os_str().to_owned())],+ remove: engine+ .credential_env()+ .iter()+ .map(|s| s.to_string())+ .collect(),+ }+ }++ pub fn apply(&self, cmd: &mut tokio::process::Command) {+ for key in &self.remove {+ cmd.env_remove(key);+ }+ for (key, value) in &self.set {+ cmd.env(key, value);+ }+ }+}++/// Where kwnt keeps the home of a profile it manages.+pub fn managed_home(data_dir: &Path, profile_id: &str) -> PathBuf {+ data_dir.join("profiles").join(profile_id)+}++/// Creates a managed home, readable by this user only.+pub fn create_private_dir(path: &Path) -> std::io::Result<()> {+ std::fs::create_dir_all(path)?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))?;+ }+ Ok(())+}++/// Checks a home dir the user picked for a `cli_home` profile and returns its canonical path:+/// an existing, absolute, real (not symlinked) directory owned by kwnt's user, and not `/`,+/// `$HOME`, the engine's own default home or another profile's home.+pub fn validate_user_home(+ raw: &str,+ engine: Engine,+ other_homes: &[String],+) -> Result<PathBuf, String> {+ let path = Path::new(raw);+ if !path.is_absolute() {+ return Err("home_dir must be an absolute path".into());+ }+ let meta =+ std::fs::symlink_metadata(path).map_err(|_| "home_dir does not exist".to_string())?;+ if meta.file_type().is_symlink() {+ return Err("home_dir must not be a symlink".into());+ }+ if !meta.is_dir() {+ return Err("home_dir must be a directory".into());+ }+ #[cfg(unix)]+ {+ use std::os::unix::fs::MetadataExt;+ let own_uid = dirs::home_dir()+ .and_then(|h| std::fs::metadata(h).ok())+ .map(|m| m.uid());+ if own_uid.is_some_and(|uid| uid != meta.uid()) {+ return Err("home_dir must belong to the user kwnt runs as".into());+ }+ }+ let canonical = path+ .canonicalize()+ .map_err(|_| "home_dir is not readable".to_string())?;+ let canon = |p: PathBuf| p.canonicalize().unwrap_or(p);+ if canonical == Path::new("/")+ || dirs::home_dir().map(canon).as_deref() == Some(canonical.as_path())+ {+ return Err("home_dir is too broad; pick a dedicated directory".into());+ }+ if engine.system_home().map(canon).as_deref() == Some(canonical.as_path()) {+ return Err(+ "home_dir is this engine's default login, which the system profile already uses".into(),+ );+ }+ if other_homes+ .iter()+ .any(|h| canon(PathBuf::from(h)) == canonical)+ {+ return Err("another profile already uses this home_dir".into());+ }+ Ok(canonical)+}++/// Facts about a profile that decide whether a turn can use it right now.+#[derive(Debug, Default)]+pub struct Availability {+ pub states: HashMap<String, LlmProfileState>,+ pub with_key: HashSet<String>,+ /// Profiles whose last login check said signed out.+ pub signed_out: HashSet<String>,+}++impl Availability {+ fn usable(&self, p: &LlmProfile, now: DateTime<Utc>) -> bool {+ let limited = self+ .states+ .get(&p.id)+ .and_then(|s| s.limited_until)+ .is_some_and(|t| t > now);+ let keyless = p.kind == "api_key" && !self.with_key.contains(&p.id);+ !limited && !keyless && !self.signed_out.contains(&p.id)+ }+}++/// Profiles a turn on `engine` tries, in order. First the kwant's own profile (`bound`, if it is+/// an enabled profile of this engine) or else the engine default; then, with failover on, the+/// engine's other enabled profiles by priority that aren't out of quota, keyless or signed out.+/// The first one is skipped too when unusable, unless failover is off or nothing else is usable.+/// Empty when the engine has no enabled profile: the turn then runs as before profiles.+pub fn failover_order(+ profiles: &[LlmProfile],+ engine: Engine,+ bound: Option<&str>,+ failover: bool,+ avail: &Availability,+ now: DateTime<Utc>,+) -> Vec<LlmProfile> {+ let mut mine: Vec<&LlmProfile> = profiles+ .iter()+ .filter(|p| p.engine == engine.as_str() && p.enabled)+ .collect();+ mine.sort_by(|a, b| (a.priority, a.created_at, &a.id).cmp(&(b.priority, b.created_at, &b.id)));+ let first = bound+ .and_then(|id| mine.iter().find(|p| p.id == id))+ .or_else(|| mine.iter().find(|p| p.is_default))+ .or_else(|| mine.first())+ .copied();+ let Some(first) = first else {+ return Vec::new();+ };+ if !failover {+ return vec![first.clone()];+ }+ let rest: Vec<LlmProfile> = mine+ .iter()+ .filter(|p| p.id != first.id && avail.usable(p, now))+ .map(|p| (*p).clone())+ .collect();+ let mut order = Vec::with_capacity(MAX_ATTEMPTS);+ if avail.usable(first, now) || rest.is_empty() {+ order.push(first.clone());+ }+ order.extend(rest);+ order.truncate(MAX_ATTEMPTS);+ order+}++/// Validates a profile name: 1 to 40 printable characters, trimmed.+pub fn clean_name(raw: &str) -> Result<String, String> {+ let name = raw.trim();+ if name.is_empty() || name.chars().count() > 40 || name.chars().any(char::is_control) {+ return Err("name must be 1 to 40 printable characters".into());+ }+ Ok(name.to_string())+}++/// Validates an API key: 8 to 512 characters, no whitespace or control characters.+pub fn clean_key(raw: &str) -> Result<ProfileKey, String> {+ let key = raw.trim();+ let len = key.chars().count();+ if !(8..=512).contains(&len) || key.chars().any(|c| c.is_whitespace() || c.is_control()) {+ return Err("api_key must be 8 to 512 characters with no spaces".into());+ }+ Ok(ProfileKey(key.to_string()))+}++#[cfg(test)]+mod tests {+ use super::*;+ use chrono::TimeZone;++ fn profile(id: &str, engine: &str, kind: &str, priority: i64, default: bool) -> LlmProfile {+ LlmProfile {+ id: id.into(),+ engine: engine.into(),+ name: id.into(),+ kind: kind.into(),+ home_dir: None,+ priority,+ enabled: true,+ is_default: default,+ created_at: None,+ }+ }++ fn now() -> DateTime<Utc> {+ Utc.with_ymd_and_hms(2026, 10, 16, 12, 0, 0).unwrap()+ }++ fn ids(v: &[LlmProfile]) -> Vec<&str> {+ v.iter().map(|p| p.id.as_str()).collect()+ }++ #[test]+ fn engine_from_model() {+ assert_eq!(Engine::from_model("claude"), Some(Engine::Claude));+ assert_eq!(Engine::from_model("claude-opus-5-5"), Some(Engine::Claude));+ assert_eq!(Engine::from_model("grok-beta"), Some(Engine::Grok));+ assert_eq!(Engine::from_model("gpt-5"), Some(Engine::Codex));+ assert_eq!(Engine::from_model("codex"), Some(Engine::Codex));+ assert_eq!(Engine::from_model("local_ollama"), None);+ }++ #[test]+ fn launch_env_per_engine() {+ let home = Path::new("/data/profiles/prf_1");+ let env = CliEnv::for_home(Engine::Claude, home);+ assert_eq!(+ env.set,+ vec![("CLAUDE_CONFIG_DIR".to_string(), home.as_os_str().to_owned())]+ );+ assert!(env.remove.contains(&"ANTHROPIC_API_KEY".to_string()));+ assert!(env.remove.contains(&"CLAUDE_CODE_OAUTH_TOKEN".to_string()));+ let env = CliEnv::for_home(Engine::Codex, home);+ assert_eq!(env.set[0].0, "CODEX_HOME");+ assert!(env.remove.contains(&"OPENAI_API_KEY".to_string()));+ let env = CliEnv::for_home(Engine::Grok, home);+ assert_eq!(env.set[0].0, "GROK_HOME");+ assert!(env.remove.contains(&"XAI_API_KEY".to_string()));+ assert!(env.remove.contains(&"GROK_AUTH_PATH".to_string()));+ }++ #[test]+ fn order_starts_with_bound_then_default_then_priority() {+ let profiles = vec![+ profile("sys", "claude", "system", 0, true),+ profile("work", "claude", "cli_home", 10, false),+ profile("personal", "claude", "cli_home", 20, false),+ profile("g", "grok", "system", 0, true),+ ];+ let empty = Availability::default();+ assert_eq!(+ ids(&failover_order(+ &profiles,+ Engine::Claude,+ None,+ true,+ &empty,+ now()+ )),+ ["sys", "work", "personal"]+ );+ assert_eq!(+ ids(&failover_order(+ &profiles,+ Engine::Claude,+ Some("personal"),+ true,+ &empty,+ now()+ )),+ ["personal", "sys", "work"]+ );+ // A binding to another engine's profile is ignored+ assert_eq!(+ ids(&failover_order(+ &profiles,+ Engine::Claude,+ Some("g"),+ true,+ &empty,+ now()+ ))[0],+ "sys"+ );+ // Pinned: only the first+ assert_eq!(+ ids(&failover_order(+ &profiles,+ Engine::Claude,+ Some("work"),+ false,+ &empty,+ now()+ )),+ ["work"]+ );+ assert!(failover_order(&profiles, Engine::Codex, None, true, &empty, now()).is_empty());+ }++ #[test]+ fn order_skips_limited_keyless_signed_out_and_disabled() {+ let mut profiles = vec![+ profile("sys", "claude", "system", 0, true),+ profile("a", "claude", "cli_home", 1, false),+ profile("b", "claude", "api_key", 2, false),+ profile("c", "claude", "cli_home", 3, false),+ profile("d", "claude", "cli_home", 4, false),+ ];+ profiles[4].enabled = false;+ let states = HashMap::from([(+ "sys".to_string(),+ LlmProfileState {+ profile_id: "sys".into(),+ limited_until: Some(now() + chrono::Duration::hours(1)),+ last_error: Some("quota".into()),+ },+ )]);+ let avail = Availability {+ states,+ with_key: HashSet::new(),+ signed_out: HashSet::from(["a".to_string()]),+ };+ // sys is limited so it's skipped even as the default; a is signed out; b has no key; d is disabled+ assert_eq!(+ ids(&failover_order(+ &profiles,+ Engine::Claude,+ None,+ true,+ &avail,+ now()+ )),+ ["c"]+ );+ // Pinned to a limited profile: still tried, the user asked for it+ assert_eq!(+ ids(&failover_order(+ &profiles,+ Engine::Claude,+ None,+ false,+ &avail,+ now()+ )),+ ["sys"]+ );+ // An expired limit doesn't count+ let later = now() + chrono::Duration::hours(2);+ assert_eq!(+ ids(&failover_order(+ &profiles,+ Engine::Claude,+ None,+ true,+ &avail,+ later+ )),+ ["sys", "c"]+ );+ }++ #[test]+ fn order_keeps_unusable_first_when_nothing_else_works() {+ let profiles = vec![profile("sys", "claude", "system", 0, true)];+ let states = HashMap::from([(+ "sys".to_string(),+ LlmProfileState {+ profile_id: "sys".into(),+ limited_until: Some(now() + chrono::Duration::hours(1)),+ last_error: None,+ },+ )]);+ let avail = Availability {+ states,+ ..Default::default()+ };+ assert_eq!(+ ids(&failover_order(+ &profiles,+ Engine::Claude,+ None,+ true,+ &avail,+ now()+ )),+ ["sys"]+ );+ }++ #[test]+ fn order_is_capped() {+ let profiles: Vec<_> = (0..6)+ .map(|i| profile(&format!("p{i}"), "codex", "cli_home", i, i == 0))+ .collect();+ assert_eq!(+ failover_order(+ &profiles,+ Engine::Codex,+ None,+ true,+ &Availability::default(),+ now()+ )+ .len(),+ MAX_ATTEMPTS+ );+ }++ #[test]+ fn user_home_validation() {+ let dir = tempfile::tempdir().unwrap();+ let ok = dir.path().join("work-claude");+ std::fs::create_dir(&ok).unwrap();+ assert_eq!(+ validate_user_home(ok.to_str().unwrap(), Engine::Claude, &[]).unwrap(),+ ok.canonicalize().unwrap()+ );+ assert!(validate_user_home("relative/dir", Engine::Claude, &[]).is_err());+ assert!(validate_user_home(+ dir.path().join("missing").to_str().unwrap(),+ Engine::Claude,+ &[]+ )+ .is_err());+ let file = dir.path().join("file");+ std::fs::write(&file, "x").unwrap();+ assert!(validate_user_home(file.to_str().unwrap(), Engine::Claude, &[]).is_err());+ #[cfg(unix)]+ {+ let link = dir.path().join("link");+ std::os::unix::fs::symlink(&ok, &link).unwrap();+ assert!(validate_user_home(link.to_str().unwrap(), Engine::Claude, &[]).is_err());+ }+ assert!(validate_user_home("/", Engine::Claude, &[]).is_err());+ if let Some(home) = dirs::home_dir() {+ assert!(validate_user_home(home.to_str().unwrap(), Engine::Claude, &[]).is_err());+ }+ let taken = vec![ok.to_string_lossy().into_owned()];+ assert!(validate_user_home(ok.to_str().unwrap(), Engine::Claude, &taken).is_err());+ }++ #[test]+ fn name_and_key_validation() {+ assert_eq!(clean_name(" Work ").unwrap(), "Work");+ assert!(clean_name("").is_err());+ assert!(clean_name(&"x".repeat(41)).is_err());+ assert!(clean_name("a\nb").is_err());+ assert!(clean_key("sk-ant-1234567890").is_ok());+ assert!(clean_key("short").is_err());+ assert!(clean_key("has space inside").is_err());+ assert!(format!("{:?}", clean_key("sk-ant-1234567890").unwrap()).contains("redacted"));+ }+}diff --git a/src/profiles/status.rs b/src/profiles/status.rsnew file mode 100644index 00000000..eacd1541--- /dev/null+++ b/src/profiles/status.rs@@ -0,0 +1,273 @@+//! Whether each profile is signed in, checked with the engine CLI's own status command and+//! cached so the profile list stays fast and turns never wait on a check.++use super::login::LoginManager;+use super::{managed_home, Engine};+use crate::db::models::LlmProfile;+use serde::Serialize;+use std::collections::{HashMap, HashSet};+use std::path::{Path, PathBuf};+use std::process::Stdio;+use std::sync::Mutex;+use std::time::{Duration, Instant};++/// How long a sign-in check is reused.+pub const STATUS_TTL: Duration = Duration::from_secs(60);+/// Longest a single check may take.+const PROBE_TIMEOUT: Duration = Duration::from_secs(8);++#[derive(Debug, Clone, Default, PartialEq, Serialize)]+pub struct ProfileStatus {+ /// `None` when it couldn't be told (CLI not installed, check timed out).+ pub signed_in: Option<bool>,+ /// The account the CLI reports (email or sign-in method), or "API key".+ pub account_label: Option<String>,+}++/// Profile homes, sign-in checks and logins.+pub struct ProfileManager {+ pub data_dir: PathBuf,+ pub logins: LoginManager,+ cache: Mutex<HashMap<String, (Instant, ProfileStatus)>>,+}++impl ProfileManager {+ pub fn new(data_dir: PathBuf) -> Self {+ Self {+ data_dir,+ logins: LoginManager::default(),+ cache: Mutex::new(HashMap::new()),+ }+ }++ /// The config dir a `cli_home` profile runs with.+ pub fn home_of(&self, p: &LlmProfile) -> Option<PathBuf> {+ (p.kind == "cli_home").then(|| {+ p.home_dir+ .as_ref()+ .map(PathBuf::from)+ .unwrap_or_else(|| managed_home(&self.data_dir, &p.id))+ })+ }++ pub fn set_status(&self, id: &str, status: ProfileStatus) {+ self.cache+ .lock()+ .unwrap()+ .insert(id.to_string(), (Instant::now(), status));+ }++ pub fn invalidate(&self, id: &str) {+ self.cache.lock().unwrap().remove(id);+ }++ /// Profiles whose last check said signed out, for failover to skip.+ pub fn signed_out(&self) -> HashSet<String> {+ self.cache+ .lock()+ .unwrap()+ .iter()+ .filter(|(_, (_, s))| s.signed_in == Some(false))+ .map(|(id, _)| id.clone())+ .collect()+ }++ /// Sign-in status of every profile; checks run concurrently, only for stale entries.+ /// `with_key`: profiles (and system profiles whose engine has a Settings or env key) that+ /// count as signed in through an API key.+ pub async fn statuses(+ &self,+ profiles: &[LlmProfile],+ with_key: &HashSet<String>,+ ) -> HashMap<String, ProfileStatus> {+ let mut out = HashMap::new();+ let mut checks = Vec::new();+ {+ let cache = self.cache.lock().unwrap();+ for p in profiles {+ if p.kind == "api_key" || (p.kind == "system" && with_key.contains(&p.id)) {+ let has = with_key.contains(&p.id);+ out.insert(+ p.id.clone(),+ ProfileStatus {+ signed_in: Some(has),+ account_label: has.then(|| "API key".to_string()),+ },+ );+ continue;+ }+ match cache.get(&p.id) {+ Some((at, s)) if at.elapsed() < STATUS_TTL => {+ out.insert(p.id.clone(), s.clone());+ }+ _ => {+ if let Some(engine) = Engine::parse(&p.engine) {+ checks.push((p.id.clone(), engine, self.home_of(p)));+ }+ }+ }+ }+ }+ let results =+ futures::future::join_all(checks.into_iter().map(|(id, engine, home)| async move {+ let status = probe(engine, home.as_deref()).await;+ (id, status)+ }))+ .await;+ for (id, status) in results {+ self.set_status(&id, status.clone());+ out.insert(id, status);+ }+ out+ }+}++/// Asks the engine's CLI whether it's signed in, with `home` as its config dir (`None`: the+/// CLI's own default, i.e. the system profile).+pub async fn probe(engine: Engine, home: Option<&Path>) -> ProfileStatus {+ if engine == Engine::Grok {+ // grok has no status command; a login is its auth file+ let file = match home {+ Some(h) => Some(h.join("auth.json")),+ None => std::env::var_os("GROK_AUTH_PATH")+ .filter(|p| !p.is_empty())+ .map(PathBuf::from)+ .or_else(|| engine.system_home().map(|h| h.join("auth.json"))),+ };+ let signed_in = file.is_some_and(|f| f.is_file());+ return ProfileStatus {+ signed_in: Some(signed_in),+ account_label: signed_in.then(|| "grok login".into()),+ };+ }+ let Some(bin) = crate::drivers::find_cli_binary(engine.as_str()) else {+ return ProfileStatus {+ signed_in: None,+ account_label: Some(format!("{} CLI not installed", engine.as_str())),+ };+ };+ let mut cmd = tokio::process::Command::new(bin);+ match engine {+ Engine::Claude => cmd.args(["auth", "status", "--json"]),+ _ => cmd.args(["login", "status"]),+ };+ if let Some(home) = home {+ super::CliEnv::for_home(engine, home).apply(&mut cmd);+ }+ cmd.env("NO_COLOR", "1")+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .kill_on_drop(true);+ let Ok(Ok(out)) = tokio::time::timeout(PROBE_TIMEOUT, cmd.output()).await else {+ return ProfileStatus::default();+ };+ let stdout = String::from_utf8_lossy(&out.stdout);+ let stderr = String::from_utf8_lossy(&out.stderr);+ match engine {+ Engine::Claude => claude_status(&stdout),+ _ => codex_status(out.status.success(), &stdout, &stderr),+ }+}++fn claude_status(stdout: &str) -> ProfileStatus {+ let Ok(v) = serde_json::from_str::<serde_json::Value>(stdout.trim()) else {+ return ProfileStatus::default();+ };+ let signed_in = v["loggedIn"].as_bool();+ let label = ["email", "emailAddress", "account", "authMethod"]+ .iter()+ .find_map(|k| v[*k].as_str().filter(|s| !s.is_empty()))+ .map(|s| s.chars().take(80).collect());+ ProfileStatus {+ signed_in,+ account_label: if signed_in == Some(true) { label } else { None },+ }+}++fn codex_status(success: bool, stdout: &str, stderr: &str) -> ProfileStatus {+ let text = format!("{stdout}\n{stderr}");+ let line = text+ .lines()+ .map(|l| super::login::strip_ansi(l).trim().to_string())+ .find(|l| !l.is_empty())+ .unwrap_or_default();+ let signed_in = success && !line.to_lowercase().contains("not logged in");+ ProfileStatus {+ signed_in: Some(signed_in),+ account_label: signed_in+ .then(|| super::classify::redact_detail(&line, 60))+ .filter(|s| !s.is_empty()),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parses_cli_status_output() {+ let s =+ claude_status(r#"{"loggedIn":true,"authMethod":"claude.ai","email":"[email protected]"}"#);+ assert_eq!(+ s,+ ProfileStatus {+ signed_in: Some(true),+ account_label: Some("[email protected]".into())+ }+ );+ let s = claude_status(r#"{"loggedIn":false,"authMethod":"none"}"#);+ assert_eq!(+ s,+ ProfileStatus {+ signed_in: Some(false),+ account_label: None+ }+ );+ assert_eq!(claude_status("garbage"), ProfileStatus::default());+ let s = codex_status(true, "Logged in using ChatGPT\n", "");+ assert_eq!(s.signed_in, Some(true));+ assert_eq!(s.account_label.as_deref(), Some("Logged in using ChatGPT"));+ assert_eq!(+ codex_status(false, "", "Not logged in\n").signed_in,+ Some(false)+ );+ }++ #[tokio::test]+ async fn grok_status_is_its_auth_file() {+ let dir = tempfile::tempdir().unwrap();+ assert_eq!(+ probe(Engine::Grok, Some(dir.path())).await.signed_in,+ Some(false)+ );+ std::fs::write(dir.path().join("auth.json"), "{}").unwrap();+ assert_eq!(+ probe(Engine::Grok, Some(dir.path())).await.signed_in,+ Some(true)+ );+ }++ #[test]+ fn signed_out_cache() {+ let m = ProfileManager::new(PathBuf::from("/tmp/x"));+ m.set_status(+ "a",+ ProfileStatus {+ signed_in: Some(false),+ account_label: None,+ },+ );+ m.set_status(+ "b",+ ProfileStatus {+ signed_in: Some(true),+ account_label: None,+ },+ );+ m.set_status("c", ProfileStatus::default());+ assert_eq!(m.signed_out(), HashSet::from(["a".to_string()]));+ m.invalidate("a");+ assert!(m.signed_out().is_empty());+ }+}diff --git a/src/server/auth.rs b/src/server/auth.rsnew file mode 100644index 00000000..53862a7d--- /dev/null+++ b/src/server/auth.rs@@ -0,0 +1,451 @@+//! Who may call the API. Browsers may only call it from kwnt's own page (Origin allowlist), and+//! requests that don't come from this machine need the API token, as a bearer header or the+//! `kwnt_token` cookie the UI gets by posting the token to `/api/auth/session`.+//!+//! "From this machine" means a loopback peer, a loopback `Host` and no proxy forwarding headers.+//! The `Host` check is what keeps a DNS-rebinding page (same peer, foreign host) out.++use super::AppState;+use crate::config::Config;+use axum::{+ extract::{ConnectInfo, Request, State},+ http::{header, HeaderMap, HeaderValue, Method, StatusCode},+ middleware::Next,+ response::{IntoResponse, Response},+ Json,+};+use serde::Deserialize;+use serde_json::json;+use std::net::{IpAddr, SocketAddr};+use std::path::Path;++pub const COOKIE: &str = "kwnt_token";+const TOKEN_FILE: &str = "api-token";++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Require {+ /// Requests from other machines need the token (default).+ Auto,+ /// Every API request needs the token, local ones too.+ Always,+ /// No token at all (only for setups behind their own auth).+ Never,+}++pub struct ApiToken {+ token: String,+ pub require: Require,+ /// Extra browser origins allowed besides kwnt's own (`KWNT_ALLOWED_ORIGINS`).+ extra_origins: Vec<String>,+ port: u16,+}++impl std::fmt::Debug for ApiToken {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("ApiToken")+ .field("require", &self.require)+ .finish_non_exhaustive()+ }+}++impl ApiToken {+ /// `KWNT_API_TOKEN`, else `<data_dir>/api-token` (created with a random token, mode 0600).+ pub fn load(config: &Config) -> Self {+ let require = match std::env::var("KWNT_REQUIRE_TOKEN")+ .unwrap_or_default()+ .to_lowercase()+ .as_str()+ {+ "always" | "1" | "true" => Require::Always,+ "never" | "0" | "false" => Require::Never,+ _ => Require::Auto,+ };+ let extra_origins = std::env::var("KWNT_ALLOWED_ORIGINS")+ .unwrap_or_default()+ .split(',')+ .map(|o| o.trim().trim_end_matches('/').to_string())+ .filter(|o| !o.is_empty())+ .collect();+ let token = std::env::var("KWNT_API_TOKEN")+ .ok()+ .map(|t| t.trim().to_string())+ .filter(|t| t.len() >= 16)+ .unwrap_or_else(|| load_or_create(&config.data_dir));+ Self {+ token,+ require,+ extra_origins,+ port: config.port,+ }+ }++ pub fn for_tests(token: &str, require: Require, port: u16) -> Self {+ Self {+ token: token.into(),+ require,+ extra_origins: Vec::new(),+ port,+ }+ }++ /// The token, for `kwnt token` and the startup URL only.+ pub fn reveal(&self) -> &str {+ &self.token+ }++ pub fn matches(&self, candidate: &str) -> bool {+ constant_time_eq(self.token.as_bytes(), candidate.as_bytes())+ }++ fn origin_allowed(&self, origin: &str, host: Option<&str>) -> bool {+ let origin = origin.trim_end_matches('/');+ let own = [self.port, 5199]+ .iter()+ .flat_map(|p| {+ [+ format!("http://127.0.0.1:{p}"),+ format!("http://localhost:{p}"),+ format!("http://[::1]:{p}"),+ ]+ })+ .any(|o| o == origin);+ let same_host = host+ .is_some_and(|h| origin == format!("http://{h}") || origin == format!("https://{h}"));+ own || same_host || self.extra_origins.iter().any(|o| o == origin)+ }+}++/// Reads the token file, or writes a new random one. Falls back to an in-memory token.+pub fn load_or_create(data_dir: &Path) -> String {+ let path = data_dir.join(TOKEN_FILE);+ if let Ok(t) = std::fs::read_to_string(&path) {+ let t = t.trim().to_string();+ if t.len() >= 16 {+ return t;+ }+ }+ let token = format!(+ "{}{}",+ uuid::Uuid::new_v4().simple(),+ uuid::Uuid::new_v4().simple()+ );+ let _ = std::fs::create_dir_all(data_dir);+ if let Err(e) = write_private(&path, &token) {+ tracing::warn!(error = %e, "could not save the API token; it changes on restart");+ }+ token+}++fn write_private(path: &Path, contents: &str) -> std::io::Result<()> {+ use std::io::Write;+ let mut opts = std::fs::OpenOptions::new();+ opts.write(true).create(true).truncate(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ opts.mode(0o600);+ }+ let mut f = opts.open(path)?;+ f.write_all(contents.as_bytes())?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;+ }+ Ok(())+}++fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {+ if a.len() != b.len() {+ return false;+ }+ a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0+}++fn is_loopback_host(host: &str) -> bool {+ let name = match host.strip_prefix('[') {+ Some(rest) => rest.split(']').next().unwrap_or(""),+ None => host.rsplit_once(':').map(|(h, _)| h).unwrap_or(host),+ };+ name.eq_ignore_ascii_case("localhost")+ || name.parse::<IpAddr>().is_ok_and(|ip| ip.is_loopback())+}++/// Paths that never need the token: health, the login endpoints themselves, the OAuth redirect+/// (the provider's page sends the browser there) and the MCP endpoints, which carry their own+/// per-turn tokens.+fn exempt(path: &str) -> bool {+ path == "/api/health"+ || path.starts_with("/api/auth/")+ || path == "/api/mcp/oauth/callback"+ || path.starts_with("/api/mcp/permission/")+ || path.starts_with("/api/mcp/gateway")+}++fn header_str(headers: &HeaderMap, name: impl header::AsHeaderName) -> Option<&str> {+ headers.get(name).and_then(|v| v.to_str().ok())+}++/// Whether the request comes from this machine, not through a proxy, to a loopback name.+pub fn is_local(headers: &HeaderMap, peer: Option<IpAddr>) -> bool {+ let forwarded = [+ "forwarded",+ "x-forwarded-for",+ "x-forwarded-host",+ "x-real-ip",+ ]+ .iter()+ .any(|h| headers.contains_key(*h));+ let host_ok = header_str(headers, header::HOST).is_none_or(is_loopback_host);+ peer.is_none_or(|ip| ip.is_loopback() || ip.to_canonical().is_loopback())+ && !forwarded+ && host_ok+}++fn cookie_token(headers: &HeaderMap) -> Option<&str> {+ headers+ .get_all(header::COOKIE)+ .iter()+ .filter_map(|v| v.to_str().ok())+ .flat_map(|v| v.split(';'))+ .find_map(|c| {+ c.trim()+ .strip_prefix(COOKIE)+ .and_then(|r| r.strip_prefix('='))+ })+}++fn bearer(headers: &HeaderMap) -> Option<&str> {+ header_str(headers, header::AUTHORIZATION)+ .and_then(|v| v.strip_prefix("Bearer "))+ .map(str::trim)+}++fn presented_token_ok(api: &ApiToken, headers: &HeaderMap) -> bool {+ bearer(headers).is_some_and(|t| api.matches(t))+ || cookie_token(headers).is_some_and(|t| api.matches(t))+}++fn needs_token(api: &ApiToken, headers: &HeaderMap, peer: Option<IpAddr>) -> bool {+ match api.require {+ Require::Never => false,+ Require::Always => true,+ Require::Auto => !is_local(headers, peer),+ }+}++fn deny(status: StatusCode, msg: &str) -> Response {+ (status, Json(json!({ "error": msg }))).into_response()+}++/// Origin check, CORS for allowed origins, and the token check, for every `/api` request.+pub async fn guard(State(state): State<AppState>, req: Request, next: Next) -> Response {+ let path = req.uri().path().to_string();+ if !path.starts_with("/api/") && path != "/api" {+ return next.run(req).await;+ }+ let api = state.api_token.clone();+ let headers = req.headers().clone();+ let peer = req+ .extensions()+ .get::<ConnectInfo<SocketAddr>>()+ .map(|c| c.0.ip());+ let host = header_str(&headers, header::HOST);+ let origin = header_str(&headers, header::ORIGIN).map(str::to_string);++ if let Some(o) = &origin {+ if !api.origin_allowed(o, host) {+ return deny(StatusCode::FORBIDDEN, "origin not allowed");+ }+ }+ let preflight = req.method() == Method::OPTIONS+ && headers.contains_key(header::ACCESS_CONTROL_REQUEST_METHOD);+ let mut resp = if preflight {+ StatusCode::NO_CONTENT.into_response()+ } else if !exempt(&path)+ && needs_token(&api, &headers, peer)+ && !presented_token_ok(&api, &headers)+ {+ deny(StatusCode::UNAUTHORIZED, "API token required")+ } else {+ next.run(req).await+ };+ if let Some(o) = origin.and_then(|o| HeaderValue::from_str(&o).ok()) {+ let h = resp.headers_mut();+ h.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, o);+ h.insert(+ header::ACCESS_CONTROL_ALLOW_CREDENTIALS,+ HeaderValue::from_static("true"),+ );+ h.append(header::VARY, HeaderValue::from_static("Origin"));+ if preflight {+ h.insert(+ header::ACCESS_CONTROL_ALLOW_METHODS,+ HeaderValue::from_static("GET, POST, PUT, PATCH, DELETE, OPTIONS"),+ );+ h.insert(+ header::ACCESS_CONTROL_ALLOW_HEADERS,+ HeaderValue::from_static("authorization, content-type"),+ );+ h.insert(+ header::ACCESS_CONTROL_MAX_AGE,+ HeaderValue::from_static("600"),+ );+ }+ }+ resp+}++/// `GET /api/auth/status`: `{auth_required, authenticated}` for this request.+pub async fn status(State(state): State<AppState>, req: Request) -> Response {+ let peer = req+ .extensions()+ .get::<ConnectInfo<SocketAddr>>()+ .map(|c| c.0.ip());+ let headers = req.headers();+ let required = needs_token(&state.api_token, headers, peer);+ let authenticated = !required || presented_token_ok(&state.api_token, headers);+ Json(json!({ "auth_required": required, "authenticated": authenticated })).into_response()+}++#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+pub struct SessionBody {+ token: String,+}++fn session_cookie(value: &str, max_age: u64, secure: bool) -> HeaderValue {+ let secure = if secure { "; Secure" } else { "" };+ HeaderValue::from_str(&format!(+ "{COOKIE}={value}; HttpOnly; SameSite=Strict; Path=/; Max-Age={max_age}{secure}"+ ))+ .unwrap_or_else(|_| HeaderValue::from_static("kwnt_token=; Max-Age=0; Path=/"))+}++fn is_https(headers: &HeaderMap) -> bool {+ header_str(headers, "x-forwarded-proto").is_some_and(|p| p.eq_ignore_ascii_case("https"))+}++/// `POST /api/auth/session {token}`: checks the token and sets the `kwnt_token` cookie+/// (HttpOnly, SameSite=Strict), which EventSource and the browser WebSocket then send.+pub async fn create_session(+ State(state): State<AppState>,+ headers: HeaderMap,+ Json(body): Json<SessionBody>,+) -> Response {+ let token = body.token.trim();+ if !state.api_token.matches(token) {+ // A wrong guess costs a little time+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;+ return deny(StatusCode::UNAUTHORIZED, "wrong token");+ }+ let mut resp = StatusCode::NO_CONTENT.into_response();+ resp.headers_mut().insert(+ header::SET_COOKIE,+ session_cookie(token, 31_536_000, is_https(&headers)),+ );+ resp.headers_mut()+ .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));+ resp+}++/// `DELETE /api/auth/session`: clears the cookie.+pub async fn delete_session(headers: HeaderMap) -> Response {+ let mut resp = StatusCode::NO_CONTENT.into_response();+ resp.headers_mut().insert(+ header::SET_COOKIE,+ session_cookie("", 0, is_https(&headers)),+ );+ resp+}++#[cfg(test)]+mod tests {+ use super::*;++ fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap {+ let mut h = HeaderMap::new();+ for (k, v) in pairs {+ h.append(*k, HeaderValue::from_str(v).unwrap());+ }+ h+ }++ #[test]+ fn local_needs_loopback_peer_and_host_and_no_proxy() {+ let lo: Option<IpAddr> = Some("127.0.0.1".parse().unwrap());+ let remote: Option<IpAddr> = Some("203.0.113.9".parse().unwrap());+ assert!(is_local(&headers(&[("host", "127.0.0.1:3000")]), lo));+ assert!(is_local(&headers(&[("host", "localhost:3000")]), lo));+ assert!(is_local(+ &headers(&[("host", "[::1]:3000")]),+ Some("::1".parse().unwrap())+ ));+ assert!(is_local(&headers(&[]), None));+ assert!(!is_local(&headers(&[("host", "127.0.0.1:3000")]), remote));+ // DNS rebinding: loopback peer, foreign name+ assert!(!is_local(&headers(&[("host", "evil.example:3000")]), lo));+ // A reverse proxy on the same machine+ assert!(!is_local(+ &headers(&[+ ("host", "localhost:3000"),+ ("x-forwarded-for", "203.0.113.9")+ ]),+ lo+ ));+ assert!(!is_local(+ &headers(&[("host", "127.0.0.1.evil.example")]),+ lo+ ));+ }++ #[test]+ fn origins() {+ let api = ApiToken::for_tests("t".repeat(32).as_str(), Require::Auto, 3000);+ assert!(api.origin_allowed("http://localhost:3000", None));+ assert!(api.origin_allowed("http://127.0.0.1:5199/", None));+ assert!(api.origin_allowed("https://kwnt.example.com", Some("kwnt.example.com")));+ assert!(!api.origin_allowed("https://evil.example", Some("kwnt.example.com")));+ assert!(!api.origin_allowed("http://localhost:3001", Some("localhost:3000")));+ assert!(!api.origin_allowed("null", None));+ }++ #[test]+ fn tokens_and_cookies() {+ let api = ApiToken::for_tests("abcdefghijklmnopqrstuvwxyz012345", Require::Auto, 3000);+ assert!(presented_token_ok(+ &api,+ &headers(&[("authorization", "Bearer abcdefghijklmnopqrstuvwxyz012345")])+ ));+ assert!(presented_token_ok(+ &api,+ &headers(&[("cookie", "a=b; kwnt_token=abcdefghijklmnopqrstuvwxyz012345")])+ ));+ assert!(!presented_token_ok(+ &api,+ &headers(&[("cookie", "kwnt_token=abcdefghijklmnopqrstuvwxyz01234")])+ ));+ assert!(!presented_token_ok(+ &api,+ &headers(&[("authorization", "Basic abc")])+ ));+ assert!(!format!("{api:?}").contains("abcdef"));+ }++ #[test]+ fn token_file_is_private_and_stable() {+ let dir = tempfile::tempdir().unwrap();+ let a = load_or_create(dir.path());+ assert_eq!(a.len(), 64);+ assert_eq!(load_or_create(dir.path()), a);+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let mode = std::fs::metadata(dir.path().join(TOKEN_FILE))+ .unwrap()+ .permissions()+ .mode();+ assert_eq!(mode & 0o777, 0o600);+ }+ }+}diff --git a/src/server/mod.rs b/src/server/mod.rsindex 8beb1f29..c1a774f0 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -5,6 +5,9 @@ pub mod browser_stream;pub mod mcp_oauth;pub mod mcp_routes;pub mod mcp_runtime;+pub mod profile_routes;+pub mod profile_turn;+pub mod auth;use crate::broker::PermissionBroker;use crate::config::Config;@@ -21,7 +24,6 @@ use std::collections::HashMap;use std::sync::Arc;use tokio::sync::{broadcast, Mutex};use tokio_util::sync::CancellationToken;-use tower_http::cors::{Any, CorsLayer};#[derive(Clone)]pub struct AppState {@@ -38,6 +40,10 @@ pub struct AppState {/// Live claude CLI turns whose MCP permission prompts kwnt answers, by URL token.pub mcp_sessions: Arc<Mutex<HashMap<String, mcp_runtime::PermissionSession>>>,pub mcp_oauth: Arc<mcp_oauth::OAuthState>,+ /// LLM profiles: sign-in checks and in-app logins.+ pub profiles: Arc<crate::profiles::ProfileManager>,+ /// API token for requests from other machines (see `auth`).+ pub api_token: Arc<auth::ApiToken>,}impl AppState {@@ -51,6 +57,8 @@ impl AppState {let (event_sender, _) = broadcast::channel(128);let sandbox_manager = Arc::new(SandboxManager::new());let browser_controllers = Arc::new(Mutex::new(HashMap::new()));+ let profiles = Arc::new(crate::profiles::ProfileManager::new(config.data_dir.clone()));+ let api_token = Arc::new(auth::ApiToken::load(&config));let browser_service = Arc::new(crate::sandbox::service::BrowserService::new(config.data_dir.clone(), config.browser_cdp_url.clone()));Self {config,@@ -65,6 +73,8 @@ impl AppState {browser_service,mcp_sessions: Arc::new(Mutex::new(HashMap::new())),mcp_oauth: Arc::new(mcp_oauth::OAuthState::default()),+ profiles,+ api_token,}}@@ -76,13 +86,20 @@ impl AppState {}pub fn create_router(state: AppState) -> Router {- let cors = CorsLayer::new()- .allow_origin(Any)- .allow_methods(Any)- .allow_headers(Any);-Router::new().route("/api/health", get(routes::health))+ .route("/api/auth/status", get(auth::status))+ .route("/api/auth/session", post(auth::create_session).delete(auth::delete_session))+ .route("/api/profiles", get(profile_routes::list).post(profile_routes::create))+ .route("/api/profiles/:id", axum::routing::patch(profile_routes::update).delete(profile_routes::remove))+ .route("/api/profiles/:id/key", put(profile_routes::set_key).delete(profile_routes::delete_key))+ .route("/api/profiles/:id/login", post(profile_routes::start_login))+ .route(+ "/api/profiles/:id/login/:flow_id",+ get(profile_routes::get_login).delete(profile_routes::cancel_login),+ )+ .route("/api/profiles/:id/login/:flow_id/code", post(profile_routes::submit_login_code))+ .route("/api/profiles/:id/logout", post(profile_routes::logout)).route("/api/laya/status", get(routes::laya_status)).route("/api/kwants", get(routes::list_kwants).post(routes::create_kwant)).route("/api/kwants/:id", put(routes::update_kwant))@@ -121,6 +138,6 @@ pub fn create_router(state: AppState) -> Router {.route("/api/mcp/gateway/grok", post(mcp_runtime::gateway_grok_endpoint)).route("/api/events", get(sse::sse_handler)).fallback(crate::embedded::static_handler)- .layer(cors)+ .layer(axum::middleware::from_fn_with_state(state.clone(), auth::guard)).with_state(state)}diff --git a/src/server/profile_routes.rs b/src/server/profile_routes.rsnew file mode 100644index 00000000..fb1ea984--- /dev/null+++ b/src/server/profile_routes.rs@@ -0,0 +1,528 @@+//! `/api/profiles`: LLM accounts per engine. API keys are write-only: no response ever carries+//! one, only `has_key`.++use super::AppState;+use crate::db::models::{LlmProfile, LlmProfilePatch, NewLlmProfile};+use crate::profiles::login::LoginView;+use crate::profiles::{+ clean_key, clean_name, create_private_dir, managed_home, validate_user_home, Engine,+ ProfileStatus,+};+use axum::{+ extract::{Path, State},+ http::StatusCode,+ response::{IntoResponse, Response},+ Json,+};+use serde::{Deserialize, Serialize};+use serde_json::json;+use std::collections::HashSet;+use std::time::Duration;++/// Most profiles one engine may have.+const MAX_PER_ENGINE: usize = 20;++fn err(status: StatusCode, msg: impl Into<String>) -> Response {+ (status, Json(json!({ "error": msg.into() }))).into_response()+}++fn db_err(e: impl std::fmt::Display) -> Response {+ let text = e.to_string();+ if text.contains("UNIQUE") {+ return err(+ StatusCode::CONFLICT,+ "a profile with this name or home_dir already exists",+ );+ }+ tracing::warn!(error = %text, "profile db error");+ err(StatusCode::INTERNAL_SERVER_ERROR, "database error")+}++#[derive(Debug, Serialize)]+pub struct ProfileOut {+ pub id: String,+ pub engine: String,+ pub name: String,+ pub kind: String,+ pub enabled: bool,+ pub is_default: bool,+ pub priority: i64,+ /// The config dir a `cli_home` profile runs with (kwnt-managed when not picked).+ pub home_dir: Option<String>,+ pub has_key: bool,+ pub signed_in: Option<bool>,+ pub account_label: Option<String>,+ pub limited_until: Option<chrono::DateTime<chrono::Utc>>,+ /// "quota" or "auth" from the last refused turn.+ pub last_error: Option<String>,+}++/// Profiles that count as signed in through a key: their own, or for a system profile the+/// engine's Settings key or env key, as before profiles.+async fn keyed_ids(state: &AppState, profiles: &[LlmProfile]) -> HashSet<String> {+ let mut ids = state.db.profile_ids_with_key().await.unwrap_or_default();+ for p in profiles.iter().filter(|p| p.kind == "system") {+ let Some(engine) = Engine::parse(&p.engine) else {+ continue;+ };+ let setting = state+ .db+ .get_setting(engine.key_setting())+ .await+ .ok()+ .flatten()+ .is_some_and(|k| !k.is_empty());+ let env = engine+ .credential_env()+ .first()+ .and_then(std::env::var_os)+ .is_some_and(|v| !v.is_empty());+ if setting || env {+ ids.insert(p.id.clone());+ }+ }+ ids+}++async fn views(state: &AppState, profiles: Vec<LlmProfile>) -> Vec<ProfileOut> {+ let own_keys = state.db.profile_ids_with_key().await.unwrap_or_default();+ let keyed = keyed_ids(state, &profiles).await;+ let states = state.db.list_profile_states().await.unwrap_or_default();+ let statuses = state.profiles.statuses(&profiles, &keyed).await;+ profiles+ .into_iter()+ .map(|p| {+ let st = states.get(&p.id);+ let status = statuses.get(&p.id).cloned().unwrap_or_default();+ ProfileOut {+ home_dir: state+ .profiles+ .home_of(&p)+ .map(|h| h.to_string_lossy().into_owned()),+ has_key: own_keys.contains(&p.id),+ signed_in: status.signed_in,+ account_label: status.account_label,+ limited_until: st+ .and_then(|s| s.limited_until)+ .filter(|t| *t > chrono::Utc::now()),+ last_error: st.and_then(|s| s.last_error.clone()),+ id: p.id,+ engine: p.engine,+ name: p.name,+ kind: p.kind,+ enabled: p.enabled,+ is_default: p.is_default,+ priority: p.priority,+ }+ })+ .collect()+}++async fn view_of(state: &AppState, id: &str) -> Response {+ match state.db.get_profile(id).await {+ Ok(Some(p)) => Json(views(state, vec![p]).await.pop()).into_response(),+ Ok(None) => err(StatusCode::NOT_FOUND, "no such profile"),+ Err(e) => db_err(e),+ }+}++#[allow(clippy::result_large_err)]+async fn load(state: &AppState, id: &str) -> Result<LlmProfile, Response> {+ match state.db.get_profile(id).await {+ Ok(Some(p)) => Ok(p),+ Ok(None) => Err(err(StatusCode::NOT_FOUND, "no such profile")),+ Err(e) => Err(db_err(e)),+ }+}++/// `GET /api/profiles`+pub async fn list(State(state): State<AppState>) -> Response {+ match state.db.list_profiles().await {+ Ok(profiles) => Json(views(&state, profiles).await).into_response(),+ Err(e) => db_err(e),+ }+}++#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+pub struct CreateBody {+ engine: String,+ name: String,+ kind: String,+ home_dir: Option<String>,+ priority: Option<i64>,+ enabled: Option<bool>,+ is_default: Option<bool>,+ api_key: Option<String>,+}++/// `POST /api/profiles`+pub async fn create(State(state): State<AppState>, Json(body): Json<CreateBody>) -> Response {+ let Some(engine) = Engine::parse(&body.engine) else {+ return err(+ StatusCode::BAD_REQUEST,+ "engine must be claude, codex or grok",+ );+ };+ let name = match clean_name(&body.name) {+ Ok(n) => n,+ Err(e) => return err(StatusCode::BAD_REQUEST, e),+ };+ let key = match (body.kind.as_str(), body.api_key.as_deref()) {+ ("api_key", Some(k)) => match clean_key(k) {+ Ok(k) => Some(k),+ Err(e) => return err(StatusCode::BAD_REQUEST, e),+ },+ ("api_key", None) => None,+ ("cli_home", Some(_)) => {+ return err(+ StatusCode::BAD_REQUEST,+ "api_key only goes with kind api_key",+ )+ }+ ("cli_home", None) => None,+ _ => return err(StatusCode::BAD_REQUEST, "kind must be cli_home or api_key"),+ };+ let all = match state.db.list_profiles().await {+ Ok(a) => a,+ Err(e) => return db_err(e),+ };+ if all.iter().filter(|p| p.engine == engine.as_str()).count() >= MAX_PER_ENGINE {+ return err(StatusCode::BAD_REQUEST, "too many profiles for this engine");+ }+ let home_dir = match (body.kind.as_str(), body.home_dir.as_deref()) {+ ("cli_home", Some(raw)) => {+ let others: Vec<String> = all+ .iter()+ .filter_map(|p| state.profiles.home_of(p))+ .map(|h| h.to_string_lossy().into_owned())+ .collect();+ match validate_user_home(raw, engine, &others) {+ Ok(p) => Some(p.to_string_lossy().into_owned()),+ Err(e) => return err(StatusCode::BAD_REQUEST, e),+ }+ }+ ("api_key", Some(_)) => {+ return err(+ StatusCode::BAD_REQUEST,+ "home_dir only goes with kind cli_home",+ )+ }+ _ => None,+ };+ let input = NewLlmProfile {+ engine: engine.as_str().into(),+ name,+ kind: body.kind.clone(),+ home_dir: home_dir.clone(),+ priority: body.priority.unwrap_or(100).clamp(0, 10_000),+ enabled: body.enabled.unwrap_or(true),+ is_default: body.is_default.unwrap_or(false),+ };+ let profile = match state.db.create_profile(&input).await {+ Ok(p) => p,+ Err(e) => return db_err(e),+ };+ if body.kind == "cli_home" && home_dir.is_none() {+ if let Err(e) = create_private_dir(&managed_home(&state.profiles.data_dir, &profile.id)) {+ tracing::warn!(error = %e, "could not create a profile home");+ let _ = state.db.delete_profile(&profile.id).await;+ return err(+ StatusCode::INTERNAL_SERVER_ERROR,+ "could not create the profile's home dir",+ );+ }+ }+ if let Some(key) = key {+ if let Err(e) = state.db.set_profile_key(&profile.id, &key).await {+ let _ = state.db.delete_profile(&profile.id).await;+ return db_err(e);+ }+ }+ let mut resp = view_of(&state, &profile.id).await;+ *resp.status_mut() = StatusCode::CREATED;+ resp+}++#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+pub struct PatchBody {+ name: Option<String>,+ priority: Option<i64>,+ enabled: Option<bool>,+ is_default: Option<bool>,+}++/// `PATCH /api/profiles/:id`+pub async fn update(+ State(state): State<AppState>,+ Path(id): Path<String>,+ Json(body): Json<PatchBody>,+) -> Response {+ let existing = match load(&state, &id).await {+ Ok(p) => p,+ Err(r) => return r,+ };+ let name = match body.name.as_deref().map(clean_name).transpose() {+ Ok(n) => n,+ Err(e) => return err(StatusCode::BAD_REQUEST, e),+ };+ if body.is_default == Some(false) && existing.is_default {+ return err(+ StatusCode::BAD_REQUEST,+ "make another profile the default instead",+ );+ }+ if body.enabled == Some(false) && (existing.is_default || body.is_default == Some(true)) {+ return err(+ StatusCode::BAD_REQUEST,+ "the default profile can't be disabled",+ );+ }+ let patch = LlmProfilePatch {+ name,+ priority: body.priority.map(|p| p.clamp(0, 10_000)),+ enabled: body.enabled,+ is_default: body.is_default,+ };+ match state.db.update_profile(&id, &patch).await {+ Ok(Some(_)) => view_of(&state, &id).await,+ Ok(None) => err(StatusCode::NOT_FOUND, "no such profile"),+ Err(e) => db_err(e),+ }+}++/// `DELETE /api/profiles/:id`. Leaves the home dir on disk: it may hold the user's own login.+pub async fn remove(State(state): State<AppState>, Path(id): Path<String>) -> Response {+ let existing = match load(&state, &id).await {+ Ok(p) => p,+ Err(r) => return r,+ };+ if existing.kind == "system" {+ return err(+ StatusCode::BAD_REQUEST,+ "the system profile can't be deleted",+ );+ }+ state.profiles.logins.cancel_profile(&id);+ match state.db.delete_profile(&id).await {+ Ok(_) => {+ state.profiles.invalidate(&id);+ StatusCode::NO_CONTENT.into_response()+ }+ Err(e) => db_err(e),+ }+}++#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+pub struct KeyBody {+ api_key: String,+}++/// `PUT /api/profiles/:id/key`+pub async fn set_key(+ State(state): State<AppState>,+ Path(id): Path<String>,+ Json(body): Json<KeyBody>,+) -> Response {+ let existing = match load(&state, &id).await {+ Ok(p) => p,+ Err(r) => return r,+ };+ if existing.kind != "api_key" {+ return err(StatusCode::BAD_REQUEST, "only api_key profiles hold a key");+ }+ let key = match clean_key(&body.api_key) {+ Ok(k) => k,+ Err(e) => return err(StatusCode::BAD_REQUEST, e),+ };+ if let Err(e) = state.db.set_profile_key(&id, &key).await {+ return db_err(e);+ }+ let _ = state.db.clear_profile_state(&id).await;+ state.profiles.invalidate(&id);+ StatusCode::NO_CONTENT.into_response()+}++/// `DELETE /api/profiles/:id/key`+pub async fn delete_key(State(state): State<AppState>, Path(id): Path<String>) -> Response {+ if let Err(r) = load(&state, &id).await {+ return r;+ }+ match state.db.delete_profile_key(&id).await {+ Ok(_) => {+ state.profiles.invalidate(&id);+ StatusCode::NO_CONTENT.into_response()+ }+ Err(e) => db_err(e),+ }+}++#[allow(clippy::result_large_err)]+async fn cli_home_profile(+ state: &AppState,+ id: &str,+) -> Result<(LlmProfile, Engine, std::path::PathBuf), Response> {+ let p = load(state, id).await?;+ let engine =+ Engine::parse(&p.engine).ok_or_else(|| err(StatusCode::BAD_REQUEST, "unknown engine"))?;+ match state.profiles.home_of(&p) {+ Some(home) if p.kind == "cli_home" => Ok((p, engine, home)),+ _ => Err(err(+ StatusCode::BAD_REQUEST,+ "sign-in is only for cli_home profiles",+ )),+ }+}++fn login_for(view: Option<LoginView>, profile_id: &str) -> Response {+ match view {+ Some(v) if v.profile_id == profile_id => Json(v).into_response(),+ _ => err(StatusCode::NOT_FOUND, "no such sign-in"),+ }+}++/// `POST /api/profiles/:id/login`: starts the engine CLI's own sign-in with this profile's home.+pub async fn start_login(State(state): State<AppState>, Path(id): Path<String>) -> Response {+ let (p, engine, home) = match cli_home_profile(&state, &id).await {+ Ok(x) => x,+ Err(r) => return r,+ };+ let Some(bin) = crate::drivers::find_cli_binary(engine.as_str()) else {+ return err(+ StatusCode::BAD_REQUEST,+ format!("the {} CLI is not installed", engine.as_str()),+ );+ };+ if let Err(e) = create_private_dir(&home) {+ tracing::warn!(error = %e, "could not create a profile home");+ return err(+ StatusCode::INTERNAL_SERVER_ERROR,+ "could not create the profile's home dir",+ );+ }+ let db = state.db.clone();+ let manager = state.profiles.clone();+ let on_success: crate::profiles::login::OnSuccess =+ std::sync::Arc::new(move |profile_id: String| {+ let db = db.clone();+ let manager = manager.clone();+ tokio::spawn(async move {+ let _ = db.clear_profile_state(&profile_id).await;+ manager.invalidate(&profile_id);+ });+ });+ match state+ .profiles+ .logins+ .start(engine, &bin, &p.id, &home, on_success)+ .await+ {+ Ok(view) => Json(view).into_response(),+ Err(e) => err(StatusCode::BAD_GATEWAY, e),+ }+}++/// `GET /api/profiles/:id/login/:flow_id`+pub async fn get_login(+ State(state): State<AppState>,+ Path((id, flow_id)): Path<(String, String)>,+) -> Response {+ login_for(state.profiles.logins.get(&flow_id), &id)+}++#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+pub struct CodeBody {+ code: String,+}++/// `POST /api/profiles/:id/login/:flow_id/code`: the code Claude's sign-in page shows.+pub async fn submit_login_code(+ State(state): State<AppState>,+ Path((id, flow_id)): Path<(String, String)>,+ Json(body): Json<CodeBody>,+) -> Response {+ if state+ .profiles+ .logins+ .get(&flow_id)+ .is_none_or(|v| v.profile_id != id)+ {+ return err(StatusCode::NOT_FOUND, "no such sign-in");+ }+ match state+ .profiles+ .logins+ .submit_code(&flow_id, &body.code)+ .await+ {+ Ok(view) => Json(view).into_response(),+ Err(e) => err(StatusCode::BAD_REQUEST, e),+ }+}++/// `DELETE /api/profiles/:id/login/:flow_id`+pub async fn cancel_login(+ State(state): State<AppState>,+ Path((id, flow_id)): Path<(String, String)>,+) -> Response {+ if state+ .profiles+ .logins+ .get(&flow_id)+ .is_none_or(|v| v.profile_id != id)+ {+ return err(StatusCode::NOT_FOUND, "no such sign-in");+ }+ state.profiles.logins.cancel(&flow_id);+ StatusCode::NO_CONTENT.into_response()+}++/// `POST /api/profiles/:id/logout`: signs the profile's home out with the engine CLI.+pub async fn logout(State(state): State<AppState>, Path(id): Path<String>) -> Response {+ let (p, engine, home) = match cli_home_profile(&state, &id).await {+ Ok(x) => x,+ Err(r) => return r,+ };+ state.profiles.logins.cancel_profile(&p.id);+ let ok = match engine {+ Engine::Grok => {+ let file = home.join("auth.json");+ !file.exists() || std::fs::remove_file(file).is_ok()+ }+ _ => {+ let Some(bin) = crate::drivers::find_cli_binary(engine.as_str()) else {+ return err(+ StatusCode::BAD_REQUEST,+ format!("the {} CLI is not installed", engine.as_str()),+ );+ };+ let mut cmd = tokio::process::Command::new(bin);+ match engine {+ Engine::Claude => cmd.args(["auth", "logout"]),+ _ => cmd.arg("logout"),+ };+ crate::profiles::CliEnv::for_home(engine, &home).apply(&mut cmd);+ cmd.stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .kill_on_drop(true);+ matches!(tokio::time::timeout(Duration::from_secs(15), cmd.status()).await, Ok(Ok(s)) if s.success())+ }+ };+ state.profiles.set_status(+ &p.id,+ ProfileStatus {+ signed_in: Some(false),+ account_label: None,+ },+ );+ if ok {+ StatusCode::NO_CONTENT.into_response()+ } else {+ state.profiles.invalidate(&p.id);+ err(StatusCode::BAD_GATEWAY, "sign-out did not finish")+ }+}diff --git a/src/server/profile_turn.rs b/src/server/profile_turn.rsnew file mode 100644index 00000000..f5d13b72--- /dev/null+++ b/src/server/profile_turn.rs@@ -0,0 +1,134 @@+//! Which profile a kwant turn runs on, the driver for it, and the chat notices when a turn+//! moves to another profile or every profile is out.++use super::AppState;+use crate::db::models::LlmProfile;+use crate::drivers::{find_cli_binary, resolve_driver_for_model, ApiDriver, CliDriver, Driver};+use crate::profiles::{+ failover_order, Availability, Engine, FailClass, ProfileStatus, ProviderFailure,+};++/// Profiles to try for a turn on `engine`, in order. Empty when the model has no profiles+/// (e.g. Ollama) or the engine has none enabled: the turn then runs as before profiles.+pub async fn plan(state: &AppState, engine: Option<Engine>, kwant_id: &str) -> Vec<LlmProfile> {+ let Some(engine) = engine else {+ return Vec::new();+ };+ let db = &state.db;+ let (Ok(profiles), Ok(binding), Ok(states), Ok(with_key)) = (+ db.list_profiles().await,+ db.get_kwant_binding(kwant_id).await,+ db.list_profile_states().await,+ db.profile_ids_with_key().await,+ ) else {+ return Vec::new();+ };+ let (bound, failover) = binding.unwrap_or((None, true));+ let avail = Availability {+ states,+ with_key,+ signed_out: state.profiles.signed_out(),+ };+ failover_order(+ &profiles,+ engine,+ bound.as_deref(),+ failover,+ &avail,+ chrono::Utc::now(),+ )+}++/// The driver for one attempt. `None` or the system profile: exactly the pre-profiles choice.+pub async fn driver_for(+ state: &AppState,+ profile: Option<&LlmProfile>,+ target_model: &str,+ configured_key: Option<String>,+ endpoint: Option<String>,+) -> Box<dyn Driver> {+ let Some(p) = profile.filter(|p| p.kind != "system") else {+ return resolve_driver_for_model(target_model, configured_key, endpoint);+ };+ let engine = Engine::parse(&p.engine).unwrap_or(Engine::Claude);+ if p.kind == "api_key" {+ let key = state+ .db+ .get_profile_key(&p.id)+ .await+ .ok()+ .flatten()+ .map(|k| k.0);+ return Box::new(ApiDriver::for_profile(key));+ }+ let home = state.profiles.home_of(p).unwrap_or_default();+ Box::new(+ CliDriver::new(+ find_cli_binary(engine.as_str()),+ Some(engine.as_str().into()),+ )+ .with_profile_home(engine, home),+ )+}++/// Remembers a refusal so failover skips the profile: until its quota resets, or until it is+/// signed in again.+pub async fn record_failure(state: &AppState, profile: &LlmProfile, failure: &ProviderFailure) {+ let until = (failure.class == FailClass::Quota)+ .then_some(failure.retry_at)+ .flatten();+ let _ = state+ .db+ .record_profile_failure(&profile.id, failure.class.as_str(), until)+ .await;+ if failure.class == FailClass::Auth && profile.kind != "api_key" {+ state.profiles.set_status(+ &profile.id,+ ProfileStatus {+ signed_in: Some(false),+ account_label: None,+ },+ );+ }+}++fn reason(failure: &ProviderFailure) -> String {+ match (failure.class, failure.retry_at) {+ (FailClass::Quota, Some(at)) => format!("is out of usage until {} UTC", at.format("%H:%M")),+ (FailClass::Quota, None) => "is out of usage".into(),+ _ => "is signed out or its key was rejected".into(),+ }+}++/// Shown while the turn moves on: "Work ran out of usage until 17:00 UTC; switching to Personal."+pub fn switch_notice(from: &LlmProfile, to: &LlmProfile, failure: &ProviderFailure) -> String {+ format!(+ "🔁 {} profile \"{}\" {}; switching to \"{}\".",+ from.engine,+ from.name,+ reason(failure),+ to.name+ )+}++/// The reply when every profile tried refused the turn.+pub fn give_up_notice(+ kwant_name: &str,+ last: &LlmProfile,+ failure: &ProviderFailure,+ tried: usize,+) -> String {+ let fix = match failure.class {+ FailClass::Quota => "Add another profile or wait for the limit to reset.",+ _ => "Sign in again (or update the key) under Settings → Profiles.",+ };+ let which = if tried > 1 {+ format!(+ "All {tried} {} profiles tried are unavailable; the last, \"{}\",",+ last.engine, last.name+ )+ } else {+ format!("The {} profile \"{}\"", last.engine, last.name)+ };+ format!("⚠️ [{kwant_name}] {which} {}. {fix}", reason(failure))+}diff --git a/src/server/routes.rs b/src/server/routes.rsindex a6110518..b42ca09b 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -2,7 +2,7 @@ use super::discussion;use super::AppState;use crate::broker::ApprovalDecision;use crate::db::models::*;-use crate::drivers::{find_cli_binary, resolve_driver_for_model, RoutingCandidate, RuntimeEvent, TurnInput};+use crate::drivers::{find_cli_binary, RoutingCandidate, RuntimeEvent, TurnInput};use crate::router::{parse_mentions_with_lookup, TagMention, TeamDecision};use axum::{extract::{Path, Query, State},@@ -39,10 +39,12 @@ pub async fn laya_status(State(state): State<AppState>) -> impl IntoResponse {Json(state.router.status())}-pub async fn list_kwants(State(state): State<AppState>) -> Result<Json<Vec<Kwant>>, StatusCode> {+pub async fn list_kwants(+ State(state): State<AppState>,+) -> Result<Json<Vec<KwantView>>, StatusCode> {state.db- .list_kwants()+ .kwant_views().await.map(Json).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)@@ -61,30 +63,114 @@ async fn validate_kwant_name(state: &AppState, name: &mut String, own_id: OptionOk(())}-pub async fn create_kwant(- State(state): State<AppState>,- Json(mut payload): Json<NewKwant>,-) -> Result<Json<Kwant>, StatusCode> {- validate_kwant_name(&state, &mut payload.name, None).await?;+/// `Some(None)` for an explicit JSON `null`, so "unset" and "leave as is" differ.+fn deserialize_some<'de, D, T>(d: D) -> Result<Option<T>, D::Error>+where+ D: serde::Deserializer<'de>,+ T: Deserialize<'de>,+{+ T::deserialize(d).map(Some)+}++/// Profile fields a kwant create or update may carry besides the kwant's own.+#[derive(Debug, Deserialize)]+pub struct ProfileBinding {+ /// A profile id, `null` for the engine default, absent to leave as is.+ #[serde(default, deserialize_with = "deserialize_some")]+ profile_id: Option<Option<String>>,+ profile_failover: Option<bool>,+}++#[derive(Debug, Deserialize)]+pub struct CreateKwantRequest {+ #[serde(flatten)]+ base: NewKwant,+ #[serde(flatten)]+ binding: ProfileBinding,+}++#[derive(Debug, Deserialize)]+pub struct UpdateKwantRequest {+ #[serde(flatten)]+ base: UpdateKwant,+ #[serde(flatten)]+ binding: ProfileBinding,+}++/// The pinned profile must exist and be for the engine of the kwant's model.+async fn check_binding(+ state: &AppState,+ binding: &ProfileBinding,+ preferred_model: &str,+) -> Result<(), StatusCode> {+ let Some(Some(id)) = &binding.profile_id else {+ return Ok(());+ };+ let profile = state+ .db+ .get_profile(id)+ .await+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?+ .ok_or(StatusCode::BAD_REQUEST)?;+ match crate::profiles::Engine::from_model(preferred_model) {+ Some(engine) if engine.as_str() != profile.engine => Err(StatusCode::BAD_REQUEST),+ _ => Ok(()),+ }+}++async fn save_binding(+ state: &AppState,+ kwant_id: &str,+ binding: &ProfileBinding,+) -> Result<(), StatusCode> {+ if binding.profile_id.is_none() && binding.profile_failover.is_none() {+ return Ok(());+ }+ let profile_id = binding.profile_id.as_ref().map(|p| p.as_deref());state.db- .create_kwant(&payload)+ .set_kwant_binding(kwant_id, profile_id, binding.profile_failover).await- .map(Json).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)}+async fn kwant_view_json(state: &AppState, id: &str) -> Result<Json<KwantView>, StatusCode> {+ match state.db.kwant_view(id).await {+ Ok(Some(v)) => Ok(Json(v)),+ Ok(None) => Err(StatusCode::NOT_FOUND),+ Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),+ }+}++pub async fn create_kwant(+ State(state): State<AppState>,+ Json(mut payload): Json<CreateKwantRequest>,+) -> Result<Json<KwantView>, StatusCode> {+ validate_kwant_name(&state, &mut payload.base.name, None).await?;+ check_binding(&state, &payload.binding, &payload.base.preferred_model).await?;+ let kwant = state+ .db+ .create_kwant(&payload.base)+ .await+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;+ save_binding(&state, &kwant.id, &payload.binding).await?;+ kwant_view_json(&state, &kwant.id).await+}+pub async fn update_kwant(State(state): State<AppState>,Path(id): Path<String>,- Json(mut payload): Json<UpdateKwant>,-) -> Result<Json<Kwant>, StatusCode> {- validate_kwant_name(&state, &mut payload.name, Some(&id)).await?;- match state.db.update_kwant(&id, &payload).await {- Ok(Some(kwant)) => Ok(Json(kwant)),- Ok(None) => Err(StatusCode::NOT_FOUND),- Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),+ Json(mut payload): Json<UpdateKwantRequest>,+) -> Result<Json<KwantView>, StatusCode> {+ validate_kwant_name(&state, &mut payload.base.name, Some(&id)).await?;+ check_binding(&state, &payload.binding, &payload.base.preferred_model).await?;+ match state.db.update_kwant(&id, &payload.base).await {+ Ok(Some(_)) => {}+ Ok(None) => return Err(StatusCode::NOT_FOUND),+ Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR),}+ save_binding(&state, &id, &payload.binding).await?;+ kwant_view_json(&state, &id).await}pub async fn list_channels(State(state): State<AppState>) -> Result<Json<Vec<Channel>>, StatusCode> {@@ -528,7 +614,60 @@ struct TurnOpts {/// Runs one kwant turn: picks model/effort, syncs the bot browser, streams the reply and saves it./// Returns the raw reply text, or `None` if the turn was cancelled or failed.-async fn run_kwant_turn(scope: &TurnScope, target_kwant: &Kwant, prompt: String, opts: TurnOpts) -> Option<String> {+async fn run_kwant_turn(+ scope: &TurnScope,+ target_kwant: &Kwant,+ prompt: String,+ opts: TurnOpts,+) -> Option<String> {+ let context_id = scope+ .channel_id+ .clone()+ .or_else(|| scope.kwant_id.clone())+ .unwrap_or_else(|| target_kwant.id.clone());+ let _ = scope.state.event_sender.send(RuntimeEvent::TurnStarted {+ kwant_id: target_kwant.id.clone(),+ context_id: Some(context_id.clone()),+ });+ // Sends turn_ended even if this future is dropped mid-turn+ let mut ended = TurnEndedGuard {+ sender: scope.state.event_sender.clone(),+ kwant_id: target_kwant.id.clone(),+ context_id,+ outcome: "cancelled",+ };+ let reply = run_kwant_turn_inner(scope, target_kwant, prompt, opts).await;+ ended.outcome = match (&reply, scope.cancel_token.is_cancelled()) {+ (Some(_), _) => "completed",+ (None, true) => "cancelled",+ (None, false) => "failed",+ };+ reply+}++struct TurnEndedGuard {+ sender: tokio::sync::broadcast::Sender<RuntimeEvent>,+ kwant_id: String,+ context_id: String,+ outcome: &'static str,+}++impl Drop for TurnEndedGuard {+ fn drop(&mut self) {+ let _ = self.sender.send(RuntimeEvent::TurnEnded {+ kwant_id: std::mem::take(&mut self.kwant_id),+ context_id: Some(std::mem::take(&mut self.context_id)),+ outcome: self.outcome.to_string(),+ });+ }+}++async fn run_kwant_turn_inner(+ scope: &TurnScope,+ target_kwant: &Kwant,+ prompt: String,+ opts: TurnOpts,+) -> Option<String> {let state = &scope.state;let event_broadcast = state.event_sender.clone();let db = state.db.clone();@@ -600,7 +739,7 @@ async fn run_kwant_turn(scope: &TurnScope, target_kwant: &Kwant, prompt: String,"🌐 Navigating bot browser to {}...",target_url)));- if let Some(ctrl) = get_or_create_browser_controller(&state, &sandbox_target).await {+ if let Some(ctrl) = get_or_create_browser_controller(state, &sandbox_target).await {match ctrl.navigate(&target_url).await {Ok(nav) => {let page_text = ctrl.extract_content().await.unwrap_or_default();@@ -667,16 +806,27 @@ async fn run_kwant_turn(scope: &TurnScope, target_kwant: &Kwant, prompt: String,}}- let driver = resolve_driver_for_model(&target_model, configured_key, endpoint);- let mcp_turn = super::mcp_runtime::prepare_turn(&state, &target_kwant, scope.workspace_dir.clone()).await;+ let engine = crate::profiles::Engine::from_model(&target_model);+ let candidates = super::profile_turn::plan(state, engine, &target_kwant.id).await;+ let attempts: Vec<Option<LlmProfile>> = if candidates.is_empty() {+ vec![None]+ } else {+ candidates.into_iter().map(Some).collect()+ };+ let mcp_turn =+ super::mcp_runtime::prepare_turn(state, target_kwant, scope.workspace_dir.clone())+ .await;let mcp_ctx = mcp_turn.as_ref().map(|(ctx, _)| ctx.clone());let turn_input = TurnInput {- browser_api_url: Some(format!("http://127.0.0.1:{}/api/sandbox/{}", state.config.port, sandbox_target)),+ browser_api_url: Some(format!(+ "http://127.0.0.1:{}/api/sandbox/{}",+ state.config.port, sandbox_target+ )),thread_id: context_id,kwant: target_kwant.clone(),prompt: final_prompt,history,- model_override: Some(target_model),+ model_override: Some(target_model.clone()),effort_level: Some(effort_level),team_context: scope.team_context.clone(),workspace_dir: scope.workspace_dir.clone(),@@ -690,42 +840,172 @@ async fn run_kwant_turn(scope: &TurnScope, target_kwant: &Kwant, prompt: String,mcp: mcp_ctx.clone(),};- let (driver_tx, mut driver_rx) = mpsc::channel(32);- let driver_task = tokio::spawn(async move {- driver.stream_turn(turn_input, driver_tx).await- });-+ let had_state = state.db.list_profile_states().await.unwrap_or_default();+ let turn_start = std::time::Instant::now();+ // Notices about profile switches, kept with the saved reply+ let mut notices: Vec<String> = Vec::new();let mut cancelled = false;- loop {- tokio::select! {- _ = cancel_token.cancelled() => {- cancelled = true;- driver_task.abort();- break;- }- event_opt = driver_rx.recv() => {- match event_opt {- Some(event) => {- let _ = event_broadcast.send(event);+ let mut driver_result = None;+ let mut gave_up: Option<String> = None;+ for (i, profile) in attempts.iter().enumerate() {+ let driver = super::profile_turn::driver_for(+ state,+ profile.as_ref(),+ &target_model,+ configured_key.clone(),+ endpoint.clone(),+ )+ .await;+ let input = turn_input.clone();+ let (driver_tx, mut driver_rx) = mpsc::channel(32);+ let driver_task =+ tokio::spawn(async move { driver.stream_turn(input, driver_tx).await });++ // The driver's TurnComplete is held back: it's re-sent with the kwant and profile,+ // or dropped when the turn moves to another profile.+ let mut held_complete = None;+ let mut side_effects = false;+ loop {+ tokio::select! {+ _ = cancel_token.cancelled() => {+ cancelled = true;+ driver_task.abort();+ break;+ }+ event_opt = driver_rx.recv() => {+ match event_opt {+ Some(RuntimeEvent::TurnComplete { tokens, duration_ms, .. }) => {+ held_complete = Some((tokens, duration_ms));+ }+ Some(event) => {+ let visible = match &event {+ RuntimeEvent::TextDelta(t) => !t.trim().is_empty(),+ RuntimeEvent::ToolCallPending { .. } | RuntimeEvent::ApprovalRequired { .. } => true,+ _ => false,+ };+ side_effects |= visible;+ let _ = event_broadcast.send(event);+ }+ None => break,}- None => break,}}}+ if cancelled {+ break;+ }+ let result = driver_task.await;+ let refused = match &result {+ Ok(Ok(out)) => out.failure.clone(),+ _ => None,+ };+ if let Some(failure) = refused {+ if let Some(p) = profile {+ super::profile_turn::record_failure(state, p, &failure).await;+ }+ let next = attempts.get(i + 1).and_then(|n| n.as_ref());+ if let (Some(from), Some(to), false) = (profile, next, side_effects) {+ let notice = super::profile_turn::switch_notice(from, to, &failure);+ let _ = event_broadcast.send(RuntimeEvent::ProfileSwitched {+ kwant_id: target_kwant.id.clone(),+ from_profile_id: from.id.clone(),+ from_name: from.name.clone(),+ to_profile_id: to.id.clone(),+ to_name: to.name.clone(),+ class: failure.class.as_str().into(),+ retry_at: failure.retry_at,+ });+ let _ = event_broadcast.send(RuntimeEvent::ThinkingDelta(notice.clone()));+ tracing::info!(kwant = %target_kwant.id, from = %from.id, to = %to.id, class = failure.class.as_str(), "turn moved to another profile");+ notices.push(notice);+ continue;+ }+ let text = match profile {+ Some(p) => {+ super::profile_turn::give_up_notice(&target_kwant.name, p, &failure, i + 1)+ }+ None => format!(+ "⚠️ [{}] The model provider refused the turn ({}). {}",+ target_kwant.name,+ failure.class.as_str(),+ failure.detail+ ),+ };+ let _ = event_broadcast.send(RuntimeEvent::TextDelta(text.clone()));+ let _ = event_broadcast.send(RuntimeEvent::TurnComplete {+ tokens: 0,+ duration_ms: turn_start.elapsed().as_millis() as u64,+ kwant_id: Some(target_kwant.id.clone()),+ profile_id: profile.as_ref().map(|p| p.id.clone()),+ });+ gave_up = Some(text);+ break;+ }+ if let Some(p) = profile {+ if had_state.contains_key(&p.id) && matches!(result, Ok(Ok(_))) {+ let _ = state.db.clear_profile_state(&p.id).await;+ }+ }+ match &result {+ Ok(Err(e)) => {+ let _ = event_broadcast.send(RuntimeEvent::Error {+ code: "driver_error".into(),+ message: e.to_string(),+ kwant_id: Some(target_kwant.id.clone()),+ });+ }+ Err(_) => {+ let _ = event_broadcast.send(RuntimeEvent::Error {+ code: "driver_crashed".into(),+ message: "the model driver stopped unexpectedly".into(),+ kwant_id: Some(target_kwant.id.clone()),+ });+ }+ Ok(Ok(_)) => {}+ }+ if let Some((tokens, duration_ms)) = held_complete {+ let _ = event_broadcast.send(RuntimeEvent::TurnComplete {+ tokens,+ duration_ms,+ kwant_id: Some(target_kwant.id.clone()),+ profile_id: profile.as_ref().map(|p| p.id.clone()),+ });+ }+ driver_result = Some(result);+ break;}-- let driver_result = if cancelled { None } else { Some(driver_task.await) };if let Some((_, token)) = &mcp_turn {super::mcp_runtime::finish_turn(&state, token).await;}let mcp_records = mcp_ctx.map(|c| c.take_records()).filter(|r| !r.is_empty());+ let with_notices = |reasoning: Option<String>| -> Option<String> {+ if notices.is_empty() {+ return reasoning;+ }+ Some(match reasoning {+ Some(r) => format!("{}\n{r}", notices.join("\n")),+ None => notices.join("\n"),+ })+ };if cancelled {let _ = event_broadcast.send(RuntimeEvent::ThinkingDelta("⏹️ Cancelled by user".into()));+ } else if let Some(text) = gave_up {+ let msg = NewMessage {+ channel_id: channel_id.clone(),+ direct_kwant_id: kwant_id.clone(),+ sender_role: "kwant".into(),+ sender_id: target_kwant.name.clone(),+ text,+ reasoning_content: with_notices(opts.label.clone()),+ tool_calls: None,+ tokens_used: 0,+ };+ let _ = db.insert_message(&msg).await;} else if let Some(Ok(Ok(output))) = driver_result {// Post-turn sync: If bot response outputs a URL, sync navigation so the user sees it in Sandbox VMif let Some(bot_url) = extract_url_from_text(&output.text) {- if let Some(ctrl) = get_or_create_browser_controller(&state, &sandbox_target).await {+ if let Some(ctrl) = get_or_create_browser_controller(state, &sandbox_target).await {let curr = ctrl.current_url.lock().await.clone().unwrap_or_default();if curr != bot_url && !bot_url.contains("localhost") && !bot_url.contains("127.0.0.1") {if let Ok(nav) = ctrl.navigate(&bot_url).await {@@ -749,14 +1029,17 @@ async fn run_kwant_turn(scope: &TurnScope, target_kwant: &Kwant, prompt: String,}let saved = match &opts.discussion {- None => Some((output.text.clone(), opts.label.clone().or(output.reasoning))),+ None => Some((+ output.text.clone(),+ with_notices(opts.label.clone().or(output.reasoning)),+ )),Some(question_label) => match discussion::parse_reply(&output.text) {discussion::Reply::Pass => None,discussion::Reply::AskUser(q) => match question_label {- Some(label) => Some((q, Some(label.clone()))),- None => Some((q, opts.label.clone())),+ Some(label) => Some((q, with_notices(Some(label.clone())))),+ None => Some((q, with_notices(opts.label.clone()))),},- discussion::Reply::Speak(t) => Some((t, opts.label.clone())),+ discussion::Reply::Speak(t) => Some((t, with_notices(opts.label.clone()))),},};if let Some((text, reasoning_content)) = saved {diff --git a/tests/driver_test.rs b/tests/driver_test.rsindex 510db659..e74cb50d 100644--- a/tests/driver_test.rs+++ b/tests/driver_test.rs@@ -44,6 +44,8 @@ impl Driver for TestDriver {.send(RuntimeEvent::TurnComplete {tokens: 42,duration_ms: 120,+ kwant_id: None,+ profile_id: None,}).await.unwrap();@@ -52,6 +54,7 @@ impl Driver for TestDriver {text: format!("Player says: {}", input.prompt),reasoning: Some("Calculating combo...".into()),tokens_used: 42,+ ..Default::default()})}}diff --git a/tests/mcp_oauth_test.rs b/tests/mcp_oauth_test.rsindex 94928af5..1bd64a40 100644--- a/tests/mcp_oauth_test.rs+++ b/tests/mcp_oauth_test.rs@@ -23,6 +23,8 @@ use tower::ServiceExt;const ORIGIN: &str = "https://kwnt.example.test";const HOST: &str = "kwnt.example.test";+/// kwnt is addressed by a public name here, so requests need the API token.+const TOKEN: &str = "test-token-0123456789abcdef";struct Env {app: Router,@@ -40,21 +42,38 @@ async fn env(options: oauth_mock::MockOptions) -> Env {let tmp = tempdir().unwrap();let db = Database::init(tmp.path()).await.unwrap();let config = Config { data_dir: tmp.path().to_path_buf(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };- let state = AppState::new(+ let mut state = AppState::new(config.clone(),db,ToolRunner::new(tmp.path().join("workspace")),PermissionBroker::new(),LayaRouter::new(config.laya_url.clone()),);- Env { app: create_router(state.clone()), state, mock, _tmp: tmp }+ state.api_token = Arc::new(kwnt::server::auth::ApiToken::for_tests(+ TOKEN,+ kwnt::server::auth::Require::Auto,+ config.port,+ ));+ Env {+ app: create_router(state.clone()),+ state,+ mock,+ _tmp: tmp,+ }}-async fn send(app: &Router, method: &str, uri: &str, body: Option<Value>, host: &str) -> (StatusCode, String) {+async fn send(+ app: &Router,+ method: &str,+ uri: &str,+ body: Option<Value>,+ host: &str,+) -> (StatusCode, String) {let req = Request::builder().method(method).uri(uri).header("host", host)+ .header("authorization", format!("Bearer {TOKEN}")).header("content-type", "application/json").body(body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty)).unwrap();@@ -314,6 +333,7 @@ async fn callback_reports_provider_errors_and_bad_state() {.uri(format!("/api/mcp/servers/{id}/oauth/start")).header("host", "127.0.0.1:7777").header("x-forwarded-host", HOST)+ .header("authorization", format!("Bearer {TOKEN}")).header("content-type", "application/json").body(Body::from(json!({"origin": ORIGIN}).to_string())).unwrap();diff --git a/tests/profile_failover_test.rs b/tests/profile_failover_test.rsnew file mode 100644index 00000000..eed2f9c5--- /dev/null+++ b/tests/profile_failover_test.rs@@ -0,0 +1,293 @@+//! A turn whose profile is out of usage moves to the engine's next profile, with a fake claude+//! CLI on PATH. Its own test binary: it changes PATH and the process env.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::Database,+ drivers::RuntimeEvent,+ router::LayaRouter,+ server::{create_router, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::time::Duration;+use tower::ServiceExt;++const FAKE_CLAUDE: &str = r#"#!/bin/sh+case "$1" in+ auth) echo '{"loggedIn":true,"email":"[email protected]"}'; exit 0 ;;+esac+if [ -f "$CLAUDE_CONFIG_DIR/out-of-usage" ]; then+ echo '{"type":"result","is_error":true,"num_turns":1,"result":"Claude AI usage limit reached|'"$FAKE_RESET"'"}'+ exit 1+fi+echo "{\"type\":\"result\",\"is_error\":false,\"num_turns\":1,\"result\":\"reply from $(basename "$CLAUDE_CONFIG_DIR") key=${ANTHROPIC_API_KEY:-none}\",\"usage\":{\"input_tokens\":3,\"output_tokens\":4}}"+"#;++async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {+ let resp = app+ .clone()+ .oneshot(+ Request::builder()+ .method(method)+ .uri(uri)+ .header("content-type", "application/json")+ .body(+ body.map(|v| Body::from(v.to_string()))+ .unwrap_or_else(Body::empty),+ )+ .unwrap(),+ )+ .await+ .unwrap();+ let s = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (s, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++/// Sends a prompt and collects the turn's events up to `turn_ended`.+async fn run_turn(app: &Router, state: &AppState, kwant_id: &str) -> Vec<RuntimeEvent> {+ let mut rx = state.event_sender.subscribe();+ let (s, v) = call(+ app,+ "POST",+ "/api/chat/send",+ Some(json!({"kwant_id": kwant_id, "prompt": "hi", "sender_id": "user"})),+ )+ .await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let mut events = Vec::new();+ tokio::time::timeout(Duration::from_secs(60), async {+ while let Ok(e) = rx.recv().await {+ let end = matches!(&e, RuntimeEvent::TurnEnded { kwant_id: k, .. } if k == kwant_id);+ events.push(e);+ if end {+ break;+ }+ }+ })+ .await+ .expect("turn did not end");+ events+}++#[tokio::test]+async fn out_of_usage_profile_fails_over_once_and_pinned_turns_give_up() {+ let tmp = tempfile::tempdir().unwrap();+ let bin = tmp.path().join("bin");+ std::fs::create_dir_all(&bin).unwrap();+ let fake = bin.join("claude");+ std::fs::write(&fake, FAKE_CLAUDE).unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ std::env::set_var(+ "PATH",+ format!(+ "{}:{}",+ bin.display(),+ std::env::var("PATH").unwrap_or_default()+ ),+ );+ // Must not reach a profile's CLI+ std::env::set_var("ANTHROPIC_API_KEY", "sk-ant-host-key-should-not-leak");+ let reset = chrono::Utc::now().timestamp() + 2 * 3600;+ std::env::set_var("FAKE_RESET", reset.to_string());++ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ // Laya is unreachable: routing falls back to the kwant's preferred model+ let config = Config {+ data_dir: data.clone(),+ laya_url: "http://127.0.0.1:9".into(),+ browser_cdp_url: Some("http://127.0.0.1:9".into()),+ ..Config::default()+ };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(data.join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ let app = create_router(state.clone());++ let (_, a) = call(&app, "POST", "/api/profiles", Some(json!({"engine": "claude", "name": "Work", "kind": "cli_home", "is_default": true, "priority": 1}))).await;+ let (_, b) = call(+ &app,+ "POST",+ "/api/profiles",+ Some(json!({"engine": "claude", "name": "Personal", "kind": "cli_home", "priority": 2})),+ )+ .await;+ let (s, _) = call(+ &app,+ "PATCH",+ "/api/profiles/prf_system_claude",+ Some(json!({"enabled": false})),+ )+ .await;+ assert_eq!(s, StatusCode::OK);+ let a_id = a["id"].as_str().unwrap().to_string();+ let b_id = b["id"].as_str().unwrap().to_string();+ std::fs::write(+ std::path::Path::new(a["home_dir"].as_str().unwrap()).join("out-of-usage"),+ "",+ )+ .unwrap();++ let (_, kwants) = call(&app, "GET", "/api/kwants", None).await;+ let k = kwants[0].clone();+ let kid = k["id"].as_str().unwrap().to_string();+ let mut body = k.clone();+ body.as_object_mut().unwrap().retain(|key, _| {+ ["name", "title", "persona_prompt", "soul", "avatar_sprite"].contains(&key.as_str())+ });+ body["preferred_model"] = json!("claude");+ let (s, v) = call(+ &app,+ "PUT",+ &format!("/api/kwants/{kid}"),+ Some(body.clone()),+ )+ .await;+ assert_eq!(s, StatusCode::OK, "{v}");++ // 1. Work is out of usage: the turn completes on Personal, with one switch+ let events = run_turn(&app, &state, &kid).await;+ let started = events+ .iter()+ .filter(|e| matches!(e, RuntimeEvent::TurnStarted { kwant_id, .. } if *kwant_id == kid))+ .count();+ assert_eq!(started, 1);+ let switches: Vec<_> = events+ .iter()+ .filter(|e| matches!(e, RuntimeEvent::ProfileSwitched { .. }))+ .collect();+ assert_eq!(switches.len(), 1, "{events:?}");+ match switches[0] {+ RuntimeEvent::ProfileSwitched {+ kwant_id,+ from_profile_id,+ to_profile_id,+ to_name,+ class,+ retry_at,+ ..+ } => {+ assert_eq!(kwant_id, &kid);+ assert_eq!(from_profile_id, &a_id);+ assert_eq!(to_profile_id, &b_id);+ assert_eq!(to_name, "Personal");+ assert_eq!(class, "quota");+ assert_eq!(retry_at.unwrap().timestamp(), reset);+ }+ _ => unreachable!(),+ }+ let completes: Vec<_> = events+ .iter()+ .filter(|e| matches!(e, RuntimeEvent::TurnComplete { .. }))+ .collect();+ assert_eq!(+ completes.len(),+ 1,+ "the refused attempt's completion is not sent: {events:?}"+ );+ assert!(+ matches!(completes[0], RuntimeEvent::TurnComplete { kwant_id: Some(k), profile_id: Some(p), tokens: 7, .. } if *k == kid && *p == b_id)+ );+ assert!(+ matches!(events.last(), Some(RuntimeEvent::TurnEnded { outcome, .. }) if outcome == "completed")+ );+ let text: String = events+ .iter()+ .filter_map(|e| match e {+ RuntimeEvent::TextDelta(t) => Some(t.as_str()),+ _ => None,+ })+ .collect();+ assert_eq!(text, format!("reply from {b_id} key=none"));+ assert!(!text.contains("usage limit"));++ let saved = state.db.list_messages(&kid, 10).await.unwrap();+ let reply = saved+ .iter()+ .rev()+ .find(|m| m.sender_role == "kwant")+ .unwrap();+ assert_eq!(reply.text, format!("reply from {b_id} key=none"));+ assert!(+ reply+ .reasoning_content+ .as_deref()+ .unwrap_or("")+ .contains("switching to \"Personal\""),+ "{reply:?}"+ );++ // Work's state: out of usage until the provider's reset time; the list shows it+ let (_, list) = call(&app, "GET", "/api/profiles", None).await;+ let work = list+ .as_array()+ .unwrap()+ .iter()+ .find(|p| p["id"] == a_id.as_str())+ .unwrap()+ .clone();+ assert_eq!(work["last_error"], "quota");+ let until: chrono::DateTime<chrono::Utc> =+ work["limited_until"].as_str().unwrap().parse().unwrap();+ assert_eq!(until.timestamp(), reset);+ assert_eq!(work["signed_in"], true);+ assert_eq!(work["account_label"], "[email protected]");++ // 2. Next turn skips Work up front: no switch at all+ let events = run_turn(&app, &state, &kid).await;+ assert!(+ !events+ .iter()+ .any(|e| matches!(e, RuntimeEvent::ProfileSwitched { .. })),+ "{events:?}"+ );+ assert!(events.iter().any(+ |e| matches!(e, RuntimeEvent::TurnComplete { profile_id: Some(p), .. } if *p == b_id)+ ));++ // 3. Pinned to Work without failover: the turn says why and stops+ body["profile_id"] = json!(a_id);+ body["profile_failover"] = json!(false);+ let (s, v) = call(&app, "PUT", &format!("/api/kwants/{kid}"), Some(body)).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let events = run_turn(&app, &state, &kid).await;+ assert!(!events+ .iter()+ .any(|e| matches!(e, RuntimeEvent::ProfileSwitched { .. })));+ let text: String = events+ .iter()+ .filter_map(|e| match e {+ RuntimeEvent::TextDelta(t) => Some(t.as_str()),+ _ => None,+ })+ .collect();+ assert!(text.contains("\"Work\" is out of usage until"), "{text}");+ assert!(!text.contains("sk-ant"), "{text}");+ assert!(+ matches!(events.last(), Some(RuntimeEvent::TurnEnded { outcome, .. }) if outcome == "failed")+ );+ let saved = state.db.list_messages(&kid, 10).await.unwrap();+ assert!(saved+ .iter()+ .rev()+ .find(|m| m.sender_role == "kwant")+ .unwrap()+ .text+ .contains("out of usage"));+}diff --git a/tests/profiles_api_test.rs b/tests/profiles_api_test.rsnew file mode 100644index 00000000..7fd5a10b--- /dev/null+++ b/tests/profiles_api_test.rs@@ -0,0 +1,590 @@+//! `/api/profiles`, kwant profile binding and the API lockdown (Origin allowlist, token).++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::Database,+ router::LayaRouter,+ server::{+ auth::{ApiToken, Require},+ create_router, AppState,+ },+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::sync::Arc;+use tempfile::{tempdir, TempDir};+use tower::ServiceExt;++const TOKEN: &str = "profiles-test-token-0123456789";+const SECRET: &str = "sk-ant-api03-SECRETSECRETSECRET0123456789";++async fn setup() -> (Router, AppState, TempDir) {+ let tmp = tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let config = Config {+ data_dir: tmp.path().to_path_buf(),+ ..Config::default()+ };+ let mut state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(tmp.path().join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ state.api_token = Arc::new(ApiToken::for_tests(TOKEN, Require::Auto, config.port));+ (create_router(state.clone()), state, tmp)+}++async fn req(+ app: &Router,+ method: &str,+ uri: &str,+ body: Option<Value>,+ headers: &[(&str, &str)],+) -> (StatusCode, String, Vec<(String, String)>) {+ let mut b = Request::builder()+ .method(method)+ .uri(uri)+ .header("content-type", "application/json");+ for (k, v) in headers {+ b = b.header(*k, *v);+ }+ let resp = app+ .clone()+ .oneshot(+ b.body(+ body.map(|v| Body::from(v.to_string()))+ .unwrap_or_else(Body::empty),+ )+ .unwrap(),+ )+ .await+ .unwrap();+ let status = resp.status();+ let hdrs = resp+ .headers()+ .iter()+ .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))+ .collect();+ let text = String::from_utf8_lossy(&to_bytes(resp.into_body(), usize::MAX).await.unwrap())+ .into_owned();+ (status, text, hdrs)+}++async fn call(+ app: &Router,+ method: &str,+ uri: &str,+ body: Option<Value>,+) -> (StatusCode, Value, String) {+ let (s, text, _) = req(app, method, uri, body, &[]).await;+ (s, serde_json::from_str(&text).unwrap_or(Value::Null), text)+}++#[tokio::test]+async fn system_profiles_exist_and_api_keys_are_write_only() {+ let (app, state, tmp) = setup().await;++ let (s, list, _) = call(&app, "GET", "/api/profiles", None).await;+ assert_eq!(s, StatusCode::OK);+ let ids: Vec<&str> = list+ .as_array()+ .unwrap()+ .iter()+ .map(|p| p["id"].as_str().unwrap())+ .collect();+ for e in ["claude", "codex", "grok"] {+ assert!(ids.contains(&format!("prf_system_{e}").as_str()), "{list}");+ }+ assert!(list+ .as_array()+ .unwrap()+ .iter()+ .all(|p| p["is_default"] == true && p["kind"] == "system"));++ // Create an api_key profile with a key: the key never comes back+ let (s, created, text) = call(+ &app,+ "POST",+ "/api/profiles",+ Some(json!({"engine": "claude", "name": "Work API", "kind": "api_key", "api_key": SECRET})),+ )+ .await;+ assert_eq!(s, StatusCode::CREATED, "{text}");+ assert!(!text.contains("SECRET"), "{text}");+ assert_eq!(created["has_key"], true);+ assert_eq!(created["signed_in"], true);+ assert_eq!(created["account_label"], "API key");+ let id = created["id"].as_str().unwrap().to_string();++ let (_, _, text) = call(&app, "GET", "/api/profiles", None).await;+ assert!(!text.contains("SECRET"), "{text}");+ assert_eq!(+ state.db.get_profile_key(&id).await.unwrap().unwrap().0,+ SECRET+ );++ // Replace, then delete the key+ let (s, _, _) = call(+ &app,+ "PUT",+ &format!("/api/profiles/{id}/key"),+ Some(json!({"api_key": "sk-ant-other-0123456789"})),+ )+ .await;+ assert_eq!(s, StatusCode::NO_CONTENT);+ let (s, _, _) = call(+ &app,+ "PUT",+ &format!("/api/profiles/{id}/key"),+ Some(json!({"api_key": "short"})),+ )+ .await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+ let (s, _, _) = call(&app, "DELETE", &format!("/api/profiles/{id}/key"), None).await;+ assert_eq!(s, StatusCode::NO_CONTENT);+ let (_, list, _) = call(&app, "GET", "/api/profiles", None).await;+ let p = list+ .as_array()+ .unwrap()+ .iter()+ .find(|p| p["id"] == id.as_str())+ .unwrap()+ .clone();+ assert_eq!(p["has_key"], false);+ assert_eq!(p["signed_in"], false);++ // The key never reaches the db file in a form we print, and nothing leaks into a response body+ assert!(state.db.get_profile_key(&id).await.unwrap().is_none());++ // A cli_home profile gets a private kwnt-managed home+ let (s, created, text) = call(+ &app,+ "POST",+ "/api/profiles",+ Some(json!({"engine": "codex", "name": "Personal", "kind": "cli_home"})),+ )+ .await;+ assert_eq!(s, StatusCode::CREATED, "{text}");+ let home = created["home_dir"].as_str().unwrap().to_string();+ assert!(home.starts_with(tmp.path().to_str().unwrap()), "{home}");+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ assert_eq!(+ std::fs::metadata(&home).unwrap().permissions().mode() & 0o777,+ 0o700+ );+ }+}++#[tokio::test]+async fn profile_validation_and_delete_rules() {+ let (app, _state, _tmp) = setup().await;+ let bad = [+ json!({"engine": "claude", "name": "x", "kind": "system"}),+ json!({"engine": "gemini", "name": "x", "kind": "api_key"}),+ json!({"engine": "claude", "name": "", "kind": "api_key"}),+ json!({"engine": "claude", "name": "x", "kind": "cli_home", "api_key": SECRET}),+ json!({"engine": "claude", "name": "x", "kind": "cli_home", "home_dir": "relative/dir"}),+ json!({"engine": "claude", "name": "x", "kind": "cli_home", "home_dir": "/"}),+ ];+ for body in bad {+ let (s, v, _) = call(&app, "POST", "/api/profiles", Some(body.clone())).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{body} -> {v}");+ assert!(v["error"].is_string());+ }+ // Unknown fields are refused rather than ignored+ let (s, _, _) = call(+ &app,+ "POST",+ "/api/profiles",+ Some(json!({"engine": "claude", "name": "x", "kind": "api_key", "secret": 1})),+ )+ .await;+ assert!(s.is_client_error());++ let (s, a, _) = call(+ &app,+ "POST",+ "/api/profiles",+ Some(json!({"engine": "claude", "name": "Work", "kind": "api_key", "is_default": true})),+ )+ .await;+ assert_eq!(s, StatusCode::CREATED);+ let (s, _, _) = call(+ &app,+ "POST",+ "/api/profiles",+ Some(json!({"engine": "claude", "name": "Work", "kind": "api_key"})),+ )+ .await;+ assert_eq!(s, StatusCode::CONFLICT);++ let id = a["id"].as_str().unwrap();+ let (_, list, _) = call(&app, "GET", "/api/profiles", None).await;+ let sys = list+ .as_array()+ .unwrap()+ .iter()+ .find(|p| p["id"] == "prf_system_claude")+ .unwrap()+ .clone();+ assert_eq!(sys["is_default"], false);+ assert_eq!(a["is_default"], true);++ // The default can't be disabled or un-defaulted directly+ let (s, _, _) = call(+ &app,+ "PATCH",+ &format!("/api/profiles/{id}"),+ Some(json!({"enabled": false})),+ )+ .await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+ let (s, v, _) = call(+ &app,+ "PATCH",+ &format!("/api/profiles/{id}"),+ Some(json!({"name": "Work 2", "priority": 5})),+ )+ .await;+ assert_eq!(s, StatusCode::OK);+ assert_eq!(v["name"], "Work 2");++ // System profiles stay; deleting the default hands it back to the system profile+ let (s, _, _) = call(&app, "DELETE", "/api/profiles/prf_system_claude", None).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+ let (s, _, _) = call(&app, "DELETE", &format!("/api/profiles/{id}"), None).await;+ assert_eq!(s, StatusCode::NO_CONTENT);+ let (_, list, _) = call(&app, "GET", "/api/profiles", None).await;+ let sys = list+ .as_array()+ .unwrap()+ .iter()+ .find(|p| p["id"] == "prf_system_claude")+ .unwrap()+ .clone();+ assert_eq!(sys["is_default"], true);+ let (s, _, _) = call(&app, "DELETE", &format!("/api/profiles/{id}"), None).await;+ assert_eq!(s, StatusCode::NOT_FOUND);++ // Sign-in is only for cli_home profiles+ let (s, _, _) = call(&app, "POST", "/api/profiles/prf_system_claude/login", None).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+}++#[tokio::test]+async fn kwants_carry_their_profile_binding() {+ let (app, _state, _tmp) = setup().await;+ let (_, kwants, _) = call(&app, "GET", "/api/kwants", None).await;+ let k = kwants[0].clone();+ // Existing kwants: engine default, failover on+ assert_eq!(k["profile_id"], Value::Null);+ assert_eq!(k["profile_failover"], true);+ let id = k["id"].as_str().unwrap();++ let (_, p, _) = call(+ &app,+ "POST",+ "/api/profiles",+ Some(json!({"engine": "codex", "name": "Personal", "kind": "api_key"})),+ )+ .await;+ let codex_profile = p["id"].as_str().unwrap();++ let base = json!({+ "name": k["name"], "title": k["title"], "persona_prompt": k["persona_prompt"],+ "soul": k["soul"], "avatar_sprite": k["avatar_sprite"],+ });+ let with = |model: &str, extra: Value| {+ let mut b = base.clone();+ b["preferred_model"] = json!(model);+ for (key, v) in extra.as_object().unwrap() {+ b[key] = v.clone();+ }+ b+ };++ // A claude kwant can't be pinned to a codex profile; unknown profiles are refused+ let (s, _, _) = call(+ &app,+ "PUT",+ &format!("/api/kwants/{id}"),+ Some(with("claude", json!({"profile_id": codex_profile}))),+ )+ .await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+ let (s, _, _) = call(+ &app,+ "PUT",+ &format!("/api/kwants/{id}"),+ Some(with("codex", json!({"profile_id": "prf_nope"}))),+ )+ .await;+ assert_eq!(s, StatusCode::BAD_REQUEST);++ let (s, v, text) = call(+ &app,+ "PUT",+ &format!("/api/kwants/{id}"),+ Some(with(+ "codex",+ json!({"profile_id": codex_profile, "profile_failover": false}),+ )),+ )+ .await;+ assert_eq!(s, StatusCode::OK, "{text}");+ assert_eq!(v["profile_id"], codex_profile);+ assert_eq!(v["profile_failover"], false);++ // Omitted: unchanged. null: back to the engine default.+ let (_, v, _) = call(+ &app,+ "PUT",+ &format!("/api/kwants/{id}"),+ Some(with("codex", json!({}))),+ )+ .await;+ assert_eq!(v["profile_id"], codex_profile);+ let (_, v, _) = call(+ &app,+ "PUT",+ &format!("/api/kwants/{id}"),+ Some(with("codex", json!({"profile_id": null}))),+ )+ .await;+ assert_eq!(v["profile_id"], Value::Null);+ assert_eq!(v["profile_failover"], false);++ // Deleting a profile unpins its kwants+ call(+ &app,+ "PUT",+ &format!("/api/kwants/{id}"),+ Some(with("codex", json!({"profile_id": codex_profile}))),+ )+ .await;+ call(+ &app,+ "DELETE",+ &format!("/api/profiles/{codex_profile}"),+ None,+ )+ .await;+ let (_, kwants, _) = call(&app, "GET", "/api/kwants", None).await;+ let k = kwants+ .as_array()+ .unwrap()+ .iter()+ .find(|k| k["id"] == id)+ .unwrap()+ .clone();+ assert_eq!(k["profile_id"], Value::Null);+}++#[tokio::test]+async fn foreign_origins_are_refused() {+ let (app, _state, _tmp) = setup().await;+ // No Origin (curl, the CLI agents): fine+ let (s, _, _) = req(+ &app,+ "GET",+ "/api/kwants",+ None,+ &[("host", "127.0.0.1:3000")],+ )+ .await;+ assert_eq!(s, StatusCode::OK);+ // kwnt's own page and the dev server+ for origin in ["http://127.0.0.1:3000", "http://localhost:5199"] {+ let (s, _, h) = req(+ &app,+ "GET",+ "/api/kwants",+ None,+ &[("host", "127.0.0.1:3000"), ("origin", origin)],+ )+ .await;+ assert_eq!(s, StatusCode::OK, "{origin}");+ assert!(h+ .iter()+ .any(|(k, v)| k == "access-control-allow-origin" && v == origin));+ }+ // Any other site, simple request or preflight+ let (s, _, h) = req(+ &app,+ "POST",+ "/api/chat/send",+ Some(json!({})),+ &[+ ("host", "127.0.0.1:3000"),+ ("origin", "https://evil.example"),+ ],+ )+ .await;+ assert_eq!(s, StatusCode::FORBIDDEN);+ assert!(!h.iter().any(|(k, _)| k == "access-control-allow-origin"));+ let (s, _, _) = req(+ &app,+ "OPTIONS",+ "/api/profiles",+ None,+ &[+ ("host", "127.0.0.1:3000"),+ ("origin", "https://evil.example"),+ ("access-control-request-method", "POST"),+ ],+ )+ .await;+ assert_eq!(s, StatusCode::FORBIDDEN);+ // The UI itself (not /api) is never blocked+ let (s, _, _) = req(+ &app,+ "GET",+ "/",+ None,+ &[("origin", "https://evil.example")],+ )+ .await;+ assert_eq!(s, StatusCode::OK);+}++#[tokio::test]+async fn remote_requests_need_the_token() {+ let (app, _state, _tmp) = setup().await;+ let remote = ("host", "kwnt.example.com");++ let (s, _, _) = req(&app, "GET", "/api/kwants", None, &[remote]).await;+ assert_eq!(s, StatusCode::UNAUTHORIZED);+ // A local proxy forwarding a remote request is remote+ let (s, _, _) = req(+ &app,+ "GET",+ "/api/kwants",+ None,+ &[+ ("host", "127.0.0.1:3000"),+ ("x-forwarded-for", "203.0.113.9"),+ ],+ )+ .await;+ assert_eq!(s, StatusCode::UNAUTHORIZED);+ // Health stays open for probes+ let (s, _, _) = req(&app, "GET", "/api/health", None, &[remote]).await;+ assert_eq!(s, StatusCode::OK);++ let (s, body, _) = req(&app, "GET", "/api/auth/status", None, &[remote]).await;+ assert_eq!(s, StatusCode::OK);+ assert_eq!(+ serde_json::from_str::<Value>(&body).unwrap(),+ json!({"auth_required": true, "authenticated": false})+ );++ let bearer = format!("Bearer {TOKEN}");+ let (s, _, _) = req(+ &app,+ "GET",+ "/api/kwants",+ None,+ &[remote, ("authorization", &bearer)],+ )+ .await;+ assert_eq!(s, StatusCode::OK);+ let (s, _, _) = req(+ &app,+ "GET",+ "/api/kwants",+ None,+ &[remote, ("authorization", "Bearer wrong-token-0123456789")],+ )+ .await;+ assert_eq!(s, StatusCode::UNAUTHORIZED);++ // The UI trades the token for an HttpOnly cookie, which EventSource and WebSockets send+ let (s, _, _) = req(+ &app,+ "POST",+ "/api/auth/session",+ Some(json!({"token": "nope-nope-nope-nope"})),+ &[remote],+ )+ .await;+ assert_eq!(s, StatusCode::UNAUTHORIZED);+ let (s, _, h) = req(+ &app,+ "POST",+ "/api/auth/session",+ Some(json!({"token": TOKEN})),+ &[+ remote,+ ("origin", "https://kwnt.example.com"),+ ("x-forwarded-proto", "https"),+ ],+ )+ .await;+ assert_eq!(s, StatusCode::NO_CONTENT);+ let cookie = h+ .iter()+ .find(|(k, _)| k == "set-cookie")+ .map(|(_, v)| v.clone())+ .unwrap();+ assert!(+ cookie.contains("HttpOnly")+ && cookie.contains("SameSite=Strict")+ && cookie.contains("Secure"),+ "{cookie}"+ );+ let pair = cookie.split(';').next().unwrap().to_string();+ let (s, _, _) = req(+ &app,+ "GET",+ "/api/kwants",+ None,+ &[remote, ("cookie", &pair)],+ )+ .await;+ assert_eq!(s, StatusCode::OK);+ let (_, body, _) = req(+ &app,+ "GET",+ "/api/auth/status",+ None,+ &[remote, ("cookie", &pair)],+ )+ .await;+ assert_eq!(+ serde_json::from_str::<Value>(&body).unwrap()["authenticated"],+ true+ );++ // Local requests (the UI on this machine, agents curling the browser API) need nothing+ let (s, _, _) = req(+ &app,+ "GET",+ "/api/kwants",+ None,+ &[("host", "localhost:3000")],+ )+ .await;+ assert_eq!(s, StatusCode::OK);+ let (_, body, _) = req(+ &app,+ "GET",+ "/api/auth/status",+ None,+ &[("host", "localhost:3000")],+ )+ .await;+ assert_eq!(+ serde_json::from_str::<Value>(&body).unwrap(),+ json!({"auth_required": false, "authenticated": true})+ );+}