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
Custom API accounts: any OpenAI- or Anthropic-compatible server per space
Lin (kwant bot)72b83f656249
diff --git a/docs/llm-profiles.md b/docs/llm-profiles.mdindex 35ee8f8f..02c248fa 100644--- a/docs/llm-profiles.md+++ b/docs/llm-profiles.md@@ -12,6 +12,7 @@ the environment. Existing setups keep working without any change.| `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 |+| `custom_api` | engine `custom` only: the account's own server (see below), with its key if any | a check of the server's model list |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@@ -32,6 +33,23 @@ Set `profile_failover: false` on a kwant to stay on its profile and get an explaA profile that ran out of usage is skipped until its reset time (or one hour when the providerdidn't say). Overloads and rate limits are retried, not failed over.+**Custom API accounts.** Engine `custom`, kind `custom_api`: any server that speaks the OpenAI+chat API (`openai-chat`: OpenRouter, LM Studio, Agent Maestro's `/api/openai/v1`, …) or the+Anthropic Messages API (`anthropic-messages`: Agent Maestro's `/api/anthropic`). A space can have+several; they belong to that space only. The base URL is cut back to the API root (a pasted+`…/chat/completions` or `…/messages` is removed; Anthropic gets `/v1` added), must be http(s), and+may not carry a user, password, query or fragment, so a key never sits in it. The account is+checked with `GET {base}/models` when it is created or changed, on `POST …/check`, and again+when the account list or the Engines page is read and the last check is over a minute old: `ready`, `unreachable` ("Nothing is answering at <url>. Is Agent Maestro /+the server running?"), `key_rejected` or `error`, with a readable `detail`. A server that lists+no models is ready when the account has a `model`. A turn runs the bot's pinned model+(`custom:<model id>`) as is, else the account's `model`, else the first listed model for the+effort's tier; replies stream. MCP tools are offered on `openai-chat` only (`supports_tools`);+`anthropic-messages` turns run without them and say so. Custom API never falls back to the host:+a space without an enabled account answers "No Custom API account is on in this space".+The accounts need database schema version 2; if that change failed at start (see the log),+creating one answers `503`.+Keys are write-only: no API response contains one, only `has_key`. Provider error text is keptonly as a class (`quota`, `auth`).@@ -71,10 +89,11 @@ Errors are `{"error": "<message>"}`. Bodies with unknown fields are refused.### 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`+- `POST /api/profiles` `{"engine", "name", "kind": "cli_home"|"api_key"|"custom_api", "home_dir"?, "priority"?, "enabled"?, "is_default"?, "api_key"?, "protocol"?, "base_url"?, "model"?}` → `201 Profile`; `409` on a duplicate name or home. `custom_api` (engine `custom`) needs `protocol` and `base_url`; its server is checked before the response+- `PATCH /api/profiles/:id` `{"name"?, "priority"?, "enabled"?, "is_default"?, "protocol"?, "base_url"?, "model"?}` → `Profile`; the last three only for `custom_api`, `"model": ""` clears it, and a change re-checks the server+- `POST /api/profiles/:id/check` → `Profile` (`custom_api`: checks the server again now)- `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)+- `PUT /api/profiles/:id/key` `{"api_key"}` → `204` (`api_key` and `custom_api` 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`@@ -86,9 +105,9 @@ Errors are `{"error": "<message>"}`. Bodies with unknown fields are refused.// Profile{"id": "prf_…" | "prf_system_claude",- "engine": "claude" | "codex" | "grok",+ "engine": "claude" | "codex" | "grok" | "custom","name": "Work",- "kind": "system" | "cli_home" | "api_key",+ "kind": "system" | "cli_home" | "api_key" | "custom_api","enabled": true,"is_default": false,"priority": 100,@@ -97,7 +116,17 @@ Errors are `{"error": "<message>"}`. Bodies with unknown fields are refused."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+ "last_error": "quota" | "auth" | null,+ "custom": null | { // custom_api only+ "protocol": "openai-chat" | "anthropic-messages",+ "base_url": "http://localhost:23333/api/openai/v1",+ "model": "gpt-4.1" | null,+ "status": "ready" | "unreachable" | "key_rejected" | "error" | null,+ "detail": "Connected · 12 models" | null,+ "models": [{"id": "gpt-4.1", "label": "gpt-4.1", "tier": "fast" | "balanced" | "deep" | null, "default": true}],+ "checked_at": "2026-10-18T12:00:00Z" | null,+ "supports_tools": true+ }}// Login{diff --git a/src/db/custom_api.rs b/src/db/custom_api.rsnew file mode 100644index 00000000..280b72d2--- /dev/null+++ b/src/db/custom_api.rs@@ -0,0 +1,158 @@+//! Custom API accounts: a profile of engine `custom` and kind `custom_api`, whose server (protocol,+//! base URL, model) lives in `llm_profile_endpoints`. Its key, if any, is stored like every other+//! profile key, in `llm_profile_secrets`.+//!+//! Schema version 2 widens `llm_profiles`' CHECKs for the new engine and kind and adds the+//! endpoints table, in one transaction that rolls back on any error. A failed migration leaves+//! version 1, which this release still runs on without Custom API accounts, and retries at the+//! next start. A release from before version 2 still starts on it but doesn't know `custom` rows:+//! it lists them under no engine and never routes to them.++use super::spaces::{foreign_key_violations, rebuild, SPACES_SCHEMA_VERSION};+use super::{Database, DbError};+use serde::{Deserialize, Serialize};+use sqlx::{Connection, FromRow, SqliteConnection};++/// `PRAGMA user_version` once Custom API accounts can be stored.+pub const CUSTOM_API_SCHEMA_VERSION: i64 = 2;++/// Where a Custom API account sends its turns.+#[derive(Debug, Clone, PartialEq, Eq, FromRow, Serialize, Deserialize)]+pub struct ProfileEndpoint {+ pub profile_id: String,+ /// "openai-chat" or "anthropic-messages".+ pub protocol: String,+ /// Normalized: no trailing slash, ends at the API root (`…/v1`).+ pub base_url: String,+ /// The model entered by hand: used when the server lists none, and as the account's+ /// default when a bot doesn't pin one.+ pub model: Option<String>,+}++const LLM_PROFILES_V2: &str = "CREATE TABLE llm_profiles__spaces_new (+ id TEXT PRIMARY KEY,+ engine TEXT NOT NULL CHECK (engine IN ('claude', 'codex', 'grok', 'custom')),+ name TEXT NOT NULL,+ kind TEXT NOT NULL CHECK (kind IN ('system', 'cli_home', 'api_key', 'custom_api')),+ 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,+ space_id TEXT NOT NULL DEFAULT 'spc_default',+ UNIQUE (space_id, engine, name COLLATE NOCASE)+)";++const AFTER_REBUILD: [&str; 2] = [+ "CREATE UNIQUE INDEX llm_profiles_one_default ON llm_profiles (space_id, engine) WHERE is_default = 1",+ "CREATE INDEX llm_profiles_by_space ON llm_profiles (space_id, engine)",+];++const ENDPOINTS_TABLE: &str = "CREATE TABLE llm_profile_endpoints (+ profile_id TEXT PRIMARY KEY,+ protocol TEXT NOT NULL CHECK (protocol IN ('openai-chat', 'anthropic-messages')),+ base_url TEXT NOT NULL,+ model TEXT,+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ FOREIGN KEY(profile_id) REFERENCES llm_profiles(id) ON DELETE CASCADE+)";++impl Database {+ /// Brings a spaces database to [`CUSTOM_API_SCHEMA_VERSION`]. Never fails startup: an error+ /// is logged and the database stays as it was. Returns whether the schema is now in place.+ pub(super) async fn migrate_custom_api(&self) -> Result<bool, DbError> {+ let version = self.schema_version().await?;+ if version >= CUSTOM_API_SCHEMA_VERSION {+ return Ok(true);+ }+ if version < SPACES_SCHEMA_VERSION {+ return Ok(false);+ }+ let mut conn = self.pool.acquire().await?;+ // Table rebuilds need foreign keys off, and SQLite ignores this pragma inside a transaction+ sqlx::query("PRAGMA foreign_keys = OFF").execute(&mut *conn).await?;+ let result = custom_api_in_transaction(&mut conn).await;+ sqlx::query("PRAGMA foreign_keys = ON").execute(&mut *conn).await?;+ match result {+ Ok(()) => {+ tracing::info!("Database ready for Custom API accounts");+ Ok(true)+ }+ Err(e) => {+ tracing::error!(+ "Custom API accounts are unavailable: the schema change failed and was rolled back ({e})"+ );+ Ok(false)+ }+ }+ }++ /// Whether Custom API accounts can be stored (the migration ran).+ pub async fn custom_api_ready(&self) -> bool {+ self.schema_version().await.is_ok_and(|v| v >= CUSTOM_API_SCHEMA_VERSION)+ }++ pub async fn get_profile_endpoint(&self, profile_id: &str) -> Result<Option<ProfileEndpoint>, DbError> {+ if !self.custom_api_ready().await {+ return Ok(None);+ }+ Ok(sqlx::query_as::<_, ProfileEndpoint>(+ "SELECT profile_id, protocol, base_url, model FROM llm_profile_endpoints WHERE profile_id = ?",+ )+ .bind(profile_id)+ .fetch_optional(&self.pool)+ .await?)+ }++ /// Every endpoint, by profile id.+ pub async fn list_profile_endpoints(+ &self,+ ) -> Result<std::collections::HashMap<String, ProfileEndpoint>, DbError> {+ if !self.custom_api_ready().await {+ return Ok(Default::default());+ }+ let rows = sqlx::query_as::<_, ProfileEndpoint>(+ "SELECT profile_id, protocol, base_url, model FROM llm_profile_endpoints",+ )+ .fetch_all(&self.pool)+ .await?;+ Ok(rows.into_iter().map(|e| (e.profile_id.clone(), e)).collect())+ }++ pub async fn set_profile_endpoint(&self, endpoint: &ProfileEndpoint) -> Result<(), DbError> {+ sqlx::query(+ "INSERT INTO llm_profile_endpoints (profile_id, protocol, base_url, model, updated_at)+ VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)+ ON CONFLICT(profile_id) DO UPDATE SET protocol = excluded.protocol,+ base_url = excluded.base_url, model = excluded.model, updated_at = CURRENT_TIMESTAMP",+ )+ .bind(&endpoint.profile_id)+ .bind(&endpoint.protocol)+ .bind(&endpoint.base_url)+ .bind(&endpoint.model)+ .execute(&self.pool)+ .await?;+ Ok(())+ }+}++async fn custom_api_in_transaction(conn: &mut SqliteConnection) -> Result<(), DbError> {+ // Violations already in the data aren't ours to fix; only new ones abort the migration+ let before = foreign_key_violations(conn).await?;+ let mut tx = conn.begin().await?;+ rebuild(&mut tx, "llm_profiles", LLM_PROFILES_V2, &AFTER_REBUILD).await?;+ sqlx::query(ENDPOINTS_TABLE).execute(&mut *tx).await?;+ let after = foreign_key_violations(&mut tx).await?;+ let new: Vec<_> = after+ .iter()+ .filter(|(key, n)| **n > before.get(*key).copied().unwrap_or(0))+ .collect();+ if !new.is_empty() {+ return Err(DbError::Migration(format!("foreign key check failed: {new:?}")));+ }+ sqlx::query(&format!("PRAGMA user_version = {CUSTOM_API_SCHEMA_VERSION}"))+ .execute(&mut *tx)+ .await?;+ tx.commit().await?;+ Ok(())+}diff --git a/src/db/mod.rs b/src/db/mod.rsindex 3c66c760..6b21ede4 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -8,6 +8,7 @@ pub mod questions;pub mod skills;pub mod away;pub mod spaces;+pub mod custom_api;/// What a space's #general says about itself.pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";@@ -128,6 +129,7 @@ impl Database {db.ensure_one_general().await?;db.seed_defaults().await?;db.migrate_space_archive().await?;+ db.migrate_custom_api().await?;}Ok(db)diff --git a/src/db/profiles.rs b/src/db/profiles.rsindex aaba6655..ac7294c4 100644--- a/src/db/profiles.rs+++ b/src/db/profiles.rs@@ -144,7 +144,14 @@ impl Database {let Some(existing) = self.get_profile(id).await? else {return Ok(false);};+ let endpoints = self.custom_api_ready().await;let mut tx = self.pool.begin().await?;+ if endpoints {+ sqlx::query("DELETE FROM llm_profile_endpoints WHERE profile_id = ?")+ .bind(id)+ .execute(&mut *tx)+ .await?;+ }for sql in ["DELETE FROM llm_profile_secrets WHERE profile_id = ?","DELETE FROM llm_profile_state WHERE profile_id = ?",diff --git a/src/db/spaces.rs b/src/db/spaces.rsindex 8b6fd4ba..86fa1a32 100644--- a/src/db/spaces.rs+++ b/src/db/spaces.rs@@ -341,7 +341,7 @@ async fn migrate_in_transaction(conn: &mut SqliteConnection) -> Result<(), DbErr/// SQLite's documented rebuild: create the new table, copy every row, drop the old one and/// rename. Child tables refer to the parent by name, so their foreign keys follow the rename./// Refuses to drop a column the new table doesn't have, rather than lose data.-async fn rebuild(conn: &mut SqliteConnection, table: &str, create: &str, after: &[&str]) -> Result<(), DbError> {+pub(super) async fn rebuild(conn: &mut SqliteConnection, table: &str, create: &str, after: &[&str]) -> Result<(), DbError> {let new_table = format!("{table}__spaces_new");sqlx::query(create).execute(&mut *conn).await?;@@ -385,7 +385,7 @@ async fn columns(conn: &mut SqliteConnection, table: &str) -> Result<Vec<String>}/// `PRAGMA foreign_key_check` counted per (table, parent). Not per rowid: a rebuild renumbers them.-async fn foreign_key_violations(conn: &mut SqliteConnection) -> Result<HashMap<(String, String), usize>, DbError> {+pub(super) async fn foreign_key_violations(conn: &mut SqliteConnection) -> Result<HashMap<(String, String), usize>, DbError> {let rows: Vec<(String, Option<i64>, String, i64)> =sqlx::query_as("PRAGMA foreign_key_check").fetch_all(&mut *conn).await?;let mut counts = HashMap::new();diff --git a/src/drivers/api.rs b/src/drivers/api.rsindex 2de2cdfa..892d2ba2 100644--- a/src/drivers/api.rs+++ b/src/drivers/api.rs@@ -101,7 +101,7 @@ impl std::fmt::Display for ApiError {}/// The provider's own error message out of an error body (OpenAI and Anthropic shapes), redacted.-fn error_message(body: &str) -> String {+pub(crate) 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"];@@ -157,6 +157,116 @@ fn anthropic_body(model: &str, messages: &[Value], max_tokens: i64) -> Value {})}+/// The reply text of a non-streamed call, OpenAI or Anthropic shaped.+fn reply_text(reply: &Value) -> Option<String> {+ let anthropic_text = reply["content"].as_array().map(|blocks| {+ blocks+ .iter()+ .filter_map(|b| b["text"].as_str())+ .collect::<Vec<_>>()+ .join("")+ });+ reply["choices"][0]["message"]["content"]+ .as_str()+ .map(str::to_string)+ .or(anthropic_text)+}++/// Tokens a reply used, from OpenAI's `total_tokens` or Anthropic's input + output.+fn usage_tokens(usage: &Value) -> Option<u64> {+ usage["total_tokens"]+ .as_u64()+ .or_else(|| Some(usage["input_tokens"].as_u64()? + usage["output_tokens"].as_u64().unwrap_or(0)))+}++/// Reads a streamed reply (server-sent events, OpenAI or Anthropic shaped), sending each piece+/// of text as it arrives. A server that answers with one JSON body instead is read whole. Returns+/// the full text and tokens used; a stream cut off midway keeps what arrived, with a note.+async fn stream_reply(+ mut resp: reqwest::Response,+ anthropic: bool,+ event_tx: &mpsc::Sender<RuntimeEvent>,+) -> (String, usize) {+ let is_sse = resp+ .headers()+ .get(reqwest::header::CONTENT_TYPE)+ .and_then(|v| v.to_str().ok())+ .is_some_and(|v| v.contains("text/event-stream"));+ if !is_sse {+ let reply = resp.json::<Value>().await.unwrap_or(Value::Null);+ let text = reply_text(&reply).unwrap_or_else(|| "No response content".into());+ let _ = event_tx.send(RuntimeEvent::TextDelta(text.clone())).await;+ return (text, usage_tokens(&reply["usage"]).unwrap_or(45) as usize);+ }+ let mut text = String::new();+ let mut input_tokens = 0u64;+ let mut output_tokens = 0u64;+ let mut total_tokens: Option<u64> = None;+ let mut pending: Vec<u8> = Vec::new();+ let mut failure: Option<String> = None;+ 'read: loop {+ let chunk = match resp.chunk().await {+ Ok(Some(c)) => c,+ Ok(None) => break,+ Err(_) => {+ failure = Some("the stream was cut off".into());+ break;+ }+ };+ pending.extend_from_slice(&chunk);+ while let Some(end) = pending.iter().position(|b| *b == b'\n') {+ let line: Vec<u8> = pending.drain(..=end).collect();+ let line = String::from_utf8_lossy(&line);+ let Some(data) = line.trim().strip_prefix("data:").map(str::trim) else {+ continue;+ };+ if data == "[DONE]" {+ break 'read;+ }+ let Ok(event) = serde_json::from_str::<Value>(data) else {+ continue;+ };+ if event.get("error").is_some_and(|e| !e.is_null()) {+ failure = Some(error_message(data));+ break 'read;+ }+ let piece = if anthropic {+ match event["type"].as_str() {+ Some("message_start") => {+ input_tokens = event["message"]["usage"]["input_tokens"].as_u64().unwrap_or(0);+ None+ }+ Some("message_delta") => {+ output_tokens = event["usage"]["output_tokens"].as_u64().unwrap_or(output_tokens);+ None+ }+ Some("content_block_delta") => event["delta"]["text"].as_str(),+ _ => None,+ }+ } else {+ if let Some(t) = usage_tokens(&event["usage"]) {+ total_tokens = Some(t);+ }+ event["choices"][0]["delta"]["content"].as_str()+ };+ if let Some(piece) = piece.filter(|p| !p.is_empty()) {+ text.push_str(piece);+ let _ = event_tx.send(RuntimeEvent::TextDelta(piece.to_string())).await;+ }+ }+ }+ if let Some(why) = failure {+ let note = format!("{}⚠️ The reply stopped early: {why}", if text.is_empty() { "" } else { "\n\n" });+ text.push_str(¬e);+ let _ = event_tx.send(RuntimeEvent::TextDelta(note)).await;+ } else if text.is_empty() {+ text = "No response content".into();+ let _ = event_tx.send(RuntimeEvent::TextDelta(text.clone())).await;+ }+ let tokens = total_tokens.unwrap_or(input_tokens + output_tokens);+ (text, if tokens == 0 { 45 } else { tokens as usize })+}+struct ChatRequest<'a> {url: &'a str,api_key: Option<&'a str>,@@ -165,6 +275,8 @@ struct ChatRequest<'a> {max_tokens: i64,/// Model calls allowed this turn; each round of MCP tool calls costs one.max_calls: usize,+ /// Stream the reply as it is written (rounds without tools only).+ stream: bool,}#[derive(Clone, Debug)]@@ -174,6 +286,9 @@ pub struct ApiDriver {endpoint: Option<String>,/// Whether a missing key may come from the provider's env var (not for profiles).env_keys: bool,+ /// A Custom API account's base URL: no key needed, replies streamed, and a server that+ /// doesn't answer is named in the error.+ custom_base: Option<String>,}impl ApiDriver {@@ -183,6 +298,17 @@ impl ApiDriver {api_key,endpoint,env_keys: true,+ custom_base: None,+ }+ }++ /// A Custom API account's driver: turns go to `chat_url` (see [`super::custom::chat_url`])+ /// with the account's own key, or none; never a host key.+ pub fn for_custom(api_key: Option<String>, chat_url: String, base: String) -> Self {+ Self {+ env_keys: false,+ custom_base: Some(base),+ ..Self::new(api_key, Some(chat_url))}}@@ -227,7 +353,8 @@ impl ApiDriver {}impl ApiDriver {- async fn post_chat(&self, request: &ChatRequest<'_>, body: &Value) -> Result<Value, ApiError> {+ /// Sends one model call; `Err` for no answer or an error status, with the provider's message.+ async fn send_chat(&self, request: &ChatRequest<'_>, body: &Value) -> Result<reqwest::Response, ApiError> {let mut req = self.client.post(request.url)@@ -243,10 +370,10 @@ impl ApiDriver {}let resp = req.send().await.map_err(|e| ApiError {status: None,- message: if e.is_timeout() {- "request timed out".into()- } else {- "connection failed".into()+ message: match (&self.custom_base, e.is_timeout()) {+ (_, true) => "request timed out".into(),+ (Some(base), false) => super::custom::not_answering(base),+ (None, false) => "connection failed".into(),},retry_after: None,})?;@@ -264,6 +391,11 @@ impl ApiDriver {retry_after,});}+ Ok(resp)+ }++ async fn post_chat(&self, request: &ChatRequest<'_>, body: &Value) -> Result<Value, ApiError> {+ let resp = self.send_chat(request, body).await?;resp.json::<Value>().await.map_err(|_| ApiError {status: None,message: "invalid response from the model API".into(),@@ -277,9 +409,17 @@ impl ApiDriver {request: &ChatRequest<'_>,body: &Value,) -> Result<Value, ApiError> {+ self.with_retry(|| self.post_chat(request, body)).await+ }++ async fn with_retry<T, F, Fut>(&self, call: F) -> Result<T, ApiError>+ where+ F: Fn() -> Fut,+ Fut: std::future::Future<Output = Result<T, ApiError>>,+ {let mut attempt = 0;loop {- match self.post_chat(request, body).await {+ match call().await {Ok(v) => return Ok(v),Err(e) => {let class = crate::profiles::classify(e.status, &e.message, chrono::Utc::now())@@ -308,10 +448,26 @@ impl ApiDriver {session: Option<&McpToolSession>,caller: &Caller,event_tx: &mpsc::Sender<RuntimeEvent>,- ) -> Result<(String, usize), ApiError> {+ ) -> Result<(String, usize, bool), ApiError> {let tools = session.map(|s| s.openai_tools()).unwrap_or_default();let max_calls = request.max_calls.max(1);let mut tokens = 0usize;+ if request.stream && tools.is_empty() {+ let mut body = if is_anthropic(request.url) {+ anthropic_body(request.model, &messages, request.max_tokens)+ } else {+ json!({+ "model": request.model,+ "messages": messages,+ "temperature": request.temperature,+ "max_tokens": request.max_tokens,+ })+ };+ body["stream"] = json!(true);+ let resp = self.with_retry(|| self.send_chat(request, &body)).await?;+ let (text, tokens) = stream_reply(resp, is_anthropic(request.url), event_tx).await;+ return Ok((text, tokens, true));+ }for round in 0..max_calls {let body = if is_anthropic(request.url) {anthropic_body(request.model, &messages, request.max_tokens)@@ -335,37 +491,20 @@ impl ApiDriver {return Ok((format!("⚠️ The model request failed after running tools: {e}"),tokens,+ false,))}};- 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;+ tokens += usage_tokens(&reply["usage"]).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()- .map(str::to_string)- .or(anthropic_text);+ let content = reply_text(&reply);let calls = message["tool_calls"].as_array().filter(|c| !c.is_empty());let (Some(calls), Some(session)) = (calls, session) else {return Ok((content.unwrap_or_else(|| "No response content".into()),tokens,+ false,));};if round + 1 == max_calls {@@ -374,7 +513,7 @@ impl ApiDriver {Some(c) => format!("{c}\n\n{note}"),None => note,};- return Ok((text, tokens));+ return Ok((text, tokens, false));}if let Some(c) = content.as_deref().filter(|c| !c.trim().is_empty()) {@@ -436,7 +575,8 @@ 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() {+ let custom = self.custom_base.is_some();+ if !self.env_keys && api_key.is_none() && !custom {return Ok(TurnOutput::refused(crate::profiles::ProviderFailure {class: crate::profiles::FailClass::Auth,retry_at: None,@@ -445,7 +585,7 @@ impl Driver for ApiDriver {}// If target is a real live API endpoint with API key or local Ollama, call HTTP streaming- if api_key.is_some() || is_ollama(target_model) {+ if api_key.is_some() || is_ollama(target_model) || custom {let system_prompt = input.format_system_prompt();let mut messages = vec![json!({"role": "system", "content": system_prompt})];@@ -468,6 +608,11 @@ impl Driver for ApiDriver {_ => input.kwant.max_tokens,};+ if custom && input.model.is_none() {+ return Err(DriverError::Execution(+ "This Custom API account has no model to run: enter a model id for it under Space settings → Accounts, or pin one on the bot (\"custom:<model>\").".into(),+ ));+ }let model = match api_model_name(target_model, input.model.as_deref(), &url, api_key.as_deref(), effort).await {Ok(m) => m,Err(why) => return Err(DriverError::Execution(why)),@@ -481,7 +626,7 @@ impl Driver for ApiDriver {.is_some_and(|c| c.servers.iter().any(|s| s.name != crate::mcp::SELF_SERVER_NAME));if has_user_servers && mcp.is_none() {let _ = event_tx- .send(RuntimeEvent::ThinkingDelta("MCP tools aren't offered on the Anthropic API endpoint; running without them.".into()))+ .send(RuntimeEvent::ThinkingDelta("MCP tools aren't offered over the Anthropic Messages API; running without them.".into())).await;}let session = match mcp {@@ -502,6 +647,7 @@ impl Driver for ApiDriver {temperature: input.kwant.temperature,max_tokens,max_calls: mcp.map(|c| c.max_tool_iterations).unwrap_or(1),+ stream: custom,};let caller = Caller {kwant_id: input.kwant.id.clone(),@@ -512,7 +658,7 @@ impl Driver for ApiDriver {if let Some(session) = session {session.shutdown().await;}- let (text, tokens) = match outcome {+ let (text, tokens, streamed) = match outcome {Ok(done) => done,Err(e) => {let now = chrono::Utc::now();@@ -527,13 +673,16 @@ impl Driver for ApiDriver {}_ => {tracing::warn!(status = ?e.status, "model API call failed");- (format!("⚠️ The model request failed: {e}"), 0)+ (format!("⚠️ The model request failed: {e}"), 0, false)}}}};{- let _ = event_tx.send(RuntimeEvent::TextDelta(text.clone())).await;+ // A streamed reply was sent piece by piece already+ if !streamed {+ let _ = event_tx.send(RuntimeEvent::TextDelta(text.clone())).await;+ }let _ = event_tx.send(RuntimeEvent::TurnComplete {tokens,@@ -634,6 +783,7 @@ mod tests {temperature: 0.7,max_tokens: 100,max_calls: 1,+ stream: false,}}@@ -654,7 +804,7 @@ mod tests {kwant_name: "K".into(),turn_id: "t".into(),};- let (text, tokens) = driver+ let (text, tokens, streamed) = driver.chat_loop(&request(&url, "sk-ant-test-key"),messages,@@ -666,6 +816,7 @@ mod tests {.unwrap();assert_eq!(text, "Hi there");assert_eq!(tokens, 7);+ assert!(!streamed, "a request without stream is read whole");let (headers, body) = seen.lock().unwrap()[0].clone();assert_eq!(headers["x-api-key"], "sk-ant-test-key");@@ -673,6 +824,7 @@ mod tests {assert!(headers.get("authorization").is_none());assert_eq!(body["model"], DEFAULT_CLAUDE_MODEL);assert_eq!(body["system"], "be brief");+ assert!(body.get("stream").is_none(), "existing API-key turns are not streamed");assert!(body.get("temperature").is_none());let roles: Vec<&str> = body["messages"].as_array()diff --git a/src/drivers/custom.rs b/src/drivers/custom.rsnew file mode 100644index 00000000..87b9c0f5--- /dev/null+++ b/src/drivers/custom.rs@@ -0,0 +1,350 @@+//! Custom API accounts: any server speaking the OpenAI Chat Completions or the Anthropic Messages+//! protocol (Agent Maestro, OpenRouter, LM Studio, vLLM, …). Here: the base URL rules, the URLs a+//! turn and a check use, and the check that says whether the server answers and which models it+//! lists. Turns run on [`super::ApiDriver::for_custom`].++use super::engines::{tier_from_name, EngineModel};+use serde::Serialize;+use std::time::Duration;++/// How long a check waits for the server.+const CHECK_TIMEOUT: Duration = Duration::from_secs(10);+const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);+/// Most models a check keeps (OpenRouter lists hundreds).+const MAX_MODELS: usize = 500;+/// Longest base URL or model id accepted.+const MAX_URL_LEN: usize = 2048;+const MAX_MODEL_LEN: usize = 200;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+pub enum Protocol {+ #[serde(rename = "openai-chat")]+ OpenaiChat,+ #[serde(rename = "anthropic-messages")]+ AnthropicMessages,+}++impl Protocol {+ pub fn parse(s: &str) -> Option<Self> {+ match s {+ "openai-chat" => Some(Protocol::OpenaiChat),+ "anthropic-messages" => Some(Protocol::AnthropicMessages),+ _ => None,+ }+ }++ pub fn as_str(self) -> &'static str {+ match self {+ Protocol::OpenaiChat => "openai-chat",+ Protocol::AnthropicMessages => "anthropic-messages",+ }+ }++ /// Whether turns on this protocol get the bot's MCP tools. OpenAI chat sends them as+ /// `tools` and kwnt runs the calls; the Anthropic Messages path has no tool support yet.+ pub fn supports_tools(self) -> bool {+ self == Protocol::OpenaiChat+ }+}++/// Checks a base URL and brings it to the API root that `/chat/completions`, `/messages` and+/// `/models` hang off: http(s) only, no credentials, query or fragment (keys go in the API key+/// field, never the URL), and a pasted endpoint URL cut back to its root. Anthropic roots end+/// in `/v1`, added when missing ("http://127.0.0.1:23333/api/anthropic" works as is). OpenAI+/// roots are kept as given, since not every server puts its API under `/v1`.+pub fn normalize_base(raw: &str, protocol: Protocol) -> Result<String, String> {+ let raw = raw.trim();+ if raw.is_empty() {+ return Err("base_url is required".into());+ }+ if raw.len() > MAX_URL_LEN || raw.chars().any(char::is_control) {+ return Err("base_url is not a valid URL".into());+ }+ let url = url::Url::parse(raw).map_err(|_| "base_url is not a valid URL".to_string())?;+ if !matches!(url.scheme(), "http" | "https") {+ return Err("base_url must start with http:// or https://".into());+ }+ if url.host_str().is_none_or(str::is_empty) {+ return Err("base_url needs a host".into());+ }+ if !url.username().is_empty() || url.password().is_some() {+ return Err("base_url must not contain a user name or password; put the key in api_key".into());+ }+ if url.query().is_some() || url.fragment().is_some() {+ return Err("base_url must not contain ?query or #fragment; put the key in api_key".into());+ }+ let mut path = url.path().trim_end_matches('/').to_string();+ for suffix in ["/chat/completions", "/completions", "/messages", "/models", "/responses"] {+ if let Some(root) = path.strip_suffix(suffix) {+ path = root.trim_end_matches('/').to_string();+ break;+ }+ }+ if protocol == Protocol::AnthropicMessages && !path.ends_with("/v1") {+ path.push_str("/v1");+ }+ let mut root = url.clone();+ root.set_path(&path);+ Ok(root.as_str().trim_end_matches('/').to_string())+}++/// Validates a hand-entered model id: 1 to 200 printable characters, no spaces.+pub fn clean_model(raw: &str) -> Result<Option<String>, String> {+ let model = raw.trim();+ if model.is_empty() {+ return Ok(None);+ }+ if model.chars().count() > MAX_MODEL_LEN || model.chars().any(|c| c.is_whitespace() || c.is_control()) {+ return Err("model must be up to 200 characters with no spaces".into());+ }+ Ok(Some(model.to_string()))+}++/// Where turns go: `{base}/chat/completions` or `{base}/messages`. The Anthropic one ends in+/// `/v1/messages`, which is how [`super::ApiDriver`] tells the protocols apart.+pub fn chat_url(base: &str, protocol: Protocol) -> String {+ match protocol {+ Protocol::OpenaiChat => format!("{base}/chat/completions"),+ Protocol::AnthropicMessages => format!("{base}/messages"),+ }+}++pub fn models_url(base: &str) -> String {+ format!("{base}/models")+}++/// The message for a server that doesn't answer at all.+pub fn not_answering(base: &str) -> String {+ format!("Nothing is answering at {base}. Is Agent Maestro / the server running?")+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum CheckStatus {+ /// The server answered: turns can run.+ Ready,+ /// Connection refused, DNS failure or timeout.+ Unreachable,+ /// 401/403: the key is missing or refused.+ KeyRejected,+ /// Anything else (unexpected status, no models and none entered).+ Error,+}++/// One check of a Custom API account.+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct CustomCheck {+ pub status: CheckStatus,+ /// Readable, never contains the key.+ pub detail: String,+ /// What the server listed; empty when it lists none.+ pub models: Vec<EngineModel>,+ pub checked_at: chrono::DateTime<chrono::Utc>,+}++impl CustomCheck {+ pub fn new(status: CheckStatus, detail: impl Into<String>, models: Vec<EngineModel>) -> Self {+ Self { status, detail: detail.into(), models, checked_at: chrono::Utc::now() }+ }++ pub fn ready(&self) -> bool {+ self.status == CheckStatus::Ready+ }+}++/// The models in a `GET /models` body: OpenAI's and Anthropic's `{"data": [{"id": …}]}`, with+/// `display_name` (Anthropic) or `name` (OpenRouter) as the label. `model`, the account's own+/// model, is marked as the default when listed. `None` when the body isn't a model list.+pub fn parse_models(body: &serde_json::Value, model: Option<&str>) -> Option<Vec<EngineModel>> {+ let data = body.get("data").or_else(|| body.get("models"))?.as_array()?;+ let mut models: Vec<EngineModel> = data+ .iter()+ .filter_map(|m| {+ let id = m["id"].as_str().or_else(|| m.as_str())?.trim();+ if id.is_empty() || id.len() > MAX_MODEL_LEN {+ return None;+ }+ let label = m["display_name"].as_str().or_else(|| m["name"].as_str()).unwrap_or(id);+ Some(EngineModel {+ id: id.to_string(),+ label: crate::profiles::classify::redact_detail(label, 120),+ default: model.is_some_and(|d| d.eq_ignore_ascii_case(id)),+ tier: tier_from_name(id),+ })+ })+ .take(MAX_MODELS)+ .collect();+ let mut seen = std::collections::HashSet::new();+ models.retain(|m| seen.insert(m.id.clone()));+ Some(models)+}++/// Asks the server for its models: ready when it answers, else why not. A server without a+/// model list (Agent Maestro's OpenAI side) is ready when the account names a model.+pub async fn check(protocol: Protocol, base: &str, key: Option<&str>, model: Option<&str>) -> CustomCheck {+ let Ok(client) = reqwest::Client::builder()+ .timeout(CHECK_TIMEOUT)+ .connect_timeout(CONNECT_TIMEOUT)+ .build()+ else {+ return CustomCheck::new(CheckStatus::Error, "Couldn't start the check", Vec::new());+ };+ let mut req = client.get(models_url(base));+ if protocol == Protocol::AnthropicMessages {+ req = req.header("anthropic-version", super::api::ANTHROPIC_VERSION);+ }+ if let Some(key) = key {+ req = match protocol {+ Protocol::AnthropicMessages => req.header("x-api-key", key),+ Protocol::OpenaiChat => req.bearer_auth(key),+ };+ }+ let resp = match req.send().await {+ Ok(r) => r,+ Err(e) if e.is_timeout() => {+ return CustomCheck::new(+ CheckStatus::Unreachable,+ format!("{base} didn't answer within {}s. Is the server running and reachable from this machine?", CHECK_TIMEOUT.as_secs()),+ Vec::new(),+ )+ }+ Err(_) => return CustomCheck::new(CheckStatus::Unreachable, not_answering(base), Vec::new()),+ };+ let status = resp.status();+ let body = resp.text().await.unwrap_or_default();+ let listed = serde_json::from_str::<serde_json::Value>(&body)+ .ok()+ .and_then(|v| parse_models(&v, model));+ let using = |why: &str| {+ model.map(|m| CustomCheck::new(CheckStatus::Ready, format!("{why}; using {m}"), Vec::new()))+ };+ match status.as_u16() {+ 200..=299 => match listed {+ Some(models) if !models.is_empty() => {+ let n = models.len();+ let detail = format!("Connected · {n} model{}", if n == 1 { "" } else { "s" });+ CustomCheck::new(CheckStatus::Ready, detail, models)+ }+ _ => using("Connected; the server lists no models").unwrap_or_else(|| {+ CustomCheck::new(+ CheckStatus::Error,+ "Connected, but the server lists no models. Enter a model id for this account.",+ Vec::new(),+ )+ }),+ },+ 401 | 403 => CustomCheck::new(+ CheckStatus::KeyRejected,+ match key {+ Some(_) => format!("The server refused the API key (HTTP {}). Check the key.", status.as_u16()),+ None => format!("The server needs an API key (HTTP {}). Add one to this account.", status.as_u16()),+ },+ Vec::new(),+ ),+ 404 | 405 | 501 => using("Connected; this server doesn't list its models").unwrap_or_else(|| {+ let hint = if base.ends_with("/v1") {+ ""+ } else {+ " Most servers' base URL ends in /v1."+ };+ CustomCheck::new(+ CheckStatus::Error,+ format!(+ "{} has no model list (HTTP {}). Enter a model id for this account (Agent Maestro's OpenAI side needs one).{hint}",+ models_url(base),+ status.as_u16()+ ),+ Vec::new(),+ )+ }),+ 429 => CustomCheck::new(+ CheckStatus::Error,+ "The server is rate-limiting requests (HTTP 429). Try again in a minute.",+ Vec::new(),+ ),+ code => CustomCheck::new(+ CheckStatus::Error,+ format!("The server answered HTTP {code}: {}", super::api::error_message(&body)),+ Vec::new(),+ ),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn base_urls_normalize_to_the_api_root() {+ let oa = Protocol::OpenaiChat;+ let an = Protocol::AnthropicMessages;+ assert_eq!(normalize_base("http://localhost:1234/v1/", oa).unwrap(), "http://localhost:1234/v1");+ assert_eq!(+ normalize_base(" https://openrouter.ai/api/v1/chat/completions ", oa).unwrap(),+ "https://openrouter.ai/api/v1"+ );+ assert_eq!(+ normalize_base("http://127.0.0.1:23333/api/openai/v1", oa).unwrap(),+ "http://127.0.0.1:23333/api/openai/v1"+ );+ // OpenAI roots aren't guessed: Gemini's is /v1beta/openai+ assert_eq!(+ normalize_base("https://generativelanguage.googleapis.com/v1beta/openai/", oa).unwrap(),+ "https://generativelanguage.googleapis.com/v1beta/openai"+ );+ assert_eq!(+ normalize_base("http://127.0.0.1:23333/api/anthropic", an).unwrap(),+ "http://127.0.0.1:23333/api/anthropic/v1"+ );+ assert_eq!(+ normalize_base("http://127.0.0.1:23333/api/anthropic/v1/messages", an).unwrap(),+ "http://127.0.0.1:23333/api/anthropic/v1"+ );+ assert_eq!(normalize_base("http://localhost:8080", oa).unwrap(), "http://localhost:8080");+ }++ #[test]+ fn base_urls_with_secrets_or_odd_schemes_are_refused() {+ let oa = Protocol::OpenaiChat;+ for bad in [+ "",+ "localhost:1234",+ "ftp://host/v1",+ "file:///etc/passwd",+ "http://user:sk-secret@host/v1",+ "http://host/v1?key=sk-secret",+ "http://host/v1#frag",+ ] {+ let err = normalize_base(bad, oa).unwrap_err();+ assert!(!err.contains("sk-secret"), "{bad}: {err}");+ }+ }++ #[test]+ fn model_ids_are_checked() {+ assert_eq!(clean_model(" ").unwrap(), None);+ assert_eq!(clean_model(" gpt-5.5 ").unwrap().as_deref(), Some("gpt-5.5"));+ assert!(clean_model("two words").is_err());+ assert!(clean_model(&"x".repeat(201)).is_err());+ }++ #[test]+ fn model_lists_parse_openai_anthropic_and_openrouter_shapes() {+ let body = serde_json::json!({"data": [+ {"id": "claude-sonnet-4.6", "display_name": "Claude Sonnet 4.6"},+ {"id": "gpt-5.5", "object": "model"},+ {"id": "openai/gpt-4o-mini", "name": "OpenAI: GPT-4o mini"},+ {"id": "gpt-5.5"},+ {"id": ""}+ ]});+ let models = parse_models(&body, Some("GPT-5.5")).unwrap();+ let ids: Vec<&str> = models.iter().map(|m| m.id.as_str()).collect();+ assert_eq!(ids, ["claude-sonnet-4.6", "gpt-5.5", "openai/gpt-4o-mini"]);+ assert_eq!(models[0].label, "Claude Sonnet 4.6");+ assert_eq!(models[2].label, "OpenAI: GPT-4o mini");+ assert!(models[1].default && !models[0].default);+ assert_eq!(models[0].tier, Some(super::super::engines::Tier::Balanced));+ assert_eq!(models[2].tier, Some(super::super::engines::Tier::Fast));+ assert!(parse_models(&serde_json::json!({"error": "nope"}), None).is_none());+ }+}diff --git a/src/drivers/engines.rs b/src/drivers/engines.rsindex 7b5116aa..c4dba4d0 100644--- a/src/drivers/engines.rs+++ b/src/drivers/engines.rs@@ -28,6 +28,8 @@ pub enum EngineId {OpenaiApi,XaiApi,Ollama,+ /// The space's Custom API accounts (OpenAI-compatible or Anthropic-compatible servers).+ CustomApi,}#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]@@ -115,7 +117,7 @@ pub fn codex_tier(slug: &str, description: Option<&str>) -> Option<Tier> {impl EngineId {/// Every engine, in the order the API lists them.- pub const ALL: [EngineId; 7] = [+ pub const ALL: [EngineId; 8] = [EngineId::Claude,EngineId::Codex,EngineId::Grok,@@ -123,6 +125,7 @@ impl EngineId {EngineId::OpenaiApi,EngineId::XaiApi,EngineId::Ollama,+ EngineId::CustomApi,];pub fn name(self) -> &'static str {@@ -134,13 +137,16 @@ impl EngineId {EngineId::OpenaiApi => "OpenAI API",EngineId::XaiApi => "xAI API",EngineId::Ollama => "Ollama",+ EngineId::CustomApi => "Custom API",}}pub fn kind(self) -> EngineKind {match self {EngineId::Claude | EngineId::Codex | EngineId::Grok => EngineKind::Cli,- EngineId::AnthropicApi | EngineId::OpenaiApi | EngineId::XaiApi => EngineKind::Api,+ EngineId::AnthropicApi | EngineId::OpenaiApi | EngineId::XaiApi | EngineId::CustomApi => {+ EngineKind::Api+ }EngineId::Ollama => EngineKind::Local,}}@@ -155,6 +161,7 @@ impl EngineId {EngineId::OpenaiApi => "openai_api",EngineId::XaiApi => "xai_api",EngineId::Ollama => "ollama",+ EngineId::CustomApi => "custom_api",}}@@ -168,15 +175,18 @@ impl EngineId {EngineId::Claude | EngineId::AnthropicApi => Some(Engine::Claude),EngineId::Codex | EngineId::OpenaiApi => Some(Engine::Codex),EngineId::Grok | EngineId::XaiApi => Some(Engine::Grok),+ EngineId::CustomApi => Some(Engine::Custom),EngineId::Ollama => None,}}+ /// For Custom API both are [`EngineId::CustomApi`]: it has no CLI.pub fn of_family(engine: Engine) -> (EngineId, EngineId) {match engine {Engine::Claude => (EngineId::Claude, EngineId::AnthropicApi),Engine::Codex => (EngineId::Codex, EngineId::OpenaiApi),Engine::Grok => (EngineId::Grok, EngineId::XaiApi),+ Engine::Custom => (EngineId::CustomApi, EngineId::CustomApi),}}}@@ -342,6 +352,9 @@ pub async fn probe_within(id: EngineId, env: &ProbeEnv, limit: Duration) -> ProbEngineId::Grok => probe_grok(env.grok_bin.as_deref()).await,EngineId::AnthropicApi | EngineId::OpenaiApi | EngineId::XaiApi => probe_api(id, env).await,EngineId::Ollama => probe_ollama(env).await,+ // Nothing on the host to check: each account is checked on its own (see+ // `drivers::custom`), and a space's report is ready through its accounts+ EngineId::CustomApi => Probe::new(EngineStatus::NotInstalled, Some(CUSTOM_API_DETAIL.into())),}};// Dropping the check kills its commands (kill_on_drop) and aborts its requests.@@ -854,6 +867,13 @@ impl EngineRegistry {}}+/// What Engines says about Custom API, which has nothing on the host to check.+pub const CUSTOM_API_DETAIL: &str = "Runs on this space's Custom API accounts: add one under Space settings → Accounts";++/// A turn on Custom API with no account of the space that can take it.+pub const NO_CUSTOM_ACCOUNT: &str =+ "No Custom API account is on in this space. Add one under Space settings → Accounts.";+/// The model a turn runs on one engine.#[derive(Debug, Clone, PartialEq)]pub struct ModelChoice {@@ -948,6 +968,10 @@ pub fn system_route(let Some(family) = Engine::from_model(target_model) else {return Err(format!("No engine runs the model '{target_model}'. Pick another in the bot's settings."));};+ // Never the host's env keys or CLIs: only the space's own accounts run it+ if family == Engine::Custom {+ return Err(NO_CUSTOM_ACCOUNT.into());+ }let (cli, api) = EngineId::of_family(family);if let Some(key) = key_for(api, configured_key) {if engines.usable(api, true) {diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex 5e53830f..bb51440f 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -1,5 +1,6 @@pub mod api;pub mod cli;+pub mod custom;pub mod engines;pub mod events;pub mod grok;@@ -254,6 +255,7 @@ pub async fn detect_available_models(Engine::Claude => "Claude",Engine::Grok => "Grok",Engine::Codex => "OpenAI Codex",+ Engine::Custom => unreachable!("Custom API is offered below"),};available.push(ModelDescriptor {id: family.as_str().into(),@@ -263,6 +265,16 @@ pub async fn detect_available_models(});}+ // Custom API: only through the space's own accounts, never the host's+ if profile_engines.contains(&Engine::Custom) && engines.is_enabled(EngineId::CustomApi) {+ available.push(ModelDescriptor {+ id: Engine::Custom.as_str().into(),+ display_name: "Custom API".into(),+ capability_desc: "this space's own model server (Agent Maestro, OpenRouter, LM Studio …): general questions, coding and writing".into(),+ is_cli: false,+ });+ }+// Local Ollama: before its first check, the old quick look at the server decides.let ollama = engines.report(EngineId::Ollama);let model = match ollama.status {diff --git a/src/profiles/login.rs b/src/profiles/login.rsindex e864a472..1aefcbb0 100644--- a/src/profiles/login.rs+++ b/src/profiles/login.rs@@ -155,6 +155,9 @@ impl LoginManager {Engine::Claude => cmd.args(["auth", "login", "--claudeai"]),Engine::Codex => cmd.args(["login", "--device-auth"]),Engine::Grok => cmd.args(["login", "--device-auth"]),+ Engine::Custom => {+ return Err(StartError::Failed("Custom API accounts use an API key, not a sign-in".into()))+ }};if home.is_dir() {cmd.current_dir(home);diff --git a/src/profiles/mod.rs b/src/profiles/mod.rsindex 72073c0d..0c28b4fd 100644--- a/src/profiles/mod.rs+++ b/src/profiles/mod.rs@@ -21,6 +21,9 @@ pub enum Engine {Claude,Codex,Grok,+ /// A Custom API account: any OpenAI-compatible or Anthropic-compatible server (Agent+ /// Maestro, OpenRouter, LM Studio, …). Only ever runs on the space's own accounts.+ Custom,}impl Engine {@@ -29,6 +32,7 @@ impl Engine {"claude" => Some(Engine::Claude),"codex" => Some(Engine::Codex),"grok" => Some(Engine::Grok),+ "custom" => Some(Engine::Custom),_ => None,}}@@ -36,7 +40,10 @@ impl Engine {/// 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") {+ // "custom:claude-sonnet-4.6" runs on a Custom API account, not on Claude's+ if model == "custom" || model.starts_with("custom:") || model.starts_with("custom/") {+ Some(Engine::Custom)+ } else if model.contains("claude") {Some(Engine::Claude)} else if model.contains("grok") {Some(Engine::Grok)@@ -52,6 +59,7 @@ impl Engine {Engine::Claude => "claude",Engine::Codex => "codex",Engine::Grok => "grok",+ Engine::Custom => "custom",}}@@ -61,6 +69,8 @@ impl Engine {Engine::Claude => "CLAUDE_CONFIG_DIR",Engine::Codex => "CODEX_HOME",Engine::Grok => "GROK_HOME",+ // No CLI; never set (see `system_home`)+ Engine::Custom => "KWNT_CUSTOM_API_HOME",}}@@ -98,6 +108,7 @@ impl Engine {],Engine::Codex => &["OPENAI_API_KEY", "CODEX_API_KEY"],Engine::Grok => &["XAI_API_KEY", "GROK_AUTH_PATH"],+ Engine::Custom => &[],}}@@ -116,7 +127,7 @@ impl Engine {"ANTHROPIC_AWS_","VERTEX_REGION_",],- Engine::Codex | Engine::Grok => &[],+ Engine::Codex | Engine::Grok | Engine::Custom => &[],}}@@ -126,6 +137,8 @@ impl Engine {Engine::Claude => "anthropic_api_key",Engine::Codex => "openai_api_key",Engine::Grok => "xai_api_key",+ // Never stored: a Custom API key lives with its account only+ Engine::Custom => "custom_api_key",}}@@ -135,11 +148,15 @@ impl Engine {Engine::Claude => "claude",Engine::Codex => "codex",Engine::Grok => "grok",+ Engine::Custom => "custom",}}/// The CLI's own config dir when kwnt doesn't set one: what the system profile uses.pub fn system_home(self) -> Option<PathBuf> {+ if self == Engine::Custom {+ return None;+ }let from_env = std::env::var_os(self.home_env()).filter(|v| !v.is_empty()).map(PathBuf::from);@@ -149,6 +166,7 @@ impl Engine {Engine::Claude => ".claude",Engine::Codex => ".codex",Engine::Grok => ".grok",+ Engine::Custom => unreachable!("Custom API has no CLI home"),})})})@@ -225,7 +243,7 @@ impl CliEnv {.collect();vec!["--settings".into(), serde_json::json!({ "env": env }).to_string()]}- Engine::Codex | Engine::Grok => Vec::new(),+ Engine::Codex | Engine::Grok | Engine::Custom => Vec::new(),};Self {set: vec![(engine.home_env().to_string(), home.as_os_str().to_owned())],diff --git a/src/profiles/status.rs b/src/profiles/status.rsindex b94e2ced..5d157b92 100644--- a/src/profiles/status.rs+++ b/src/profiles/status.rs@@ -29,6 +29,8 @@ pub struct ProfileManager {pub data_dir: PathBuf,pub logins: LoginManager,cache: Mutex<HashMap<String, (Instant, ProfileStatus)>>,+ /// The last check of each Custom API account: its status and the models it lists.+ custom: Mutex<HashMap<String, (Instant, crate::drivers::custom::CustomCheck)>>,}impl ProfileManager {@@ -37,6 +39,7 @@ impl ProfileManager {data_dir,logins: LoginManager::default(),cache: Mutex::new(HashMap::new()),+ custom: Mutex::new(HashMap::new()),}}@@ -59,6 +62,37 @@ impl ProfileManager {pub fn invalidate(&self, id: &str) {self.cache.lock().unwrap().remove(id);+ self.custom.lock().unwrap().remove(id);+ }++ /// Records a Custom API account's check; "ready" counts as signed in.+ pub fn set_custom(&self, id: &str, check: crate::drivers::custom::CustomCheck) {+ self.set_status(+ id,+ ProfileStatus {+ signed_in: Some(check.ready()),+ account_label: Some(check.detail.clone()),+ },+ );+ self.custom+ .lock()+ .unwrap()+ .insert(id.to_string(), (Instant::now(), check));+ }++ /// A Custom API account's last check, if still fresh.+ pub fn custom_check(&self, id: &str) -> Option<crate::drivers::custom::CustomCheck> {+ self.custom+ .lock()+ .unwrap()+ .get(id)+ .filter(|(at, _)| at.elapsed() < STATUS_TTL)+ .map(|(_, c)| c.clone())+ }++ /// A Custom API account's last check, however old.+ pub fn last_custom_check(&self, id: &str) -> Option<crate::drivers::custom::CustomCheck> {+ self.custom.lock().unwrap().get(id).map(|(_, c)| c.clone())}/// Profiles whose last check said signed out, for failover to skip.@@ -107,6 +141,13 @@ impl ProfileManager {);continue;}+ if p.kind == "custom_api" {+ // Checked over HTTP by the caller (`profile_turn::refresh_custom`), never by a CLI+ if let Some((_, s)) = cache.get(&p.id) {+ out.insert(p.id.clone(), s.clone());+ }+ continue;+ }match cache.get(&p.id) {Some((at, s)) if at.elapsed() < STATUS_TTL => {out.insert(p.id.clone(), s.clone());diff --git a/src/router/mod.rs b/src/router/mod.rsindex 4896d9e5..8600835f 100644--- a/src/router/mod.rs+++ b/src/router/mod.rs@@ -60,6 +60,7 @@ fn family_id(name: &str) -> Option<&'static str> {"claude" => Some("claude"),"codex" => Some("codex"),"grok" => Some("grok"),+ "custom" => Some("custom"),"ollama" | "local_ollama" => Some("local_ollama"),_ => None,}diff --git a/src/server/mod.rs b/src/server/mod.rsindex 5a1974e1..ccfc0ca2 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -125,6 +125,7 @@ pub fn create_router(state: AppState) -> Router {.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/check", post(profile_routes::check)).route("/api/profiles/:id/login", post(profile_routes::start_login)).route("/api/profiles/:id/login/:flow_id",diff --git a/src/server/profile_routes.rs b/src/server/profile_routes.rsindex ea0fe8e9..fbbc5f2a 100644--- a/src/server/profile_routes.rs+++ b/src/server/profile_routes.rs@@ -57,6 +57,27 @@ pub struct ProfileOut {pub limited_until: Option<chrono::DateTime<chrono::Utc>>,/// "quota" or "auth" from the last refused turn.pub last_error: Option<String>,+ /// A Custom API account's server and last check; `None` for every other kind.+ pub custom: Option<CustomOut>,+}++/// A Custom API account's server, as the API shows it (never its key).+#[derive(Debug, Serialize)]+pub struct CustomOut {+ /// "openai-chat" or "anthropic-messages".+ pub protocol: String,+ pub base_url: String,+ /// The model entered by hand, if any.+ pub model: Option<String>,+ /// "ready", "unreachable", "key_rejected" or "error"; `None` before the first check.+ pub status: Option<crate::drivers::custom::CheckStatus>,+ /// Readable: "Connected · 12 models", or why not.+ pub detail: Option<String>,+ /// What the server listed at the last check.+ pub models: Vec<crate::drivers::engines::EngineModel>,+ pub checked_at: Option<chrono::DateTime<chrono::Utc>>,+ /// Whether turns on it can call MCP tools (OpenAI chat: yes; Anthropic Messages: not yet).+ pub supports_tools: bool,}/// Profiles that count as signed in through a key: their own, or for a system profile the@@ -87,6 +108,15 @@ pub(super) async fn keyed_ids(state: &AppState, profiles: &[LlmProfile]) -> Hash}async fn views(state: &AppState, profiles: Vec<LlmProfile>) -> Vec<ProfileOut> {+ let endpoints = state.db.list_profile_endpoints().await.unwrap_or_default();+ // Stale checks of Custom API accounts run together, each bounded by its own timeout+ futures::future::join_all(+ profiles+ .iter()+ .filter(|p| p.kind == "custom_api")+ .map(|p| super::profile_turn::refresh_custom(state, p, false)),+ )+ .await;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();@@ -96,7 +126,22 @@ async fn views(state: &AppState, profiles: Vec<LlmProfile>) -> Vec<ProfileOut> {.map(|p| {let st = states.get(&p.id);let status = statuses.get(&p.id).cloned().unwrap_or_default();+ let custom = endpoints.get(&p.id).map(|e| {+ let check = state.profiles.last_custom_check(&p.id);+ CustomOut {+ supports_tools: crate::drivers::custom::Protocol::parse(&e.protocol)+ .is_some_and(|p| p.supports_tools()),+ protocol: e.protocol.clone(),+ base_url: e.base_url.clone(),+ model: e.model.clone(),+ status: check.as_ref().map(|c| c.status),+ detail: check.as_ref().map(|c| c.detail.clone()),+ checked_at: check.as_ref().map(|c| c.checked_at),+ models: check.map(|c| c.models).unwrap_or_default(),+ }+ });ProfileOut {+ custom,home_dir: state.profiles.home_of(&p)@@ -156,6 +201,44 @@ pub struct CreateBody {enabled: Option<bool>,is_default: Option<bool>,api_key: Option<String>,+ /// Custom API only: "openai-chat" or "anthropic-messages".+ protocol: Option<String>,+ /// Custom API only: the server's API root, e.g. `http://localhost:23333/api/openai/v1`.+ base_url: Option<String>,+ /// Custom API only: a model id, for servers that don't list theirs.+ model: Option<String>,+}++/// A Custom API account's server from a create or patch body, validated.+#[allow(clippy::result_large_err)]+fn custom_endpoint(+ profile_id: &str,+ protocol: Option<&str>,+ base_url: Option<&str>,+ model: Option<&str>,+ current: Option<&crate::db::custom_api::ProfileEndpoint>,+) -> Result<crate::db::custom_api::ProfileEndpoint, Response> {+ use crate::drivers::custom::{clean_model, normalize_base, Protocol};+ let protocol = match protocol.or(current.map(|c| c.protocol.as_str())) {+ Some(raw) => Protocol::parse(raw).ok_or_else(|| {+ err(StatusCode::BAD_REQUEST, "protocol must be openai-chat or anthropic-messages")+ })?,+ None => return Err(err(StatusCode::BAD_REQUEST, "protocol is required")),+ };+ let base_url = match base_url.or(current.map(|c| c.base_url.as_str())) {+ Some(raw) => normalize_base(raw, protocol).map_err(|e| err(StatusCode::BAD_REQUEST, e))?,+ None => return Err(err(StatusCode::BAD_REQUEST, "base_url is required")),+ };+ let model = match model {+ Some(raw) => clean_model(raw).map_err(|e| err(StatusCode::BAD_REQUEST, e))?,+ None => current.and_then(|c| c.model.clone()),+ };+ Ok(crate::db::custom_api::ProfileEndpoint {+ profile_id: profile_id.to_string(),+ protocol: protocol.as_str().into(),+ base_url,+ model,+ })}/// `POST /api/profiles`@@ -163,19 +246,41 @@ pub async fn create(State(state): State<AppState>, Scope(space): Scope, Json(bodlet Some(engine) = Engine::parse(&body.engine) else {return err(StatusCode::BAD_REQUEST,- "engine must be claude, codex or grok",+ "engine must be claude, codex, grok or custom",);};+ let is_custom = engine == Engine::Custom;+ if is_custom != (body.kind == "custom_api") {+ return err(StatusCode::BAD_REQUEST, "engine custom goes with kind custom_api, and only with it");+ }+ if !is_custom && (body.protocol.is_some() || body.base_url.is_some() || body.model.is_some()) {+ return err(StatusCode::BAD_REQUEST, "protocol, base_url and model only go with kind custom_api");+ }+ if is_custom && !state.db.custom_api_ready().await {+ return err(+ StatusCode::SERVICE_UNAVAILABLE,+ "Custom API accounts are unavailable: the database couldn't be updated for them (see the log)",+ );+ }+ // Validated before anything is stored; the id is filled in once the profile exists+ let endpoint = if is_custom {+ match custom_endpoint("", body.protocol.as_deref(), body.base_url.as_deref(), body.model.as_deref(), None) {+ Ok(e) => Some(e),+ Err(r) => return r,+ }+ } else {+ None+ };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) {+ ("api_key" | "custom_api", Some(k)) => match clean_key(k) {Ok(k) => Some(k),Err(e) => return err(StatusCode::BAD_REQUEST, e),},- ("api_key", None) => None,+ ("api_key" | "custom_api", None) => None,("cli_home", Some(_)) => {return err(StatusCode::BAD_REQUEST,@@ -183,7 +288,7 @@ pub async fn create(State(state): State<AppState>, Scope(space): Scope, Json(bod)}("cli_home", None) => None,- _ => return err(StatusCode::BAD_REQUEST, "kind must be cli_home or api_key"),+ _ => return err(StatusCode::BAD_REQUEST, "kind must be cli_home, api_key or custom_api"),};let all = match state.db.list_profiles(&space).await {Ok(a) => a,@@ -209,7 +314,7 @@ pub async fn create(State(state): State<AppState>, Scope(space): Scope, Json(bodErr(e) => return err(StatusCode::BAD_REQUEST, e),}}- ("api_key", Some(_)) => {+ ("api_key" | "custom_api", Some(_)) => {return err(StatusCode::BAD_REQUEST,"home_dir only goes with kind cli_home",@@ -240,12 +345,21 @@ pub async fn create(State(state): State<AppState>, Scope(space): Scope, Json(bod);}}+ if let Some(mut endpoint) = endpoint {+ endpoint.profile_id = profile.id.clone();+ if let Err(e) = state.db.set_profile_endpoint(&endpoint).await {+ let _ = state.db.delete_profile(&profile.id).await;+ return db_err(e);+ }+ }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);}}+ // Checked at once, so the response already says whether the server answers+ super::profile_turn::refresh_custom(&state, &profile, true).await;let mut resp = view_of(&state, &profile.id).await;*resp.status_mut() = StatusCode::CREATED;resp@@ -258,6 +372,11 @@ pub struct PatchBody {priority: Option<i64>,enabled: Option<bool>,is_default: Option<bool>,+ /// Custom API only.+ protocol: Option<String>,+ base_url: Option<String>,+ /// Custom API only: `""` clears it.+ model: Option<String>,}/// `PATCH /api/profiles/:id`@@ -286,6 +405,31 @@ pub async fn update("the default profile can't be disabled",);}+ let server_change = body.protocol.is_some() || body.base_url.is_some() || body.model.is_some();+ if server_change {+ if existing.kind != "custom_api" {+ return err(StatusCode::BAD_REQUEST, "protocol, base_url and model only go with kind custom_api");+ }+ let current = match state.db.get_profile_endpoint(&id).await {+ Ok(c) => c,+ Err(e) => return db_err(e),+ };+ let endpoint = match custom_endpoint(+ &id,+ body.protocol.as_deref(),+ body.base_url.as_deref(),+ body.model.as_deref(),+ current.as_ref(),+ ) {+ Ok(e) => e,+ Err(r) => return r,+ };+ if let Err(e) = state.db.set_profile_endpoint(&endpoint).await {+ return db_err(e);+ }+ let _ = state.db.clear_profile_state(&id).await;+ state.profiles.invalidate(&id);+ }let patch = LlmProfilePatch {name,priority: body.priority.map(|p| p.clamp(0, 10_000)),@@ -293,7 +437,12 @@ pub async fn update(is_default: body.is_default,};match state.db.update_profile(&id, &patch).await {- Ok(Some(_)) => view_of(&state, &id).await,+ Ok(Some(p)) => {+ if server_change {+ super::profile_turn::refresh_custom(&state, &p, true).await;+ }+ view_of(&state, &id).await+ }Ok(None) => err(StatusCode::NOT_FOUND, "no such profile"),Err(e) => db_err(e),}@@ -337,8 +486,8 @@ pub async fn set_key(Ok(p) => p,Err(r) => return r,};- if existing.kind != "api_key" {- return err(StatusCode::BAD_REQUEST, "only api_key profiles hold a key");+ if existing.kind != "api_key" && existing.kind != "custom_api" {+ return err(StatusCode::BAD_REQUEST, "only api_key and custom_api profiles hold a key");}let key = match clean_key(&body.api_key) {Ok(k) => k,@@ -352,6 +501,20 @@ pub async fn set_key(StatusCode::NO_CONTENT.into_response()}+/// `POST /api/profiles/:id/check`: checks a Custom API account's server again now and returns+/// the account.+pub async fn check(State(state): State<AppState>, Path(id): Path<String>) -> Response {+ let p = match load(&state, &id).await {+ Ok(p) => p,+ Err(r) => return r,+ };+ if p.kind != "custom_api" {+ return err(StatusCode::BAD_REQUEST, "only custom_api profiles are checked this way");+ }+ super::profile_turn::refresh_custom(&state, &p, true).await;+ view_of(&state, &id).await+}+/// `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 {diff --git a/src/server/profile_turn.rs b/src/server/profile_turn.rsindex fd3bfc5f..b6b00156 100644--- a/src/server/profile_turn.rs+++ b/src/server/profile_turn.rs@@ -115,6 +115,13 @@ pub async fn driver_for(.map(|(d, e)| (d, Some(e)));};let engine = Engine::parse(&p.engine).unwrap_or(Engine::Claude);+ if p.kind == "custom_api" {+ let (endpoint, key) = custom_endpoint(state, p).await?;+ let protocol = crate::drivers::custom::Protocol::parse(&endpoint.protocol)+ .ok_or_else(|| format!("Custom API account \"{}\" has an unknown protocol", p.name))?;+ let chat = crate::drivers::custom::chat_url(&endpoint.base_url, protocol);+ return Ok((Box::new(ApiDriver::for_custom(key, chat, endpoint.base_url)), None));+ }if p.kind == "api_key" {let key = state.db@@ -139,6 +146,75 @@ pub async fn driver_for())}+/// A Custom API account's server and key. `Err` when its server was never saved.+pub async fn custom_endpoint(+ state: &AppState,+ p: &LlmProfile,+) -> Result<(crate::db::custom_api::ProfileEndpoint, Option<String>), String> {+ let endpoint = state+ .db+ .get_profile_endpoint(&p.id)+ .await+ .ok()+ .flatten()+ .ok_or_else(|| format!("Custom API account \"{}\" has no server set", p.name))?;+ let key = state.db.get_profile_key(&p.id).await.ok().flatten().map(|k| k.0);+ Ok((endpoint, key))+}++/// Checks a Custom API account against its server (GET {base}/models) and caches the result.+/// Reuses a fresh check unless `force`.+pub async fn refresh_custom(+ state: &AppState,+ p: &LlmProfile,+ force: bool,+) -> Option<crate::drivers::custom::CustomCheck> {+ use crate::drivers::custom::{check, CheckStatus, CustomCheck, Protocol};+ if p.kind != "custom_api" {+ return None;+ }+ if !force {+ if let Some(c) = state.profiles.custom_check(&p.id) {+ return Some(c);+ }+ }+ let result = match custom_endpoint(state, p).await {+ Ok((endpoint, key)) => match Protocol::parse(&endpoint.protocol) {+ Some(proto) => check(proto, &endpoint.base_url, key.as_deref(), endpoint.model.as_deref()).await,+ None => CustomCheck::new(CheckStatus::Error, "Unknown protocol", Vec::new()),+ },+ Err(e) => CustomCheck::new(CheckStatus::Error, e, Vec::new()),+ };+ state.profiles.set_custom(&p.id, result.clone());+ Some(result)+}++/// The model a turn on a Custom API account runs: the bot's pinned model as is (the server+/// knows its own ids best), else the account's own model, else the one its server lists for the+/// tier. `None` when none is known; the driver then says so.+pub async fn custom_model(+ state: &AppState,+ p: &LlmProfile,+ pinned: Option<&str>,+ tier: crate::drivers::engines::Tier,+) -> Option<crate::drivers::engines::ModelChoice> {+ use crate::drivers::engines::{choose_model, ModelChoice};+ let named = |id: &str| ModelChoice {+ id: id.to_string(),+ label: id.to_string(),+ tier: crate::drivers::engines::tier_from_name(id),+ };+ if let Some(pin) = pinned.map(str::trim).filter(|m| !m.is_empty()) {+ return Some(named(pin));+ }+ let stored = state.db.get_profile_endpoint(&p.id).await.ok().flatten().and_then(|e| e.model);+ if let Some(m) = stored {+ return Some(named(&m));+ }+ let models = refresh_custom(state, p, false).await.map(|c| c.models).unwrap_or_default();+ choose_model(&models, None, tier)+}+/// `family`'s own accounts (not the system profile) that pass `bar` and whose engine is on,/// in the order failover prefers them. The one rule for "this account can take a turn".fn own_accounts<'a>(@@ -164,7 +240,7 @@ pub async fn profile_engines(state: &AppState, space: &SpaceId) -> HashSet<Enginlet Some((profiles, avail)) = accounts(state, space).await else {return HashSet::new();};- [Engine::Claude, Engine::Codex, Engine::Grok]+ [Engine::Claude, Engine::Codex, Engine::Grok, Engine::Custom].into_iter().filter(|f| !own_accounts(state, &profiles, *f, &avail, SignInBar::NotSignedOut).is_empty()).collect()@@ -189,7 +265,8 @@ pub fn readiness(};let system = |p: &&LlmProfile| p.kind == "system";let host_off = profiles.iter().any(|p| system(&p) && p.engine == family.as_str() && !p.enabled);- let host = host && !host_off;+ // Custom API runs only on the space's own accounts, never on anything of the host's+ let host = host && !host_off && family != Engine::Custom;let picked = preference_order(profiles, family, None).into_iter().filter(|p| system(p) || profile_engine(p) == Some(report.id))@@ -280,6 +357,9 @@ pub async fn refresh_sign_ins(state: &AppState) {if let Ok(profiles) = state.db.list_profiles(&SpaceId::new(&space.id)).await {let keyed = super::profile_routes::keyed_ids(state, &profiles).await;state.profiles.statuses(&profiles, &keyed).await;+ for p in profiles.iter().filter(|p| p.kind == "custom_api" && p.enabled) {+ refresh_custom(state, p, false).await;+ }}}REFRESHING.store(false, Ordering::Release);@@ -512,6 +592,16 @@ mod tests {uses(readiness(&r, &profiles, &signed_in(&["p_personal"]), now())),(true, Some("Personal".into())));+ // Custom API is ready only through a checked account of the space, never the host+ let c = report(EngineId::CustomApi, true, EngineStatus::Ready);+ let mut maestro = profile("p_maestro", "Maestro", "custom_api", 10, true);+ maestro.engine = "custom".into();+ assert_eq!(readiness(&c, &[], &Availability::default(), now()), (false, None));+ assert_eq!(readiness(&c, std::slice::from_ref(&maestro), &Availability::default(), now()), (false, None));+ assert_eq!(+ uses(readiness(&c, std::slice::from_ref(&maestro), &signed_in(&["p_maestro"]), now())),+ (true, Some("Maestro".into()))+ );// Ollama has no accounts: ready from its own check alonelet o = report(EngineId::Ollama, true, EngineStatus::Ready);assert_eq!(readiness(&o, &profiles, &Availability::default(), now()), (true, None));diff --git a/src/server/routes.rs b/src/server/routes.rsindex f3ef9fd2..e5c2a786 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -1124,7 +1124,11 @@ async fn run_kwant_turn_inner(let host_off = super::profile_turn::host_off(state, &space).await;let available_models =crate::drivers::detect_available_models(&db, &state.engines, &profile_engines, &host_off).await;- if available_models.is_empty() {+ // A bot pinned to Custom API runs on its account even when that account's last check+ // failed, so the reply says what is wrong with it (no account, server down, key refused)+ let pinned_custom = crate::router::parse_pin(&target_kwant.preferred_model).family.as_deref()+ == Some(crate::profiles::Engine::Custom.as_str());+ if available_models.is_empty() && !pinned_custom {// Say why when it's this space's own switch, so nobody hunts for a broken enginelet text = if host_off.is_empty() {format!("⚠️ [{}] {}", target_kwant.name, crate::drivers::engines::NO_ENGINE_MESSAGE)@@ -1411,18 +1415,23 @@ async fn run_kwant_turn_inner(};// The model for the engine this attempt runs on: the pinned one, else the effort's tierlet runs_on = host_engine.or_else(|| profile.as_ref().and_then(super::profile_turn::profile_engine));- let choice = runs_on.and_then(|e| {- crate::drivers::engines::choose_model(- &crate::drivers::engines::known_models(&state.engines, e),- pinned_model.as_deref(),- tier,- )- });+ let custom = profile.as_ref().filter(|p| p.kind == "custom_api");+ let choice = match custom {+ Some(p) => super::profile_turn::custom_model(state, p, pinned_model.as_deref(), tier).await,+ None => runs_on.and_then(|e| {+ crate::drivers::engines::choose_model(+ &crate::drivers::engines::known_models(&state.engines, e),+ pinned_model.as_deref(),+ tier,+ )+ }),+ };// An API account whose models weren't listed here picks its own from the tier- let unlisted_api = runs_on.is_some_and(|e| {- e.kind() == crate::drivers::engines::EngineKind::Api- && state.engines.report(e).models.is_empty()- });+ let unlisted_api = custom.is_none()+ && runs_on.is_some_and(|e| {+ e.kind() == crate::drivers::engines::EngineKind::Api+ && state.engines.report(e).models.is_empty()+ });let mut input = turn_input.clone();input.model = if unlisted_api { None } else { choice.as_ref().and_then(|c| c.run_id()).map(str::to_string) };if let Some(e) = runs_on {diff --git a/tests/custom_api_migration_test.rs b/tests/custom_api_migration_test.rsnew file mode 100644index 00000000..1822df8c--- /dev/null+++ b/tests/custom_api_migration_test.rs@@ -0,0 +1,129 @@+//! Schema version 2 (Custom API accounts): the `llm_profiles` rebuild keeps every row, index and+//! rule, and a failed change leaves version 1 running without Custom API accounts.++use kwnt::db::custom_api::{ProfileEndpoint, CUSTOM_API_SCHEMA_VERSION};+use kwnt::db::spaces::SPACES_SCHEMA_VERSION;+use kwnt::db::Database;+use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions};+use std::path::Path;+use std::str::FromStr;++async fn raw(path: &Path) -> SqlitePool {+ let opts = SqliteConnectOptions::from_str(&format!("sqlite://{}", path.display()))+ .unwrap()+ .foreign_keys(true);+ SqlitePoolOptions::new().max_connections(1).connect_with(opts).await.unwrap()+}++async fn exec(pool: &SqlitePool, sql: &str) -> Result<(), sqlx::Error> {+ sqlx::query(sql).execute(pool).await.map(|_| ())+}++/// A database as the release before spaces leaves it, with accounts of every kind.+async fn legacy(dir: &Path) {+ Database::init_without_spaces(dir).await.unwrap();+ let pool = raw(&dir.join("kwnt.db")).await;+ for sql in [+ "UPDATE llm_profiles SET is_default = 0 WHERE id = 'prf_system_claude'",+ "INSERT INTO llm_profiles (id, engine, name, kind, home_dir, priority, enabled, is_default) VALUES+ ('prf_personal', 'claude', 'Personal', 'cli_home', '/h/personal', 1, 1, 1),+ ('prf_grok_key', 'grok', 'Key', 'api_key', NULL, 5, 0, 0)",+ "INSERT INTO llm_profile_secrets (profile_id, api_key) VALUES ('prf_grok_key', 'xai-secret')",+ "INSERT INTO llm_profile_state (profile_id, limited_until, last_error) VALUES ('prf_personal', '2030-01-01T00:00:00Z', 'quota')",+ ] {+ exec(&pool, sql).await.unwrap_or_else(|e| panic!("{sql}: {e}"));+ }+ pool.close().await;+}++async fn profiles(pool: &SqlitePool) -> Vec<(String, String, String, String, i64, bool, bool)> {+ sqlx::query_as(+ "SELECT id, engine, name, kind, priority, enabled, is_default FROM llm_profiles ORDER BY id",+ )+ .fetch_all(pool)+ .await+ .unwrap()+}++#[tokio::test]+async fn the_rebuild_keeps_every_account_and_rule_and_adds_custom() {+ let tmp = tempfile::tempdir().unwrap();+ legacy(tmp.path()).await;+ let before = profiles(&raw(&tmp.path().join("kwnt.db")).await).await;++ let db = Database::init(tmp.path()).await.unwrap();+ assert_eq!(db.schema_version().await.unwrap(), CUSTOM_API_SCHEMA_VERSION);+ assert!(db.custom_api_ready().await);+ let pool = raw(&tmp.path().join("kwnt.db")).await;+ assert_eq!(profiles(&pool).await, before, "every account kept as it was");+ let secret: (String,) = sqlx::query_as("SELECT api_key FROM llm_profile_secrets WHERE profile_id = 'prf_grok_key'")+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(secret.0, "xai-secret");+ let state: (String,) = sqlx::query_as("SELECT last_error FROM llm_profile_state WHERE profile_id = 'prf_personal'")+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(state.0, "quota");++ // The rules survive the rebuild: one default per engine and space, names unique per space+ // regardless of case, and only known engines and kinds+ assert!(exec(&pool, "INSERT INTO llm_profiles (id, engine, name, kind, is_default) VALUES ('p2', 'claude', 'Second', 'cli_home', 1)").await.is_err());+ assert!(exec(&pool, "INSERT INTO llm_profiles (id, engine, name, kind) VALUES ('p3', 'claude', 'PERSONAL', 'cli_home')").await.is_err());+ assert!(exec(&pool, "INSERT INTO llm_profiles (id, engine, name, kind) VALUES ('p4', 'bogus', 'X', 'api_key')").await.is_err());+ assert!(exec(&pool, "INSERT INTO llm_profiles (id, engine, name, kind) VALUES ('p5', 'custom', 'X', 'bogus')").await.is_err());+ exec(&pool, "INSERT INTO llm_profiles (id, engine, name, kind) VALUES ('p_custom', 'custom', 'Maestro', 'custom_api')").await.unwrap();+ // Same name on another engine is fine, as before+ exec(&pool, "INSERT INTO llm_profiles (id, engine, name, kind) VALUES ('p_custom2', 'custom', 'Personal', 'custom_api')").await.unwrap();+ pool.close().await;++ let endpoint = ProfileEndpoint {+ profile_id: "p_custom".into(),+ protocol: "openai-chat".into(),+ base_url: "http://localhost:23333/api/openai/v1".into(),+ model: Some("gpt-4.1".into()),+ };+ db.set_profile_endpoint(&endpoint).await.unwrap();+ assert_eq!(db.get_profile_endpoint("p_custom").await.unwrap(), Some(endpoint.clone()));+ // Upsert+ let changed = ProfileEndpoint { model: None, ..endpoint };+ db.set_profile_endpoint(&changed).await.unwrap();+ assert_eq!(db.get_profile_endpoint("p_custom").await.unwrap(), Some(changed));+ assert_eq!(db.list_profile_endpoints().await.unwrap().len(), 1);+ db.delete_profile("p_custom").await.unwrap();+ assert_eq!(db.get_profile_endpoint("p_custom").await.unwrap(), None);+ drop(db);++ // Runs once: a second start changes nothing+ let db = Database::init(tmp.path()).await.unwrap();+ assert_eq!(db.schema_version().await.unwrap(), CUSTOM_API_SCHEMA_VERSION);+ let pool = raw(&tmp.path().join("kwnt.db")).await;+ assert_eq!(profiles(&pool).await.len(), before.len() + 1);+}++#[tokio::test]+async fn a_failed_change_rolls_back_and_keeps_running_on_version_1() {+ let tmp = tempfile::tempdir().unwrap();+ legacy(tmp.path()).await;+ // A table in the way makes the change fail part-way, after the rebuild+ let pool = raw(&tmp.path().join("kwnt.db")).await;+ exec(&pool, "CREATE TABLE llm_profile_endpoints (x TEXT)").await.unwrap();+ pool.close().await;++ let db = Database::init(tmp.path()).await.expect("startup never fails on it");+ assert_eq!(db.schema_version().await.unwrap(), SPACES_SCHEMA_VERSION);+ assert!(!db.custom_api_ready().await);+ assert_eq!(db.get_profile_endpoint("x").await.unwrap(), None);+ let pool = raw(&tmp.path().join("kwnt.db")).await;+ // The rebuild was rolled back: the old rules, without custom+ assert!(exec(&pool, "INSERT INTO llm_profiles (id, engine, name, kind) VALUES ('p_c', 'custom', 'M', 'custom_api')").await.is_err());+ assert_eq!(profiles(&pool).await.len(), 5, "3 system + 2 accounts, all kept");++ // Out of the way: the next start finishes it+ exec(&pool, "DROP TABLE llm_profile_endpoints").await.unwrap();+ pool.close().await;+ drop(db);+ let db = Database::init(tmp.path()).await.unwrap();+ assert_eq!(db.schema_version().await.unwrap(), CUSTOM_API_SCHEMA_VERSION);+}diff --git a/tests/custom_api_test.rs b/tests/custom_api_test.rsnew file mode 100644index 00000000..d75d36fc--- /dev/null+++ b/tests/custom_api_test.rs@@ -0,0 +1,548 @@+//! Custom API accounts end to end, against a fake server that speaks both the OpenAI chat and the+//! Anthropic Messages APIs under Agent Maestro's paths (`/api/openai/v1`, `/api/anthropic/v1`):+//! the model list, a streamed turn in a space other than Default with "ran on <account>", a+//! rejected key and a server that isn't running.++use axum::{+ body::{to_bytes, Body},+ extract::State,+ http::{HeaderMap, Request, StatusCode},+ response::{IntoResponse, Response},+ routing::{get, post},+ Json, 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::sync::{Arc, Mutex};+use std::time::Duration;+use tower::ServiceExt;++const KEY: &str = "sk-custom-SECRET-0123456789";+const HOST_KEY: &str = "sk-host-key-must-not-reach-custom";++type Seen = Arc<Mutex<Vec<(String, HeaderMap, Value)>>>;++#[derive(Clone)]+struct Fake {+ seen: Seen,+ /// Whether `GET …/models` answers (Agent Maestro's OpenAI side may not list).+ lists: bool,+}++fn authorized(headers: &HeaderMap, anthropic: bool) -> bool {+ let got = if anthropic {+ headers.get("x-api-key").and_then(|v| v.to_str().ok()).map(str::to_string)+ } else {+ headers+ .get("authorization")+ .and_then(|v| v.to_str().ok())+ .and_then(|v| v.strip_prefix("Bearer "))+ .map(str::to_string)+ };+ got.as_deref() == Some(KEY)+}++fn denied() -> Response {+ (StatusCode::UNAUTHORIZED, Json(json!({"error": {"message": "invalid api key"}}))).into_response()+}++fn sse(events: Vec<String>) -> Response {+ let body: String = events.into_iter().map(|e| format!("{e}\n\n")).collect();+ ([("content-type", "text/event-stream")], body).into_response()+}++async fn models(fake: Fake, headers: HeaderMap, anthropic: bool) -> Response {+ if !fake.lists {+ return StatusCode::NOT_FOUND.into_response();+ }+ if !authorized(&headers, anthropic) {+ return denied();+ }+ if anthropic {+ Json(json!({"data": [{"id": "claude-sonnet-4", "display_name": "Claude Sonnet 4"}]})).into_response()+ } else {+ Json(json!({"object": "list", "data": [{"id": "gpt-4.1"}, {"id": "claude-sonnet-4"}]})).into_response()+ }+}++/// A fake model server. The reply names the model and the API it came through.+async fn fake_server(lists: bool) -> (String, Seen) {+ let seen: Seen = Arc::default();+ let fake = Fake { seen: seen.clone(), lists };+ let app = Router::new()+ .route(+ "/api/openai/v1/models",+ get(|State(f): State<Fake>, h: HeaderMap| async move { models(f, h, false).await }),+ )+ .route(+ "/api/anthropic/v1/models",+ get(|State(f): State<Fake>, h: HeaderMap| async move { models(f, h, true).await }),+ )+ .route(+ "/api/openai/v1/chat/completions",+ post(|State(f): State<Fake>, h: HeaderMap, Json(body): Json<Value>| async move {+ f.seen.lock().unwrap().push(("openai".into(), h.clone(), body.clone()));+ if !authorized(&h, false) {+ return denied();+ }+ let model = body["model"].as_str().unwrap_or("?").to_string();+ if body["stream"] != true {+ return Json(json!({"choices": [{"message": {"content": format!("unstreamed {model}")}}]}))+ .into_response();+ }+ let piece = |t: &str| format!("data: {}", json!({"choices": [{"delta": {"content": t}}]}));+ sse(vec![+ piece("Hello "),+ piece(&format!("from {model} ")),+ piece("over OpenAI"),+ format!("data: {}", json!({"choices": [], "usage": {"total_tokens": 9}})),+ "data: [DONE]".into(),+ ])+ }),+ )+ .route(+ "/api/anthropic/v1/messages",+ post(|State(f): State<Fake>, h: HeaderMap, Json(body): Json<Value>| async move {+ f.seen.lock().unwrap().push(("anthropic".into(), h.clone(), body.clone()));+ if !authorized(&h, true) {+ return denied();+ }+ let model = body["model"].as_str().unwrap_or("?").to_string();+ let delta = |t: &str| {+ format!(+ "event: content_block_delta\ndata: {}",+ json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": t}})+ )+ };+ sse(vec![+ format!("event: message_start\ndata: {}", json!({"type": "message_start", "message": {"usage": {"input_tokens": 5}}})),+ delta("Hello "),+ delta(&format!("from {model} ")),+ delta("over Anthropic"),+ format!("event: message_delta\ndata: {}", json!({"type": "message_delta", "usage": {"output_tokens": 6}})),+ format!("event: message_stop\ndata: {}", json!({"type": "message_stop"})),+ ])+ }),+ )+ .with_state(fake);+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let root = format!("http://{}", listener.local_addr().unwrap());+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ (root, seen)+}++/// A port nothing listens on.+async fn closed_port() -> u16 {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ listener.local_addr().unwrap().port()+}++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_else(|_| Value::String(String::from_utf8_lossy(&bytes).into())))+}++struct Env {+ app: Router,+ state: AppState,+ _tmp: tempfile::TempDir,+}++async fn setup() -> Env {+ // The host's own keys must never be used for a Custom API turn+ std::env::set_var("OPENAI_API_KEY", HOST_KEY);+ std::env::set_var("ANTHROPIC_API_KEY", HOST_KEY);+ let tmp = tempfile::tempdir().unwrap();+ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ // Laya is unreachable: routing falls back to the bot's pinned 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()),+ );+ Env { app: create_router(state.clone()), state, _tmp: tmp }+}++impl Env {+ async fn space(&self, name: &str) -> String {+ let (s, v) = call(+ &self.app,+ "POST",+ "/api/spaces",+ Some(json!({"name": name, "icon": "🧪", "this_machine_enabled": false})),+ )+ .await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+ v["id"].as_str().unwrap().to_string()+ }++ async fn account(&self, space: &str, body: Value) -> (StatusCode, Value) {+ call(&self.app, "POST", &format!("/api/profiles?space={space}"), Some(body)).await+ }++ async fn bot(&self, space: &str, name: &str, model: &str) -> String {+ let (s, v) = call(+ &self.app,+ "POST",+ &format!("/api/kwants?space={space}"),+ Some(json!({+ "name": name,+ "title": "Tester",+ "persona_prompt": "Test persona",+ "avatar_sprite": "s",+ "driver_type": "api",+ "preferred_model": model,+ })),+ )+ .await;+ assert!(s.is_success(), "{s} {v}");+ v["id"].as_str().unwrap().to_string()+ }++ /// Sends a prompt and collects the turn's events up to `turn_ended`.+ async fn turn(&self, kwant_id: &str) -> Vec<RuntimeEvent> {+ let mut rx = self.state.event_sender.subscribe();+ let (s, v) = call(+ &self.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.unscoped().clone());+ if end {+ break;+ }+ }+ })+ .await+ .expect("turn did not end");+ events+ }++ /// The bot's saved reply and its `meta.ran_on`.+ async fn reply(&self, kwant_id: &str) -> (String, Value) {+ let saved = self.state.db.list_messages(kwant_id, 10).await.unwrap();+ let m = saved.iter().rev().find(|m| m.sender_role == "kwant").expect("a saved reply");+ let meta: Value = m.meta.as_deref().map(|s| serde_json::from_str(s).unwrap()).unwrap_or(Value::Null);+ (m.text.clone(), meta["ran_on"].clone())+ }+}++fn streamed(events: &[RuntimeEvent]) -> (String, usize) {+ let deltas: Vec<&str> = events+ .iter()+ .filter_map(|e| match e {+ RuntimeEvent::TextDelta(t) => Some(t.as_str()),+ _ => None,+ })+ .collect();+ (deltas.concat(), deltas.len())+}++fn thinking(events: &[RuntimeEvent]) -> String {+ events+ .iter()+ .filter_map(|e| match e {+ RuntimeEvent::ThinkingDelta(t) => Some(t.as_str()),+ _ => None,+ })+ .collect::<Vec<_>>()+ .join("\n")+}++#[tokio::test]+async fn openai_compatible_account_lists_models_and_streams_a_turn_in_its_space() {+ let env = setup().await;+ let (root, seen) = fake_server(true).await;+ let space = env.space("Maestro space").await;++ let (s, acct) = env+ .account(+ &space,+ json!({+ "engine": "custom", "kind": "custom_api", "name": "Copilot via Maestro",+ "protocol": "openai-chat",+ // A pasted endpoint URL is cut back to the API root+ "base_url": format!("{root}/api/openai/v1/chat/completions"),+ "api_key": KEY, "model": "gpt-4.1",+ }),+ )+ .await;+ assert_eq!(s, StatusCode::CREATED, "{acct}");+ let text = acct.to_string();+ assert!(!text.contains(KEY), "the key never comes back: {text}");+ assert_eq!(acct["has_key"], true);+ assert_eq!(acct["signed_in"], true);+ let custom = &acct["custom"];+ assert_eq!(custom["base_url"], format!("{root}/api/openai/v1"));+ assert_eq!(custom["protocol"], "openai-chat");+ assert_eq!(custom["status"], "ready", "{custom}");+ assert_eq!(custom["detail"], "Connected · 2 models");+ assert_eq!(custom["supports_tools"], true);+ let ids: Vec<&str> = custom["models"].as_array().unwrap().iter().map(|m| m["id"].as_str().unwrap()).collect();+ assert_eq!(ids, ["gpt-4.1", "claude-sonnet-4"]);+ assert_eq!(custom["models"][0]["default"], true, "the account's own model is its default");++ // Scoped to its space: Default doesn't list it+ let (_, default_list) = call(&env.app, "GET", "/api/profiles", None).await;+ assert!(!default_list.to_string().contains("Copilot via Maestro"));++ let kid = env.bot(&space, "Quill", "custom").await;+ let events = env.turn(&kid).await;+ let (text, pieces) = streamed(&events);+ assert_eq!(text, "Hello from gpt-4.1 over OpenAI");+ assert!(pieces >= 3, "streamed piece by piece, not as one block: {pieces}");+ let notice = thinking(&events);+ assert!(notice.contains("Running on Custom API · Copilot via Maestro · gpt-4.1"), "{notice}");++ let (saved, ran_on) = env.reply(&kid).await;+ assert_eq!(saved, "Hello from gpt-4.1 over OpenAI");+ assert_eq!(ran_on["account"], "Copilot via Maestro", "{ran_on}");+ assert_eq!(ran_on["engine"], "custom_api");+ assert_eq!(ran_on["engine_name"], "Custom API");+ assert_eq!(ran_on["family"], "custom");+ assert_eq!(ran_on["model"], "gpt-4.1");+ assert_eq!(ran_on["profile_id"], acct["id"]);++ let seen = seen.lock().unwrap();+ let (api, headers, body) = seen.last().unwrap();+ assert_eq!(api, "openai");+ assert_eq!(headers["authorization"], format!("Bearer {KEY}"));+ assert_eq!(body["stream"], true);+ assert_eq!(body["model"], "gpt-4.1");+ assert!(seen.iter().all(|(_, h, _)| !format!("{h:?}").contains(HOST_KEY)), "the host's key leaked");+}++#[tokio::test]+async fn anthropic_compatible_account_streams_the_bots_pinned_model() {+ let env = setup().await;+ let (root, seen) = fake_server(true).await;+ let space = env.space("Claude via Maestro").await;++ // No model on the account: the bot pins one; the base gets its /v1+ let (s, acct) = env+ .account(+ &space,+ json!({+ "engine": "custom", "kind": "custom_api", "name": "Maestro Claude",+ "protocol": "anthropic-messages", "base_url": format!("{root}/api/anthropic"),+ "api_key": KEY,+ }),+ )+ .await;+ assert_eq!(s, StatusCode::CREATED, "{acct}");+ let custom = &acct["custom"];+ assert_eq!(custom["base_url"], format!("{root}/api/anthropic/v1"));+ assert_eq!(custom["status"], "ready", "{custom}");+ assert_eq!(custom["supports_tools"], false);+ assert_eq!(custom["models"][0]["label"], "Claude Sonnet 4");++ let kid = env.bot(&space, "Sage", "custom:claude-sonnet-4").await;+ let events = env.turn(&kid).await;+ let (text, pieces) = streamed(&events);+ assert_eq!(text, "Hello from claude-sonnet-4 over Anthropic");+ assert!(pieces >= 3, "{pieces}");+ let (saved, ran_on) = env.reply(&kid).await;+ assert_eq!(saved, text);+ assert_eq!(ran_on["account"], "Maestro Claude", "{ran_on}");+ assert_eq!(ran_on["model"], "claude-sonnet-4");++ let seen = seen.lock().unwrap();+ let (api, headers, body) = seen.last().unwrap();+ assert_eq!(api, "anthropic");+ assert_eq!(headers["x-api-key"], KEY);+ assert!(headers.contains_key("anthropic-version"));+ assert!(!headers.contains_key("authorization"));+ assert_eq!(body["stream"], true);+ assert_eq!(body["model"], "claude-sonnet-4");+}++#[tokio::test]+async fn a_rejected_key_is_shown_on_the_account_and_refuses_the_turn() {+ let env = setup().await;+ let (root, seen) = fake_server(true).await;+ let space = env.space("Bad key").await;+ let wrong = "sk-wrong-WRONGWRONG-987654";+ let (s, acct) = env+ .account(+ &space,+ json!({+ "engine": "custom", "kind": "custom_api", "name": "OpenRouter",+ "protocol": "openai-chat", "base_url": format!("{root}/api/openai/v1"),+ "api_key": wrong, "model": "gpt-4.1",+ }),+ )+ .await;+ assert_eq!(s, StatusCode::CREATED, "{acct}");+ assert_eq!(acct["custom"]["status"], "key_rejected", "{acct}");+ assert_eq!(acct["signed_in"], false);+ assert!(!acct.to_string().contains(wrong));++ let kid = env.bot(&space, "Rex", "custom").await;+ let events = env.turn(&kid).await;+ let (text, _) = streamed(&events);+ assert!(text.contains("OpenRouter"), "{text}");+ assert!(text.contains("key was rejected"), "{text}");+ assert!(!text.contains(wrong));+ // Never retried on the host's keys or CLIs+ assert!(seen.lock().unwrap().iter().all(|(_, h, _)| !format!("{h:?}").contains(HOST_KEY)));++ // Fixed key: checked again at once, and ready+ let id = acct["id"].as_str().unwrap();+ let (s, _) = call(&env.app, "PUT", &format!("/api/profiles/{id}/key?space={space}"), Some(json!({"api_key": KEY}))).await;+ assert_eq!(s, StatusCode::NO_CONTENT);+ let (s, v) = call(&env.app, "POST", &format!("/api/profiles/{id}/check?space={space}"), None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["custom"]["status"], "ready", "{v}");+ let events = env.turn(&kid).await;+ assert_eq!(streamed(&events).0, "Hello from gpt-4.1 over OpenAI");+}++#[tokio::test]+async fn a_server_that_is_not_running_says_so() {+ let env = setup().await;+ let port = closed_port().await;+ let space = env.space("Offline").await;+ let (s, acct) = env+ .account(+ &space,+ json!({+ "engine": "custom", "kind": "custom_api", "name": "LM Studio",+ "protocol": "openai-chat", "base_url": format!("http://127.0.0.1:{port}/v1"),+ "model": "qwen2.5-7b",+ }),+ )+ .await;+ assert_eq!(s, StatusCode::CREATED, "{acct}");+ let expected = format!("Nothing is answering at http://127.0.0.1:{port}/v1. Is Agent Maestro / the server running?");+ assert_eq!(acct["custom"]["status"], "unreachable", "{acct}");+ assert_eq!(acct["custom"]["detail"], expected.as_str());+ assert_eq!(acct["has_key"], false);++ let kid = env.bot(&space, "Lumen", "custom").await;+ let events = env.turn(&kid).await;+ let (text, _) = streamed(&events);+ assert!(text.contains(&expected), "{text}");+}++#[tokio::test]+async fn a_server_without_a_model_list_runs_the_model_entered_by_hand() {+ let env = setup().await;+ let (root, _) = fake_server(false).await;+ let space = env.space("No list").await;+ let base = json!({+ "engine": "custom", "kind": "custom_api", "name": "Plain",+ "protocol": "openai-chat", "base_url": format!("{root}/api/openai/v1"), "api_key": KEY,+ });+ let (_, acct) = env.account(&space, base.clone()).await;+ assert_eq!(acct["custom"]["status"], "error", "no list and no model: {acct}");+ let id = acct["id"].as_str().unwrap();+ let (s, acct) = call(&env.app, "PATCH", &format!("/api/profiles/{id}?space={space}"), Some(json!({"model": "gpt-4.1"}))).await;+ assert_eq!(s, StatusCode::OK, "{acct}");+ assert_eq!(acct["custom"]["status"], "ready", "{acct}");+ assert_eq!(acct["custom"]["model"], "gpt-4.1");+ let kid = env.bot(&space, "Plainly", "custom").await;+ assert_eq!(streamed(&env.turn(&kid).await).0, "Hello from gpt-4.1 over OpenAI");+}++#[tokio::test]+async fn a_space_without_a_custom_account_never_falls_back_to_the_host() {+ let env = setup().await;+ let space = env.space("Empty").await;+ let kid = env.bot(&space, "Nemo", "custom").await;+ let events = env.turn(&kid).await;+ let (text, _) = streamed(&events);+ assert!(text.contains("No Custom API account is on in this space"), "{text}");+}++#[tokio::test]+async fn bad_account_bodies_are_refused() {+ let env = setup().await;+ let space = env.space("Validation").await;+ let ok = json!({"engine": "custom", "kind": "custom_api", "name": "X", "protocol": "openai-chat", "base_url": "http://127.0.0.1:1/v1"});+ let with = |k: &str, v: Value| {+ let mut b = ok.clone();+ b[k] = v;+ b+ };+ for (body, why) in [+ (with("kind", json!("api_key")), "custom engine with another kind"),+ (json!({"engine": "claude", "kind": "custom_api", "name": "Y"}), "custom kind on another engine"),+ (with("protocol", json!("grpc")), "unknown protocol"),+ (with("base_url", json!("ftp://example.com/v1")), "not http"),+ (with("base_url", json!("http://user:[email protected]/v1")), "credentials in the URL"),+ (with("base_url", json!("http://example.com/v1?key=abc")), "query in the URL"),+ (with("model", json!("has space")), "model with whitespace"),+ (with("api_key", json!("short")), "too-short key"),+ (json!({"engine": "openai", "kind": "api_key", "name": "Z"}), "unknown engine"),+ (json!({"engine": "claude", "kind": "api_key", "name": "Z", "base_url": "http://x/v1"}), "server fields on a key account"),+ ] {+ let (s, v) = env.account(&space, body).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{why}: {v}");+ }+ let mut no_proto = ok.clone();+ no_proto.as_object_mut().unwrap().remove("protocol");+ assert_eq!(env.account(&space, no_proto).await.0, StatusCode::BAD_REQUEST);+ // Server fields can't be patched onto another kind of account+ let (_, list) = call(&env.app, "GET", &format!("/api/profiles?space={space}"), None).await;+ let system = list.as_array().unwrap().iter().find(|p| p["kind"] == "system").unwrap()["id"].as_str().unwrap().to_string();+ let (s, _) = call(&env.app, "PATCH", &format!("/api/profiles/{system}?space={space}"), Some(json!({"base_url": "http://x/v1"}))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+ let (s, _) = call(&env.app, "POST", &format!("/api/profiles/{system}/check?space={space}"), None).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+}++#[tokio::test]+async fn deleting_an_account_removes_its_server_and_key() {+ let env = setup().await;+ let space = env.space("Delete").await;+ let (_, acct) = env+ .account(+ &space,+ json!({"engine": "custom", "kind": "custom_api", "name": "Gone", "protocol": "openai-chat",+ "base_url": "http://127.0.0.1:1/v1", "api_key": KEY, "model": "m"}),+ )+ .await;+ let id = acct["id"].as_str().unwrap().to_string();+ assert!(env.state.db.get_profile_endpoint(&id).await.unwrap().is_some());+ let (s, _) = call(&env.app, "DELETE", &format!("/api/profiles/{id}?space={space}"), None).await;+ assert_eq!(s, StatusCode::NO_CONTENT);+ assert!(env.state.db.get_profile_endpoint(&id).await.unwrap().is_none());+ assert!(env.state.db.get_profile_key(&id).await.unwrap().is_none());+}diff --git a/tests/engine_model_test.rs b/tests/engine_model_test.rsindex f3d64d8f..75835366 100644--- a/tests/engine_model_test.rs+++ b/tests/engine_model_test.rs@@ -201,7 +201,7 @@ async fn laya_picks_model_tier_pins_and_engine_switches() {assert_eq!(s, StatusCode::NOT_FOUND);let (s, v) = call(&app, "POST", "/api/engines/codex", Some(json!({"enabled": false}))).await;assert_eq!(s, StatusCode::OK, "{v}");- assert_eq!(v["engines"].as_array().unwrap().len(), 7, "the full GET /api/engines shape");+ assert_eq!(v["engines"].as_array().unwrap().len(), 8, "the full GET /api/engines shape");let codex = by_id(&v, "codex");assert_eq!((codex["status"].clone(), codex["enabled"].clone(), codex["models"].clone()), (json!("disabled"), json!(false), json!([])));assert_eq!((codex["ready"].clone(), codex["uses"].clone()), (json!(false), Value::Null));diff --git a/tests/engine_routing_test.rs b/tests/engine_routing_test.rsindex 63e3f41a..0c403bd4 100644--- a/tests/engine_routing_test.rs+++ b/tests/engine_routing_test.rs@@ -125,7 +125,7 @@ async fn turns_skip_engines_that_cannot_run() {let (s, v) = call(&app, "GET", "/api/engines", None).await;assert_eq!(s, StatusCode::OK);let engines = v["engines"].as_array().unwrap();- assert_eq!(engines.len(), 7);+ assert_eq!(engines.len(), 8, "7 engines + Custom API");assert!(engines.iter().all(|e| e["status"] == "checking" && e["checked_at"].is_null()));// 1. Re-check: only the fake claude is ready; the shape is the agreed contract@@ -146,6 +146,10 @@ async fn turns_skip_engines_that_cannot_run() {assert!(e["detail"].is_string());assert_eq!(e["models"], json!([]));}+ // Custom API has no CLI: it runs on the space's accounts and says where to add one+ let custom = by_id(&v, "custom_api");+ assert_eq!((custom["name"].clone(), custom["kind"].clone(), custom["status"].clone()), (json!("Custom API"), json!("api"), json!("not_installed")));+ assert!(custom["detail"].as_str().unwrap().contains("Custom API accounts"), "{custom}");let (_, listed) = call(&app, "GET", "/api/engines", None).await;assert_eq!(listed, v);// The old Settings fields staydiff --git a/tests/router_test.rs b/tests/router_test.rsindex 4fbb8291..f0729197 100644--- a/tests/router_test.rs+++ b/tests/router_test.rs@@ -211,6 +211,24 @@ fn preferred_model_pin_forms() {assert_eq!(parse_pin("ollama:llama3.2:latest"), pin(Some("local_ollama"), Some("llama3.2:latest")));// Old model-id pins keep workingassert_eq!(parse_pin("claude-opus-5-5"), pin(Some("claude"), Some("claude-opus-5-5")));+ // Custom API: the model id stays whole, even an OpenRouter one with its own slash+ assert_eq!(parse_pin("custom"), pin(Some("custom"), None));+ assert_eq!(parse_pin("custom:gpt-4.1"), pin(Some("custom"), Some("gpt-4.1")));+ assert_eq!(parse_pin("custom:openai/gpt-4o"), pin(Some("custom"), Some("openai/gpt-4o")));+ assert_eq!(parse_pin("custom/claude-sonnet-4"), pin(Some("custom"), Some("claude-sonnet-4")));+ // A Claude model on a Custom API account is still Custom API, never the Claude engine+ assert_eq!(+ kwnt::profiles::Engine::from_model("custom:claude-sonnet-4"),+ Some(kwnt::profiles::Engine::Custom)+ );+}++#[test]+fn custom_api_never_runs_on_the_hosts_keys_or_clis() {+ use kwnt::drivers::engines::{system_route, EngineRegistry, NO_CUSTOM_ACCOUNT};+ let engines = EngineRegistry::default();+ let route = system_route(&engines, "custom", Some("sk-host-setting-key".into()), |_| Some("/usr/bin/claude".into()));+ assert_eq!(route, Err(NO_CUSTOM_ACCOUNT.to_string()));}#[test]diff --git a/tests/spaces_migration_test.rs b/tests/spaces_migration_test.rsindex 71d2dc82..ef10eae5 100644--- a/tests/spaces_migration_test.rs+++ b/tests/spaces_migration_test.rs@@ -1,7 +1,8 @@//! Spaces S0: the migration keeps every row, backs up first, runs once and leaves the old schema//! when it can't finish.-use kwnt::db::spaces::{DEFAULT_SPACE_ID, SPACES_SCHEMA_VERSION};+use kwnt::db::custom_api::CUSTOM_API_SCHEMA_VERSION;+use kwnt::db::spaces::DEFAULT_SPACE_ID;use kwnt::db::Database;use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions};use std::collections::BTreeMap;@@ -61,10 +62,11 @@ async fn legacy(dir: &Path) -> SqlitePool {pool}-/// Every row of every table except `spaces`, without `space_id`, as quoted text.+/// Every row of every table except `spaces` and `llm_profile_endpoints` (both new, the second+/// from the Custom API change), without `space_id`, as quoted text.async fn snapshot(pool: &SqlitePool) -> BTreeMap<String, Vec<String>> {let tables: Vec<(String,)> = sqlx::query_as(- "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name != 'spaces' ORDER BY name",+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT IN ('spaces', 'llm_profile_endpoints') ORDER BY name",).fetch_all(pool).await@@ -112,7 +114,7 @@ async fn migration_keeps_every_row_and_id_and_backs_up_first() {assert_eq!(scalar_i64(&pool, "PRAGMA user_version").await, 0);let db = Database::init(tmp.path()).await.unwrap();- assert_eq!(db.schema_version().await.unwrap(), SPACES_SCHEMA_VERSION);+ assert_eq!(db.schema_version().await.unwrap(), CUSTOM_API_SCHEMA_VERSION);let after = snapshot(&pool).await;assert_eq!(before, after, "every row and id survives, nothing added or lost");@@ -186,7 +188,7 @@ async fn migration_runs_once() {for _ in 0..2 {let db = Database::init(tmp.path()).await.unwrap();- assert_eq!(db.schema_version().await.unwrap(), SPACES_SCHEMA_VERSION);+ assert_eq!(db.schema_version().await.unwrap(), CUSTOM_API_SCHEMA_VERSION);}assert_eq!(snapshot(&pool).await, first);let again: Vec<(String,)> = sqlx::query_as("SELECT sql FROM sqlite_master WHERE sql IS NOT NULL ORDER BY name").fetch_all(&pool).await.unwrap();@@ -223,7 +225,7 @@ async fn backup_failure_refuses_startup_leaves_the_old_schema_and_retries_next_sstd::fs::remove_file(tmp.path().join("backups")).unwrap();let db = Database::init(tmp.path()).await.unwrap();- assert_eq!(db.schema_version().await.unwrap(), SPACES_SCHEMA_VERSION);+ assert_eq!(db.schema_version().await.unwrap(), CUSTOM_API_SCHEMA_VERSION);assert_eq!(backups(tmp.path()).len(), 1);}@@ -289,7 +291,7 @@ async fn foreign_key_problems_already_in_the_data_do_not_block_it() {assert_eq!(count(pool.clone()).await, 2);let db = Database::init(tmp.path()).await.unwrap();- assert_eq!(db.schema_version().await.unwrap(), SPACES_SCHEMA_VERSION);+ assert_eq!(db.schema_version().await.unwrap(), CUSTOM_API_SCHEMA_VERSION);assert_eq!(count(pool.clone()).await, 2, "the same two, none new");}@@ -325,7 +327,7 @@ async fn names_are_unique_per_space() {async fn fresh_database_starts_with_spaces_and_no_backup() {let tmp = tempfile::tempdir().unwrap();let db = Database::init(tmp.path()).await.unwrap();- assert_eq!(db.schema_version().await.unwrap(), SPACES_SCHEMA_VERSION);+ assert_eq!(db.schema_version().await.unwrap(), CUSTOM_API_SCHEMA_VERSION);assert!(backups(tmp.path()).is_empty());let pool = raw(&tmp.path().join("kwnt.db")).await;