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
Requests to OpenRouter name kwant as the app (24d) (#750)
Oleksandr Ivanchenko660d0ee0a23f
diff --git a/docs/llm-profiles.md b/docs/llm-profiles.mdindex 5286a54d..264f9213 100644--- a/docs/llm-profiles.md+++ b/docs/llm-profiles.md@@ -37,7 +37,8 @@ didn't say). Overloads and rate limits are retried, not failed over.chat API (`openai-chat`: OpenRouter, NVIDIA's `https://integrate.api.nvidia.com/v1`, LM Studio, AgentMaestro's `/api/openai/v1`, …) or theAnthropic 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+several; they belong to that space only. Requests to OpenRouter name kwant as the app+(https://kwant.si), so they count on OpenRouter's app page. Nothing about you or your space is sent. 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), andmay not carry a user, password, query or fragment, so a key never sits in it. The account ischecked with `GET {base}/models` when it is created or changed, on `POST …/check`, and againdiff --git a/site-src/docs-models.html b/site-src/docs-models.htmlindex 036434b4..b40b30e6 100644--- a/site-src/docs-models.html+++ b/site-src/docs-models.html@@ -14,7 +14,7 @@ card_art: avatar:research<li><strong>Host CLIs:</strong> <code>claude</code>, <code>codex</code> and <code>grok</code>, supervised by kwant, with their own file and shell tools.</li><li><strong>Provider APIs:</strong> Anthropic, OpenAI and xAI keys.</li><li><strong>Ollama:</strong> models you've pulled into a local <a href="#ollama">Ollama</a> server, with no account or key.</li>- <li><strong>Custom API:</strong> any server that speaks the OpenAI chat API (OpenRouter, LM Studio and others; the NVIDIA preset fills in build.nvidia.com, whose models are free with an NVIDIA API key) or the Anthropic Messages API.</li>+ <li><strong>Custom API:</strong> any server that speaks the OpenAI chat API (OpenRouter, LM Studio and others; the NVIDIA preset fills in build.nvidia.com, whose models are free with an NVIDIA API key) or the Anthropic Messages API. Requests to OpenRouter name kwant as the app (https://kwant.si), so they count on OpenRouter's app page. Nothing about you or your space is sent.</li></ul><p>Each bot has a preferred model. Set it to <strong>auto</strong> and kwant picks the model and effort for every message.</p>diff --git a/site/docs/models.html b/site/docs/models.htmlindex a7bf717a..ad475cd6 100644--- a/site/docs/models.html+++ b/site/docs/models.html@@ -20,7 +20,7 @@<meta property="og:image:height" content="630"><meta property="og:image:alt" content="Models & routing: The engines kwant runs on, and the router that picks the bot and the model."><meta property="article:published_time" content="2026-10-22">-<meta property="article:modified_time" content="2026-11-07">+<meta property="article:modified_time" content="2026-11-16"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:site" content="@kwantbot"><meta name="twitter:title" content="Models & routing: Claude, Codex, Grok, Ollama · kwant">@@ -75,7 +75,7 @@<li><strong>Host CLIs:</strong> <code>claude</code>, <code>codex</code> and <code>grok</code>, supervised by kwant, with their own file and shell tools.</li><li><strong>Provider APIs:</strong> Anthropic, OpenAI and xAI keys.</li><li><strong>Ollama:</strong> models you've pulled into a local <a href="#ollama">Ollama</a> server, with no account or key.</li>- <li><strong>Custom API:</strong> any server that speaks the OpenAI chat API (OpenRouter, LM Studio and others; the NVIDIA preset fills in build.nvidia.com, whose models are free with an NVIDIA API key) or the Anthropic Messages API.</li>+ <li><strong>Custom API:</strong> any server that speaks the OpenAI chat API (OpenRouter, LM Studio and others; the NVIDIA preset fills in build.nvidia.com, whose models are free with an NVIDIA API key) or the Anthropic Messages API. Requests to OpenRouter name kwant as the app (https://kwant.si), so they count on OpenRouter's app page. Nothing about you or your space is sent.</li></ul><p>Each bot has a preferred model. Set it to <strong>auto</strong> and kwant picks the model and effort for every message.</p>@@ -160,7 +160,7 @@</footer><script src="../assets/js/site.js?v=02a491b838" defer></script><script src="../assets/js/pixel.js?v=0a1a3bf1e2" defer></script>-<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/models#article","headline":"Models & routing: Claude, Codex, Grok, Ollama","description":"Run bots on the Claude, Codex or Grok CLIs, API keys, local Ollama or any OpenAI-compatible server. The Laya router picks who answers, and which model.","url":"https://kwant.si/docs/models","mainEntityOfPage":"https://kwant.si/docs/models","image":"https://kwant.si/assets/og/docs-models.png?v=f251eb8e2d","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-11-07","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Models & routing","item":"https://kwant.si/docs/models"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>+<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/models#article","headline":"Models & routing: Claude, Codex, Grok, Ollama","description":"Run bots on the Claude, Codex or Grok CLIs, API keys, local Ollama or any OpenAI-compatible server. The Laya router picks who answers, and which model.","url":"https://kwant.si/docs/models","mainEntityOfPage":"https://kwant.si/docs/models","image":"https://kwant.si/assets/og/docs-models.png?v=f251eb8e2d","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-11-16","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Models & routing","item":"https://kwant.si/docs/models"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script><script type="application/json" id="cf-beacon">{"token": "7f6ed395033a43eea3885ad0943890c2"}</script></body></html>diff --git a/site/sitemap.xml b/site/sitemap.xmlindex ffdcb114..e40592f4 100644--- a/site/sitemap.xml+++ b/site/sitemap.xml@@ -19,7 +19,7 @@<url><loc>https://kwant.si/docs/mcp</loc><lastmod>2026-11-13</lastmod></url><url><loc>https://kwant.si/docs/memory-skills</loc><lastmod>2026-11-14</lastmod></url><url><loc>https://kwant.si/docs/mission-board</loc><lastmod>2026-11-13</lastmod></url>- <url><loc>https://kwant.si/docs/models</loc><lastmod>2026-11-07</lastmod></url>+ <url><loc>https://kwant.si/docs/models</loc><lastmod>2026-11-16</lastmod></url><url><loc>https://kwant.si/docs/parallel-universe</loc><lastmod>2026-10-29</lastmod></url><url><loc>https://kwant.si/docs/phone</loc><lastmod>2026-11-15</lastmod></url><url><loc>https://kwant.si/docs/quickstart</loc><lastmod>2026-11-15</lastmod></url>diff --git a/src/drivers/api.rs b/src/drivers/api.rsindex dc93d6db..6ac55710 100644--- a/src/drivers/api.rs+++ b/src/drivers/api.rs@@ -67,17 +67,10 @@ async fn api_model_name(/// The provider's chat models, from `GET /v1/models` beside the chat endpoint `url`.async fn list_api_models(engine: super::engines::EngineId, url: &str, key: &str) -> Vec<super::engines::EngineModel> {- let base = url.split("/v1/").next().unwrap_or(url);let Ok(client) = Client::builder().timeout(Duration::from_secs(10)).build() else {return Vec::new();};- let req = client.get(format!("{base}/v1/models"));- let req = if is_anthropic(url) {- req.header("x-api-key", key).header("anthropic-version", ANTHROPIC_VERSION)- } else {- req.bearer_auth(key)- };- match req.send().await {+ match models_request(&client, url, key).send().await {Ok(r) if r.status().is_success() => match r.json::<Value>().await {Ok(body) => super::engines::parse_api_models(engine, &body),Err(_) => Vec::new(),@@ -86,6 +79,44 @@ async fn list_api_models(engine: super::engines::EngineId, url: &str, key: &str)}}+/// `list_api_models`' `GET /v1/models` beside the chat endpoint `url`, built but not sent.+fn models_request(client: &Client, url: &str, key: &str) -> reqwest::RequestBuilder {+ let base = url.split("/v1/").next().unwrap_or(url);+ let models = format!("{base}/v1/models");+ let req = client.get(&models);+ let req = if is_anthropic(url) {+ req.header("x-api-key", key).header("anthropic-version", ANTHROPIC_VERSION)+ } else {+ req.bearer_auth(key)+ };+ with_attribution(req, &models)+}++/// The site kwant names itself by in OpenRouter's app attribution (`HTTP-Referer`).+const KWANT_SITE: &str = "https://kwant.si";+/// The app title kwant names itself by in OpenRouter's app attribution (`X-OpenRouter-Title`).+const KWANT_APP_TITLE: &str = "kwant";++/// Whether `url` goes to OpenRouter: its parsed host is `openrouter.ai` or a subdomain of it.+/// Matched on the host only, so `openrouter.ai.example.com` or a path naming it never count.+fn is_openrouter(url: &str) -> bool {+ reqwest::Url::parse(url)+ .ok()+ .and_then(|u| u.host_str().map(|h| h.trim_end_matches('.').to_ascii_lowercase()))+ .is_some_and(|h| h == "openrouter.ai" || h.ends_with(".openrouter.ai"))+}++/// Adds OpenRouter's app-attribution headers when `url` goes to OpenRouter, so kwant's usage+/// counts on its apps page and rankings. They name the app only, never the person, space or bot.+/// Requests to any other server are returned unchanged.+pub(crate) fn with_attribution(req: reqwest::RequestBuilder, url: &str) -> reqwest::RequestBuilder {+ if is_openrouter(url) {+ req.header("HTTP-Referer", KWANT_SITE).header("X-OpenRouter-Title", KWANT_APP_TITLE)+ } else {+ req+ }+}+/// Anthropic Messages API version sent with every request.pub const ANTHROPIC_VERSION: &str = "2023-06-01";/// What the bare "claude" routing id runs on the Anthropic API.@@ -1059,21 +1090,24 @@ impl ApiDriver {}impl ApiDriver {- /// 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)- .json(body)- .timeout(Duration::from_secs(300));- if let Some(key) = request.api_key {- req = if is_anthropic(request.url) {+ /// One model call's request to `url`, built but not sent: the key, and OpenRouter's app+ /// attribution when `url` goes there (see [`with_attribution`]).+ fn chat_request(&self, url: &str, api_key: Option<&str>, body: &Value) -> reqwest::RequestBuilder {+ let mut req = self.client.post(url).json(body).timeout(Duration::from_secs(300));+ if let Some(key) = api_key {+ req = if is_anthropic(url) {req.header("x-api-key", key).header("anthropic-version", ANTHROPIC_VERSION)} else {req.header("Authorization", format!("Bearer {}", key))};}+ with_attribution(req, url)+ }++ /// 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 req = self.chat_request(request.url, request.api_key, body);let resp = req.send().await.map_err(|e| ApiError {status: None,message: match (&self.custom_base, e.is_timeout()) {@@ -1632,6 +1666,92 @@ impl Driver for ApiDriver {}}+#[cfg(test)]+mod attribution_tests {+ use super::*;++ const OPENROUTER_CHAT: &str = "https://openrouter.ai/api/v1/chat/completions";++ /// The request `send_chat` would send to `url` with key `sk-test`, built with no network.+ fn chat(url: &str) -> reqwest::Request {+ ApiDriver::for_custom(Some("sk-test".into()), url.into(), url.into())+ .chat_request(url, Some("sk-test"), &json!({"model": "m", "messages": []}))+ .build()+ .unwrap()+ }++ fn header<'a>(req: &'a reqwest::Request, name: &str) -> Option<&'a str> {+ req.headers().get(name).map(|v| v.to_str().unwrap())+ }++ fn assert_attributed(req: &reqwest::Request) {+ assert_eq!(header(req, "HTTP-Referer"), Some("https://kwant.si"), "{}", req.url());+ assert_eq!(header(req, "X-OpenRouter-Title"), Some("kwant"), "{}", req.url());+ assert_eq!(header(req, "X-Title"), None, "only the current title header is sent");+ }++ fn assert_not_attributed(req: &reqwest::Request) {+ for name in ["HTTP-Referer", "Referer", "X-OpenRouter-Title", "X-Title"] {+ assert_eq!(header(req, name), None, "{name} on {}", req.url());+ }+ }++ #[test]+ fn openrouter_chat_requests_name_kwant_with_the_key_unchanged() {+ let req = chat(OPENROUTER_CHAT);+ assert_attributed(&req);+ assert_eq!(header(&req, "Authorization"), Some("Bearer sk-test"));+ assert_eq!(req.url().as_str(), OPENROUTER_CHAT);+ // Same for any openrouter.ai subdomain and any letter case+ assert_attributed(&chat("https://eu.OpenRouter.ai/api/v1/chat/completions"));+ }++ #[test]+ fn openrouter_model_list_requests_name_kwant() {+ let client = Client::new();+ let req = models_request(&client, OPENROUTER_CHAT, "sk-test").build().unwrap();+ assert_eq!(req.url().as_str(), "https://openrouter.ai/api/v1/models");+ assert_attributed(&req);+ assert_eq!(header(&req, "Authorization"), Some("Bearer sk-test"));+ }++ #[test]+ fn no_other_server_gets_attribution_headers() {+ let others = [+ "https://api.openai.com/v1/chat/completions",+ "https://api.anthropic.com/v1/messages",+ "https://api.x.ai/v1/chat/completions",+ "http://localhost:1234/v1/chat/completions",+ "http://127.0.0.1:23333/api/openai/v1/chat/completions",+ "https://openrouter.ai.example.com/v1/chat/completions",+ "https://example.com/openrouter.ai/v1/chat/completions",+ "https://example.com/v1/chat/completions?u=openrouter.ai",+ "https://notopenrouter.ai/v1",+ "https://notopenrouter.ai/v1/chat/completions",+ ];+ let client = Client::new();+ for url in others {+ let req = chat(url);+ assert_not_attributed(&req);+ assert!(header(&req, if is_anthropic(url) { "x-api-key" } else { "Authorization" }).is_some());+ assert_not_attributed(&models_request(&client, url, "sk-test").build().unwrap());+ }+ }++ #[test]+ fn openrouter_is_matched_on_the_parsed_host() {+ assert!(is_openrouter("https://openrouter.ai/api/v1"));+ assert!(is_openrouter("https://openrouter.ai./api/v1"));+ assert!(is_openrouter("https://api.openrouter.ai/v1"));+ assert!(!is_openrouter("https://openrouter.ai.example.com/v1"));+ assert!(!is_openrouter("https://notopenrouter.ai/v1"));+ assert!(!is_openrouter("https://example.com/openrouter.ai"));+ assert!(!is_openrouter("https://[email protected]/v1"));+ assert!(!is_openrouter("openrouter.ai/api/v1"));+ assert!(!is_openrouter(""));+ }+}+#[cfg(test)]mod tests {use super::*;diff --git a/src/drivers/custom.rs b/src/drivers/custom.rsindex c0114f70..adfd7199 100644--- a/src/drivers/custom.rs+++ b/src/drivers/custom.rs@@ -196,6 +196,28 @@ pub fn parse_models(body: &serde_json::Value, model: Option<&str>) -> Option<VecSome(models)}+/// The check's `GET` of the server's models, built but not sent: the key, and OpenRouter's app+/// attribution when the server is OpenRouter (see [`super::api::with_attribution`]).+fn check_request(+ client: &reqwest::Client,+ protocol: Protocol,+ base: &str,+ key: Option<&str>,+) -> reqwest::RequestBuilder {+ let url = models_url(base);+ let mut req = client.get(&url);+ 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),+ };+ }+ super::api::with_attribution(req, &url)+}+/// 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 {@@ -206,17 +228,7 @@ pub async fn check(protocol: Protocol, base: &str, key: Option<&str>, model: Optelse {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 {+ let resp = match check_request(&client, protocol, base, key).send().await {Ok(r) => r,Err(e) if e.is_timeout() => {return CustomCheck::new(@@ -291,6 +303,37 @@ pub async fn check(protocol: Protocol, base: &str, key: Option<&str>, model: Optmod tests {use super::*;+ #[test]+ fn the_check_names_kwant_only_to_openrouter() {+ let client = reqwest::Client::new();+ let get = |protocol, base: &str| {+ check_request(&client, protocol, base, Some("sk-test")).build().unwrap()+ };+ let header = |req: &reqwest::Request, name: &str| {+ req.headers().get(name).map(|v| v.to_str().unwrap().to_string())+ };++ let req = get(Protocol::OpenaiChat, "https://openrouter.ai/api/v1");+ assert_eq!(req.url().as_str(), "https://openrouter.ai/api/v1/models");+ assert_eq!(header(&req, "HTTP-Referer").as_deref(), Some("https://kwant.si"));+ assert_eq!(header(&req, "X-OpenRouter-Title").as_deref(), Some("kwant"));+ assert_eq!(header(&req, "Authorization").as_deref(), Some("Bearer sk-test"));++ for (protocol, base) in [+ (Protocol::OpenaiChat, "https://api.openai.com/v1"),+ (Protocol::AnthropicMessages, "https://api.anthropic.com/v1"),+ (Protocol::OpenaiChat, "http://localhost:1234/v1"),+ (Protocol::OpenaiChat, "https://openrouter.ai.example.com/v1"),+ (Protocol::OpenaiChat, "https://example.com/openrouter.ai/v1"),+ (Protocol::OpenaiChat, "https://notopenrouter.ai/v1"),+ ] {+ let req = get(protocol, base);+ for name in ["HTTP-Referer", "X-OpenRouter-Title", "X-Title"] {+ assert_eq!(header(&req, name), None, "{name} on {base}");+ }+ }+ }+#[test]fn base_urls_normalize_to_the_api_root() {let oa = Protocol::OpenaiChat;