Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
use futures_util::StreamExt;
use http_body_util::combinators::BoxBody;
use http_body_util::{BodyExt, Empty, Full, StreamBody};
use hyper::body::Bytes;
use hyper::body::{Frame, Incoming};
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use jan_utils::{
is_cors_header, is_same_or_app_origin, is_trusted_origin, is_valid_host, remove_prefix,
};
use reqwest::Client;
use serde_json;
use std::collections::HashMap;
use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::Arc;
use tauri_plugin_llamacpp::state::LlamacppState;
use tokio::sync::Mutex;
use crate::core::server::converters::{converter_for, SseAccumulator, StreamState, UpstreamConverter};
use crate::core::{
mcp::models::McpSettings,
state::{ProviderConfig, ServerHandle, SharedMcpServers},
};
// Orchestration + upstream plumbing moved to `core/agent`. Re-exported so the
// in-file inline-orchestration call sites and the `proxy::` test references
// keep resolving unchanged.
pub(crate) use crate::core::agent::r#loop::run_server_side_openai_orchestration;
pub(crate) use crate::core::agent::upstream::{
call_openai_chat_completions, collect_mcp_openai_tools, copy_optional_chat_params,
drop_orphaned_tool_results, execute_mcp_tool_calls, extract_choice_message, extract_tool_calls,
load_assistant_config, parse_openai_messages, repair_dangling_tool_calls,
replace_system_prompt, resolve_upstream_for_model,
};
use crate::core::openai_schema::{
http_status_indicates_api_key_retry, normalize_openai_tools_in_chat_body,
};
type ResBody = BoxBody<Bytes, Infallible>;
fn full<B: Into<Bytes>>(chunk: B) -> ResBody {
Full::new(chunk.into()).boxed()
}
fn empty() -> ResBody {
Empty::<Bytes>::new().boxed()
}
/// hyper 1.0 dropped `Body::channel`; this mpsc-backed `StreamBody` restores a
/// sender handle for the streaming/passthrough paths. `send_data` returns
/// `Result<(), ()>` so existing `.is_err()` disconnect checks compile unchanged.
struct BodySender(tokio::sync::mpsc::Sender<Result<Frame<Bytes>, Infallible>>);
impl BodySender {
async fn send_data(&mut self, data: Bytes) -> Result<(), ()> {
self.0.send(Ok(Frame::data(data))).await.map_err(|_| ())
}
}
fn body_channel() -> (BodySender, ResBody) {
let (tx, rx) = tokio::sync::mpsc::channel::<Result<Frame<Bytes>, Infallible>>(32);
let body = BodyExt::boxed(StreamBody::new(
tokio_stream::wrappers::ReceiverStream::new(rx),
));
(BodySender(tx), body)
}
/// Keeps `lease` alive until `body` has been read to its end or dropped, which
/// is when the client has everything it asked the engine for or has gone away.
fn hold_lease(body: ResBody, lease: tauri_plugin_llamacpp::state::EngineLease) -> ResBody {
BodyExt::boxed(lease.guard(body))
}
/// Transform Anthropic /messages API body to OpenAI /chat/completions body
pub(crate) fn transform_anthropic_to_openai(body: &serde_json::Value) -> Option<serde_json::Value> {
let model = body.get("model")?.as_str()?;
let messages = body.get("messages")?;
let openai_messages = convert_messages(messages, body.get("system"))?;
let stream = body
.get("stream")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let mut result = serde_json::json!({
"model": model,
"messages": openai_messages,
"stream": stream
});
// Transform Anthropic tools to OpenAI format
if let Some(tools) = body.get("tools").and_then(|t| t.as_array()) {
let openai_tools: Vec<serde_json::Value> = tools
.iter()
.filter_map(|tool| {
let name = tool.get("name")?.as_str()?;
let description = tool
.get("description")
.and_then(|d| d.as_str())
.unwrap_or("");
let input_schema = tool
.get("input_schema")
.cloned()
.unwrap_or(serde_json::json!({}));
Some(serde_json::json!({
"type": "function",
"function": {
"name": name,
"description": description,
"parameters": input_schema
}
}))
})
.collect();
if !openai_tools.is_empty() {
result["tools"] = serde_json::Value::Array(openai_tools);
}
}
// Pass through common parameters
for key in &[
// "max_tokens",
"temperature",
"top_p",
"top_k",
"frequency_penalty",
"presence_penalty",
] {
if let Some(val) = body.get(*key) {
result[*key] = val.clone();
}
}
if let Some(stop) = body.get("stop_sequences") {
result["stop"] = stop.clone();
}
Some(result)
}
/// Strips the `x-anthropic-billing-header:` attribution that Claude Code
/// prepends to the system prompt / first message. Its values (cc_version, cch,
/// …) are dynamic, so leaving them in the content busts Anthropic prompt
/// caching and leaks CLI metadata to the model. Handles both observed shapes:
/// inline: "x-anthropic-billing-header: cc_version=…;\n<prompt>"
/// wrapped: "x-anthropic-billing-header:\n cc_version=…;\n<prompt>"
pub(crate) fn strip_anthropic_billing_header(text: &str) -> &str {
const KEY: &str = "x-anthropic-billing-header:";
if text.len() < KEY.len() || !text[..KEY.len()].eq_ignore_ascii_case(KEY) {
return text;
}
let first_nl = match text.find('\n') {
Some(i) => i,
None => return text,
};
let after_first = &text[first_nl + 1..];
// Inline form: metadata sits on the header line itself.
if text[..first_nl].contains("cc_version=") || text[..first_nl].contains("cc_entrypoint=") {
return after_first;
}
// Wrapped form: metadata is the continuation line.
if let Some(rel) = after_first.find('\n') {
let cont = &after_first[..rel];
if cont.contains("cc_version=") || cont.contains("cc_entrypoint=") || cont.contains("cch=")
{
return &after_first[rel + 1..];
}
}
text
}
/// Applies `strip_anthropic_billing_header` to a message/system `content` value
/// (a bare string or an array of content blocks — only the first text block can
/// carry the header).
fn strip_billing_header_in_content(content: &mut serde_json::Value) {
match content {
serde_json::Value::String(s) => {
let stripped = strip_anthropic_billing_header(s);
if stripped.len() != s.len() {
*s = stripped.to_string();
}
}
serde_json::Value::Array(blocks) => {
for block in blocks.iter_mut() {
if let Some(text_val) = block.get_mut("text") {
if let Some(orig) = text_val.as_str() {
let stripped = strip_anthropic_billing_header(orig);
if stripped.len() != orig.len() {
let owned = stripped.to_string();
*text_val = serde_json::Value::String(owned);
}
}
break;
}
}
}
_ => {}
}
}
/// Strips the Claude Code billing header from an in-flight request body, in
/// place, before it is forwarded upstream. Covers the Anthropic `system` field
/// and the first message's content (the only places Claude Code injects it).
pub(crate) fn strip_billing_header_in_body(body: &mut serde_json::Value) {
if let Some(system) = body.get_mut("system") {
strip_billing_header_in_content(system);
}
if let Some(first) = body
.get_mut("messages")
.and_then(|v| v.as_array_mut())
.and_then(|arr| arr.first_mut())
{
if let Some(content) = first.get_mut("content") {
strip_billing_header_in_content(content);
}
}
}
/// Fills in top-level sampling defaults the caller omitted. Used for MLX
/// targets, which (unlike the llama.cpp router) have no preset to carry
/// server-side defaults. `defaults` is already in the target's key form
/// (e.g. `repetition_penalty`, not `repeat_penalty`); a present key is never
/// overwritten, so a per-request value always wins.
pub(crate) fn inject_sampling_defaults(body: &mut serde_json::Value, defaults: &serde_json::Value) {
let (Some(obj), Some(defaults_obj)) = (body.as_object_mut(), defaults.as_object()) else {
return;
};
for (k, v) in defaults_obj {
if !obj.contains_key(k) {
obj.insert(k.clone(), v.clone());
}
}
}
/// Convert Anthropic message format to OpenAI format
pub(crate) fn convert_messages(
anth_messages: &serde_json::Value,
system_prompt: Option<&serde_json::Value>,
) -> Option<serde_json::Value> {
let messages_array = anth_messages.as_array()?;
let mut openai_messages: Vec<serde_json::Value> = Vec::new();
// Anthropic system prompt is a top-level field, convert to system message
if let Some(system) = system_prompt {
if let Some(text) = system.as_str() {
openai_messages.push(serde_json::json!({
"role": "system",
"content": text
}));
} else if let Some(blocks) = system.as_array() {
let text: String = blocks
.iter()
.filter_map(|b| b.get("text").and_then(|t| t.as_str()))
.collect::<Vec<_>>()
.join("\n");
if !text.is_empty() {
openai_messages.push(serde_json::json!({
"role": "system",
"content": text
}));
}
}
}
for msg in messages_array {
let role = msg.get("role")?.as_str()?;
let content = msg.get("content")?;
if content.is_string() {
let openai_role = match role {
"user" => "user",
"assistant" => "assistant",
"system" => "system",
"developer" => "developer",
_ => continue,
};
openai_messages.push(serde_json::json!({
"role": openai_role,
"content": content
}));
continue;
}
let content_array = content.as_array()?;
match role {
"assistant" => {
// Split content into text/image parts and tool_calls
let mut text_parts: Vec<serde_json::Value> = Vec::new();
let mut tool_calls: Vec<serde_json::Value> = Vec::new();
for block in content_array {
let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
match block_type {
"text" => {
if let Some(text) = block.get("text").and_then(|v| v.as_str()) {
text_parts.push(serde_json::json!({
"type": "text",
"text": text
}));
}
}
"tool_use" => {
if let (Some(id), Some(name), Some(input)) = (
block.get("id").and_then(|v| v.as_str()),
block.get("name").and_then(|v| v.as_str()),
block.get("input"),
) {
tool_calls.push(serde_json::json!({
"id": id,
"type": "function",
"function": {
"name": name,
"arguments": input.to_string()
}
}));
}
}
_ => {
convert_media_block(block, &mut text_parts);
}
}
}
let mut msg_obj = serde_json::json!({ "role": "assistant" });
if tool_calls.is_empty() {
// No tool calls: set content normally
msg_obj["content"] = text_parts_to_content(&text_parts);
} else {
// Has tool calls: content can be null or text string
msg_obj["content"] = if text_parts.is_empty() {
serde_json::Value::Null
} else {
text_parts_to_content(&text_parts)
};
msg_obj["tool_calls"] = serde_json::Value::Array(tool_calls);
}
openai_messages.push(msg_obj);
}
"user" => {
// Separate tool_result blocks from regular content
let mut text_parts: Vec<serde_json::Value> = Vec::new();
let mut tool_results: Vec<(String, String)> = Vec::new();
for block in content_array {
let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
match block_type {
"tool_result" => {
let tool_use_id = block
.get("tool_use_id")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let result_content = extract_tool_result_content(block.get("content"));
tool_results.push((tool_use_id, result_content));
}
"text" => {
if let Some(text) = block.get("text").and_then(|v| v.as_str()) {
text_parts.push(serde_json::json!({
"type": "text",
"text": text
}));
}
}
_ => {
convert_media_block(block, &mut text_parts);
}
}
}
// Tool results become role:"tool" messages (must come before user text)
for (tool_call_id, result) in tool_results {
openai_messages.push(serde_json::json!({
"role": "tool",
"tool_call_id": tool_call_id,
"content": result
}));
}
// Remaining user content
if !text_parts.is_empty() {
openai_messages.push(serde_json::json!({
"role": "user",
"content": text_parts_to_content(&text_parts)
}));
}
}
"system" | "developer" => {
let text: String = content_array
.iter()
.filter_map(|b| b.get("text").and_then(|t| t.as_str()))
.collect::<Vec<_>>()
.join("\n");
openai_messages.push(serde_json::json!({
"role": role,
"content": text
}));
}
_ => continue,
}
}
Some(serde_json::Value::Array(openai_messages))
}
/// Convert text parts to OpenAI content value (string for single text, array for mixed)
pub(crate) fn text_parts_to_content(parts: &[serde_json::Value]) -> serde_json::Value {
if parts.is_empty() {
serde_json::Value::String(String::new())
} else if parts.len() == 1 && parts[0].get("type").and_then(|t| t.as_str()) == Some("text") {
serde_json::Value::String(
parts[0]
.get("text")
.and_then(|t| t.as_str())
.unwrap_or("")
.to_string(),
)
} else {
serde_json::Value::Array(parts.to_vec())
}
}
/// Convert image/media blocks to OpenAI format
pub(crate) fn convert_media_block(block: &serde_json::Value, parts: &mut Vec<serde_json::Value>) {
let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
if block_type == "image" {
if let Some(source) = block.get("source") {
if let (Some(data), Some(media_type)) = (
source.get("data").and_then(|v| v.as_str()),
source
.get("media_type")
.or(block.get("media_type"))
.and_then(|v| v.as_str()),
) {
parts.push(serde_json::json!({
"type": "image_url",
"image_url": {
"url": format!("data:{media_type};base64,{data}")
}
}));
}
}
} else if let Some(text) = block.get("text").and_then(|t| t.as_str()) {
parts.push(serde_json::json!({
"type": "text",
"text": text
}));
}
}
/// Extract text content from a tool_result content field
pub(crate) fn extract_tool_result_content(content: Option<&serde_json::Value>) -> String {
match content {
Some(c) if c.is_string() => c.as_str().unwrap_or("").to_string(),
Some(c) if c.is_array() => c
.as_array()
.unwrap()
.iter()
.filter_map(|b| {
if b.get("type").and_then(|t| t.as_str()) == Some("text") {
b.get("text").and_then(|t| t.as_str())
} else {
None
}
})
.collect::<Vec<_>>()
.join("\n"),
Some(c) => c.to_string(),
None => String::new(),
}
}
/// Transform OpenAI non-streaming response to Anthropic /messages format
pub(crate) fn transform_openai_response_to_anthropic(
response: &serde_json::Value,
) -> serde_json::Value {
let choice = response
.get("choices")
.and_then(|c| c.as_array())
.and_then(|c| c.first());
let message = choice.and_then(|c| c.get("message"));
let mut content_blocks: Vec<serde_json::Value> = Vec::new();
// Add text content
if let Some(text) =
message
.and_then(|m| m.get("content"))
.and_then(|c| if c.is_null() { None } else { c.as_str() })
{
if !text.is_empty() {
content_blocks.push(serde_json::json!({
"type": "text",
"text": text
}));
}
}
// Add tool_use blocks from tool_calls
if let Some(tool_calls) = message
.and_then(|m| m.get("tool_calls"))
.and_then(|tc| tc.as_array())
{
for tc in tool_calls {
let id = tc.get("id").and_then(|v| v.as_str()).unwrap_or("");
let name = tc
.get("function")
.and_then(|f| f.get("name"))
.and_then(|n| n.as_str())
.unwrap_or("");
let arguments = tc
.get("function")
.and_then(|f| f.get("arguments"))
.and_then(|a| a.as_str())
.unwrap_or("{}");
let input: serde_json::Value =
serde_json::from_str(arguments).unwrap_or(serde_json::json!({}));
content_blocks.push(serde_json::json!({
"type": "tool_use",
"id": id,
"name": name,
"input": input
}));
}
}
let finish_reason = choice
.and_then(|c| c.get("finish_reason"))
.and_then(|fr| fr.as_str())
.unwrap_or("end_turn");
let stop_reason = match finish_reason {
"stop" => "end_turn",
"length" => "max_tokens",
"tool_calls" => "tool_use",
_ => finish_reason,
};
serde_json::json!({
"id": response.get("id").unwrap_or(&serde_json::json!("")).clone(),
"type": "message",
"role": "assistant",
"content": content_blocks,
"model": response.get("model").unwrap_or(&serde_json::json!("")).clone(),
"stop_reason": stop_reason,
"stop_sequence": serde_json::Value::Null,
"usage": response.get("usage").cloned().unwrap_or(serde_json::json!({
"input_tokens": 0,
"output_tokens": 0
}))
})
}
/// Configuration for the proxy server
#[derive(Clone)]
pub struct ProxyConfig {
pub prefix: String,
pub proxy_api_key: String,
pub trusted_hosts: Vec<Vec<String>>,
pub host: String,
pub port: u16,
pub enable_server_tool_execution: bool,
/// "Allow cross-origin requests" setting. When off, only the server's own
/// pages and the app webview may call it from a browser context.
pub cors_enabled: bool,
}
/// Whether a request carrying this `Origin` may proceed. Requests without an
/// Origin (curl, SDKs, CLI tools, LAN clients) always may; browser requests
/// must come from a trusted origin (see `jan_utils::is_trusted_origin`).
///
/// Runs on every non-preflight request, before auth and body parsing, because
/// a browser sends "simple" cross-origin POSTs (e.g. `text/plain`) without a
/// preflight, so CORS headers alone do not stop the request from executing.
pub(crate) fn origin_allowed(
origin: &str,
host_header: &str,
trusted_hosts: &[Vec<String>],
cors_enabled: bool,
) -> bool {
if origin.is_empty() {
return true;
}
// Same-origin trust relies on the Host header naming this server, so only
// a Host that passes validation counts.
let host = if is_valid_host(host_header, trusted_hosts) {
host_header
} else {
""
};
if cors_enabled {
is_trusted_origin(origin, host, trusted_hosts)
} else {
is_same_or_app_origin(origin, host)
}
}
/// The request's `Origin` header, or "" when there is none. None when the
/// header is present but not visible ASCII: such a request must be refused,
/// not treated as one without an origin.
pub(crate) fn request_origin(headers: &hyper::HeaderMap) -> Option<&str> {
match headers.get(hyper::header::ORIGIN) {
None => Some(""),
Some(value) => value.to_str().ok(),
}
}
/// `/orchestrations` runs MCP tools without per-call approval, so it is only
/// served when the user opted in to server-side tool execution.
pub(crate) fn orchestrations_allowed(config: &ProxyConfig) -> bool {
config.enable_server_tool_execution
}
/// Determines the final destination path based on the original request path
pub fn get_destination_path(original_path: &str, prefix: &str) -> String {
remove_prefix(original_path, prefix)
}
use crate::core::server::MlxBackendSession;
/// The loopback endpoint local-model requests are forwarded to: the engine
/// worker's `/v1` surface, or None when no engine is running.
pub(crate) async fn engine_upstream(
llama_state: &LlamacppState,
destination_path: &str,
) -> Option<(String, String)> {
let guard = llama_state.engine.lock().await;
guard.as_ref().map(|h| {
(
format!("http://127.0.0.1:{}/v1{}", h.port, destination_path),
h.api_key.clone(),
)
})
}
pub(crate) async fn engine_list_models(
llama_state: &LlamacppState,
client: &Client,
) -> Vec<String> {
let (url, key) = match engine_upstream(llama_state, "/models").await {
Some(v) => v,
None => return Vec::new(),
};
let resp = match client
.get(&url)
.header("Authorization", format!("Bearer {key}"))
.send()
.await
{
Ok(r) => r,
Err(e) => {
log::warn!("Failed to query the engine's /v1/models: {e}");
return Vec::new();
}
};
if !resp.status().is_success() {
return Vec::new();
}
let json: serde_json::Value = match resp.json().await {
Ok(v) => v,
Err(_) => return Vec::new(),
};
json.get("data")
.and_then(|d| d.as_array())
.map(|arr| {
arr.iter()
.filter_map(|m| m.get("id").and_then(|v| v.as_str()).map(str::to_owned))
.collect()
})
.unwrap_or_default()
}
pub(crate) async fn router_first_model(
llama_state: &LlamacppState,
client: &Client,
) -> Option<String> {
engine_list_models(llama_state, client)
.await
.into_iter()
.next()
}
/// Handles the proxy request logic
#[allow(clippy::too_many_arguments)]
async fn proxy_request(
req: Request<Incoming>,
client: Client,
config: ProxyConfig,
llama_state: Arc<LlamacppState>,
mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,
provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,
model_param_defaults: Arc<Mutex<HashMap<String, serde_json::Value>>>,
mcp_servers: SharedMcpServers,
mcp_settings: Arc<Mutex<McpSettings>>,
jan_data_folder: String,
) -> Result<Response<ResBody>, hyper::Error> {
if req.method() == hyper::Method::OPTIONS {
log::debug!(
"Handling CORS preflight request from {:?} {:?}",
req.headers().get(hyper::header::HOST),
req.headers()
.get(hyper::header::ACCESS_CONTROL_REQUEST_METHOD)
);
let host = req
.headers()
.get(hyper::header::HOST)
.and_then(|v| v.to_str().ok())
.unwrap_or("");
let origin = req
.headers()
.get(hyper::header::ORIGIN)
.and_then(|v| v.to_str().ok())
.unwrap_or("");
let requested_method = req
.headers()
.get("Access-Control-Request-Method")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
let allowed_methods = ["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"];
let method_allowed = requested_method.is_empty()
|| allowed_methods
.iter()
.any(|&method| method.eq_ignore_ascii_case(requested_method));
if !method_allowed {
log::warn!("CORS preflight: Method '{requested_method}' not allowed");
return Ok(Response::builder()
.status(StatusCode::METHOD_NOT_ALLOWED)
.body(full("Method not allowed"))
.unwrap());
}
let request_path = req.uri().path();
let whitelisted_paths = ["/", "/openapi.json", "/favicon.ico"];
let is_whitelisted_path = whitelisted_paths.contains(&request_path);
let is_trusted = if is_whitelisted_path {
log::debug!(
"CORS preflight: Bypassing host check for whitelisted path: {request_path}"
);
true
} else if !host.is_empty() {
log::debug!(
"CORS preflight: Host is '{host}', trusted hosts: {:?}",
config.trusted_hosts
);
is_valid_host(host, &config.trusted_hosts)
} else {
log::warn!("CORS preflight: No Host header present");
false
};
if !is_trusted {
log::warn!("CORS preflight: Host '{host}' not trusted for path '{request_path}'");
return Ok(Response::builder()
.status(StatusCode::FORBIDDEN)
.body(full("Host not allowed"))
.unwrap());
}
let requested_headers = req
.headers()
.get("Access-Control-Request-Headers")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
let allowed_headers = [
"accept",
"accept-language",
"authorization",
"cache-control",
"connection",
"content-type",
"dnt",
"host",
"if-modified-since",
"keep-alive",
"origin",
"user-agent",
"x-api-key",
"x-csrf-token",
"x-forwarded-for",
"x-forwarded-host",
"x-forwarded-proto",
"x-requested-with",
"x-stainless-arch",
"x-stainless-lang",
"x-stainless-os",
"x-stainless-package-version",
"x-stainless-retry-count",
"x-stainless-runtime",
"x-stainless-runtime-version",
"x-stainless-timeout",
];
let headers_valid = if requested_headers.is_empty() {
true
} else {
requested_headers
.split(',')
.map(|h| h.trim())
.all(|header| {
allowed_headers
.iter()
.any(|&allowed| allowed.eq_ignore_ascii_case(header))
})
};
if !headers_valid {
log::warn!("CORS preflight: Some requested headers not allowed: {requested_headers}");
return Ok(Response::builder()
.status(StatusCode::FORBIDDEN)
.body(full("Headers not allowed"))
.unwrap());
}
let mut response = Response::builder()
.status(StatusCode::OK)
.header("Access-Control-Allow-Methods", allowed_methods.join(", "))
.header("Access-Control-Allow-Headers", allowed_headers.join(", "))
.header("Access-Control-Max-Age", "86400")
.header(
"Vary",
"Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
);
if !origin.is_empty() {
if origin_allowed(origin, host, &config.trusted_hosts, config.cors_enabled) {
response = response
.header("Access-Control-Allow-Origin", origin)
.header("Access-Control-Allow-Credentials", "true");
} else {
log::warn!(
"CORS preflight: Origin '{origin}' is not trusted, not reflecting origin"
);
}
}
log::debug!("CORS preflight response: host_trusted={is_trusted}, origin='{origin}'");
return Ok(response.body(empty()).unwrap());
}
let (parts, body) = req.into_parts();
let Some(origin_header) = request_origin(&parts.headers).map(str::to_string) else {
log::warn!("Rejected request with an Origin header that is not visible ASCII");
return Ok(Response::builder()
.status(StatusCode::FORBIDDEN)
.header("Vary", "Origin")
.body(full("Origin not allowed"))
.unwrap());
};
let host_header = parts
.headers
.get(hyper::header::HOST)
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_string();
if !origin_allowed(
&origin_header,
&host_header,
&config.trusted_hosts,
config.cors_enabled,
) {
log::warn!("Rejected request from untrusted origin '{origin_header}'");
return Ok(Response::builder()
.status(StatusCode::FORBIDDEN)
.header("Vary", "Origin")
.body(full("Origin not allowed"))
.unwrap());
}
let original_path = parts.uri.path();
let headers = parts.headers.clone();
let path = get_destination_path(original_path, &config.prefix);
let method = parts.method.clone();
let whitelisted_paths = [
"/",
"/openapi.json",
"/favicon.ico",
"/docs/swagger-ui.css",
"/docs/swagger-ui-bundle.js",
"/docs/swagger-ui-standalone-preset.js",
];
let is_whitelisted_path = whitelisted_paths.contains(&path.as_str());
if !is_whitelisted_path {
if !host_header.is_empty() {
if !is_valid_host(&host_header, &config.trusted_hosts) {
let mut error_response = Response::builder().status(StatusCode::FORBIDDEN);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full("Invalid host header")).unwrap());
}
} else {
let mut error_response = Response::builder().status(StatusCode::BAD_REQUEST);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full("Missing host header")).unwrap());
}
} else {
log::debug!("Bypassing host validation for whitelisted path: {path}");
}
if !is_whitelisted_path && !config.proxy_api_key.is_empty() {
// Check Authorization header (Bearer token)
let auth_valid = parts
.headers
.get(hyper::header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|auth_str| auth_str.strip_prefix("Bearer "))
.map(|token| token == config.proxy_api_key)
.unwrap_or(false);
// Check X-Api-Key header
let api_key_valid = parts
.headers
.get("X-Api-Key")
.and_then(|v| v.to_str().ok())
.map(|key| key == config.proxy_api_key)
.unwrap_or(false);
if !auth_valid && !api_key_valid {
let mut error_response = Response::builder().status(StatusCode::UNAUTHORIZED);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response
.body(full("Invalid or missing authorization token"))
.unwrap());
}
} else if is_whitelisted_path {
log::debug!("Bypassing authorization check for whitelisted path: {path}");
}
if path.contains("/configs") {
let mut error_response = Response::builder().status(StatusCode::NOT_FOUND);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full("Not Found")).unwrap());
}
let original_path = parts.uri.path();
let destination_path = get_destination_path(original_path, &config.prefix);
// Initialize variables that will be set in the match
let mut session_api_keys: Vec<String> = Vec::new();
#[allow(unused_assignments)]
let mut buffered_body: Option<Bytes> = None;
let mut target_base_url: Option<String> = None;
let mut is_anthropic_messages = false;
// Set when the resolved remote provider fronts a non-chat/completions native
// API; drives request rewrite + response translation back to chat shape.
let mut upstream_converter: Option<Box<dyn UpstreamConverter>> = None;
// Model id when the request resolves to an MLX session — MLX has no preset,
// so sampling defaults are injected into the body before forwarding.
let mut mlx_model_id: Option<String> = None;
match (method.clone(), destination_path.as_str()) {
// Anthropic /messages endpoint - tries /messages first, falls back to /chat/completions on error
(hyper::Method::POST, "/messages") => {
is_anthropic_messages = true;
log::info!(
"Handling POST request to /messages with chat/completions fallback on error",
);
let body_bytes = match body.collect().await {
Ok(c) => c.to_bytes(),
Err(_) => {
let mut error_response =
Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response
.body(full("Failed to read request body"))
.unwrap());
}
};
buffered_body = Some(body_bytes.clone());
// Parse body to get model_id for routing (don't transform yet)
match serde_json::from_slice::<serde_json::Value>(&body_bytes) {
Ok(mut json_body) => {
// Drop Claude Code's billing-header attribution before it is
// forwarded (passthrough) or transformed, so it can't bust
// upstream prompt caching or reach the model.
strip_billing_header_in_body(&mut json_body);
if let Ok(cleaned) = serde_json::to_vec(&json_body) {
buffered_body = Some(cleaned.into());
}
if config.enable_server_tool_execution
&& !json_body
.get("stream")
.and_then(|v| v.as_bool())
.unwrap_or(false)
{
let openai_body = match transform_anthropic_to_openai(&json_body) {
Some(v) => v,
None => {
let mut error_response =
Response::builder().status(StatusCode::BAD_REQUEST);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response
.body(full("Invalid /messages payload for orchestration mode"))
.unwrap());
}
};
match run_server_side_openai_orchestration(
&openai_body,
// The agent loop runs on genai (reqwest 0.13); the
// proxy's own passthrough stays on 0.12.
&crate::core::agent::upstream::agent_http_client(),
provider_configs.clone(),
llama_state.clone(),
mlx_sessions.clone(),
mcp_servers.clone(),
mcp_settings.clone(),
&jan_data_folder,
)
.await
{
Ok(openai_response) => {
let anthropic_response =
transform_openai_response_to_anthropic(&openai_response);
let body_str = serde_json::to_string(&anthropic_response)
.unwrap_or_else(|_| "{}".to_string());
let mut response_builder = Response::builder()
.status(StatusCode::OK)
.header(hyper::header::CONTENT_TYPE, "application/json");
response_builder = add_cors_headers_with_host_and_origin(
response_builder,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(response_builder.body(full(body_str)).unwrap());
}
Err(e) => {
let mut error_response =
Response::builder().status(StatusCode::BAD_GATEWAY);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full(e)).unwrap());
}
}
}
if let Some(model_id) = json_body.get("model").and_then(|v| v.as_str()) {
let pc = provider_configs.lock().await;
// Try to find a provider for this model
let provider_name: Option<String> = pc
.iter()
.find(|(_, config)| config.models.iter().any(|m| m == model_id))
.map(|(_, config)| config.provider.clone())
.or_else(|| {
if let Some(sep_pos) = model_id.find('/') {
let potential_provider: &str = &model_id[..sep_pos];
if pc.contains_key(potential_provider) {
return Some(potential_provider.to_string());
}
}
pc.get(model_id).map(|c| c.provider.clone())
});
drop(pc);
if let Some(ref p) = provider_name {
log::info!("Using remote provider '{p}' for model '{model_id}'");
let pc2 = provider_configs.lock().await;
let provider_config = pc2.get(p.as_str()).cloned();
drop(pc2);
if let Some(provider_cfg) = provider_config {
target_base_url = provider_cfg.base_url.clone().map(|url| {
format!("{}{}", url.trim_end_matches('/'), "/messages")
});
session_api_keys = provider_cfg.bearer_key_chain();
}
} else {
let mlx_session_info = {
let mlx_guard = mlx_sessions.lock().await;
mlx_guard
.values()
.find(|s| s.info.model_id == model_id)
.map(|s| s.info.clone())
};
if let Some(info) = mlx_session_info {
let target_port = info.port;
session_api_keys = vec![info.api_key.clone()];
mlx_model_id = Some(model_id.to_string());
target_base_url =
Some(format!("http://127.0.0.1:{}/v1/messages", target_port));
} else if let Some((url, key)) =
engine_upstream(&llama_state, "/messages").await
{
session_api_keys = vec![key];
target_base_url = Some(url);
} else {
log::warn!("No running session found for model_id: {model_id}");
let mut error_response =
Response::builder().status(StatusCode::NOT_FOUND);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response
.body(full(format!(
"No running session found for model '{model_id}'"
)))
.unwrap());
}
}
} else {
let error_msg = "Request body must contain a 'model' field";
log::warn!("POST body for /messages missing 'model' field");
let mut error_response =
Response::builder().status(StatusCode::BAD_REQUEST);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full(error_msg)).unwrap());
}
}
Err(e) => {
log::warn!("Failed to parse POST body for /messages as JSON: {e}");
let mut error_response = Response::builder().status(StatusCode::BAD_REQUEST);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
let error_msg = format!("Invalid JSON body: {}", e);
return Ok(error_response.body(full(error_msg)).unwrap());
}
}
}
(hyper::Method::POST, "/orchestrations") => {
// Headless orchestration endpoint:
// - Load assistant system prompt + assistant model hint
// - Ask the model for tool_calls
// - Execute MCP tools server-side
// - Feed tool results back and continue until completion
log::info!(
"Handling POST request to {destination_path} for assistant tool orchestration"
);
if !orchestrations_allowed(&config) {
let mut error_response = Response::builder().status(StatusCode::FORBIDDEN);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response
.body(full(
"/orchestrations requires server-side tool execution to be enabled in Settings > Local API Server",
))
.unwrap());
}
let body_bytes = match body.collect().await {
Ok(c) => c.to_bytes(),
Err(_) => {
let mut error_response =
Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response
.body(full("Failed to read request body"))
.unwrap());
}
};
let json_body: serde_json::Value = match serde_json::from_slice(&body_bytes) {
Ok(v) => v,
Err(e) => {
let mut error_response = Response::builder().status(StatusCode::BAD_REQUEST);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response
.body(full(format!("Invalid JSON body: {e}")))
.unwrap());
}
};
let assistant_id = json_body
.get("assistant_id")
.and_then(|v| v.as_str())
.map(str::trim)
.filter(|v| !v.is_empty())
.map(|v| v.to_string());
let stream = json_body
.get("stream")
.and_then(|v| v.as_bool())
.unwrap_or(false);
if stream {
let mut error_response = Response::builder().status(StatusCode::BAD_REQUEST);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response
.body(full("stream=true is not supported for /orchestrations"))
.unwrap());
}
let messages_value = match json_body.get("messages") {
Some(v) => v,
None => {
let mut error_response = Response::builder().status(StatusCode::BAD_REQUEST);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response
.body(full("Missing required field 'messages'"))
.unwrap());
}
};
let mut conversation_messages = match parse_openai_messages(messages_value) {
Ok(msgs) => msgs,
Err(e) => {
let mut error_response = Response::builder().status(StatusCode::BAD_REQUEST);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full(e)).unwrap());
}
};
// Self-heal a client-supplied conversation: a `role: "tool"`
// result whose call is not in the request, or a `tool_calls` turn
// missing one of its results, is rejected outright by some
// providers (notably Anthropic), so both shapes are fixed before
// the request goes on.
let orphaned = drop_orphaned_tool_results(&mut conversation_messages);
if orphaned > 0 {
log::warn!(
"proxy: dropped {orphaned} tool result(s) whose call is not in the request"
);
}
let repaired = repair_dangling_tool_calls(&mut conversation_messages);
if repaired > 0 {
log::warn!("proxy: repaired {repaired} dangling tool call(s) with no prior result");
}
// Load assistant config for system prompt + model hint when assistant_id is provided.
let (assistant_instructions, assistant_model_hint) =
if let Some(assistant_id) = assistant_id.as_deref() {
match load_assistant_config(&jan_data_folder, assistant_id) {
Ok(v) => v,
Err(e) => {
let mut error_response =
Response::builder().status(StatusCode::BAD_REQUEST);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full(e)).unwrap());
}
}
} else {
(None, None)
};
if let Some(sys) = assistant_instructions {
// The caller's own `system` message is the one this replaces:
// the request is stateless, so there is no earlier request to
// keep byte-stable.
replace_system_prompt(&mut conversation_messages, &sys);
}
// Resolve model to use for orchestration.
let model_override = json_body.get("model").and_then(|v| v.as_str());
let mut model_id: Option<String>;
if let Some(ov) = model_override {
model_id = Some(ov.to_string());
} else if let Some(h) = assistant_model_hint {
let trimmed = h.trim();
if !trimmed.is_empty() && trimmed != "*" {
model_id = Some(trimmed.to_string());
} else {
model_id = router_first_model(&llama_state, &client).await;
if model_id.is_none() {
let mlx_guard = mlx_sessions.lock().await;
model_id = mlx_guard.values().next().map(|s| s.info.model_id.clone());
}
}
} else {
model_id = router_first_model(&llama_state, &client).await;
if model_id.is_none() {
let mlx_guard = mlx_sessions.lock().await;
model_id = mlx_guard.values().next().map(|s| s.info.model_id.clone());
}
}
let model_id = match model_id {
Some(v) => v,
None => {
let mut error_response =
Response::builder().status(StatusCode::SERVICE_UNAVAILABLE);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response
.body(full("No running model sessions available"))
.unwrap());
}
};
// Tool execution support (MCP only for now).
let (openai_tools, tool_to_server) =
match collect_mcp_openai_tools(&mcp_servers, &mcp_settings).await {
Ok(v) => v,
Err(e) => {
let mut error_response =
Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full(e)).unwrap());
}
};
let (upstream_url, session_api_keys) = match resolve_upstream_for_model(
&model_id,
provider_configs.clone(),
llama_state.clone(),
mlx_sessions.clone(),
)
.await
{
Ok(v) => v,
Err(e) => {
let mut error_response = Response::builder().status(StatusCode::NOT_FOUND);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full(e)).unwrap());
}
};
// `provider/model` records the provider qualifier used to resolve
// the upstream above; the request body must carry the bare model id.
let body_model_id = {
let pc = provider_configs.lock().await;
crate::core::agent::upstream::strip_provider_prefix(&model_id, &pc)
};
let max_turns = json_body
.get("max_turns")
.and_then(|v| v.as_u64())
.unwrap_or(8)
.clamp(1, 20) as usize;
let mut last_response: Option<serde_json::Value> = None;
for _turn in 0..max_turns {
// Build upstream request body for each turn so messages are updated.
let mut completion_map = serde_json::Map::new();
completion_map.insert("model".to_string(), serde_json::json!(body_model_id));
completion_map.insert(
"messages".to_string(),
serde_json::Value::Array(conversation_messages.clone()),
);
completion_map.insert("stream".to_string(), serde_json::json!(false));
completion_map.insert("tool_choice".to_string(), serde_json::json!("auto"));
if !openai_tools.is_empty() {
completion_map.insert(
"tools".to_string(),
serde_json::Value::Array(openai_tools.clone()),
);
}
copy_optional_chat_params(&json_body, &mut completion_map);
let request_value = serde_json::Value::Object(completion_map);
let completion = match call_openai_chat_completions(
&client,
&upstream_url,
&session_api_keys,
&request_value,
)
.await
{
Ok(v) => v,
Err(e) => {
let mut error_response =
Response::builder().status(StatusCode::BAD_GATEWAY);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full(e)).unwrap());
}
};
let tool_calls = extract_tool_calls(&completion);
last_response = Some(completion.clone());
if tool_calls.is_empty() {
let body_str =
serde_json::to_string(&completion).unwrap_or_else(|_| "{}".to_string());
let mut response_builder = Response::builder()
.status(StatusCode::OK)
.header(hyper::header::CONTENT_TYPE, "application/json");
response_builder = add_cors_headers_with_host_and_origin(
response_builder,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(response_builder.body(full(body_str)).unwrap());
}
// Append assistant tool call message, then execute tool calls.
if let Some(choice_message) = extract_choice_message(&completion) {
let assistant_content = choice_message
.get("content")
.cloned()
.unwrap_or(serde_json::Value::Null);
conversation_messages.push(serde_json::json!({
"role": "assistant",
"content": assistant_content,
"tool_calls": tool_calls.clone()
}));
} else {
conversation_messages.push(serde_json::json!({
"role": "assistant",
"content": serde_json::Value::Null,
"tool_calls": tool_calls.clone()
}));
}
let tool_results = execute_mcp_tool_calls(
&tool_calls,
&tool_to_server,
&mcp_servers,
&mcp_settings,
)
.await;
for (tool_call_id, result_text) in tool_results {
conversation_messages.push(serde_json::json!({
"role": "tool",
"tool_call_id": tool_call_id,
"content": result_text
}));
}
}
// Safety catch: model kept requesting tools beyond max_turns.
let body_json = last_response.unwrap_or_else(|| serde_json::json!({}));
let body_str = serde_json::to_string(&body_json).unwrap_or_else(|_| "{}".to_string());
let mut error_response = Response::builder().status(StatusCode::UNPROCESSABLE_ENTITY);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
let payload = format!(
"{{\"error\":\"max_turns reached while resolving tool calls\",\"last_response\":{body_str}}}"
);
let response = error_response.body(full(payload)).unwrap();
return Ok(response);
}
(hyper::Method::POST, "/chat/completions")
| (hyper::Method::POST, "/completions")
| (hyper::Method::POST, "/embeddings")
| (hyper::Method::POST, "/messages/count_tokens") => {
log::info!(
"Handling POST request to {destination_path} requiring model lookup in body",
);
let body_bytes = match body.collect().await {
Ok(c) => c.to_bytes(),
Err(_) => {
let mut error_response =
Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response
.body(full("Failed to read request body"))
.unwrap());
}
};
buffered_body = Some(body_bytes.clone());
match serde_json::from_slice::<serde_json::Value>(&body_bytes) {
Ok(mut json_body) => {
// Work around strict JSON-schema converters that reject property schemas
// of the form `{ "description": "..." }` (missing `type`).
// This happens for OpenAI-style tool schemas used with /chat/completions.
if destination_path == "/chat/completions" {
normalize_openai_tools_in_chat_body(&mut json_body);
}
// Strip Claude Code's billing header from chat/token-count
// bodies too (it lands in the first message content here).
strip_billing_header_in_body(&mut json_body);
if let Ok(cleaned) = serde_json::to_vec(&json_body) {
buffered_body = Some(cleaned.into());
}
if config.enable_server_tool_execution
&& destination_path == "/chat/completions"
&& !json_body
.get("stream")
.and_then(|v| v.as_bool())
.unwrap_or(false)
{
match run_server_side_openai_orchestration(
&json_body,
&crate::core::agent::upstream::agent_http_client(),
provider_configs.clone(),
llama_state.clone(),
mlx_sessions.clone(),
mcp_servers.clone(),
mcp_settings.clone(),
&jan_data_folder,
)
.await
{
Ok(openai_response) => {
let body_str = serde_json::to_string(&openai_response)
.unwrap_or_else(|_| "{}".to_string());
let mut response_builder = Response::builder()
.status(StatusCode::OK)
.header(hyper::header::CONTENT_TYPE, "application/json");
response_builder = add_cors_headers_with_host_and_origin(
response_builder,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(response_builder.body(full(body_str)).unwrap());
}
Err(e) => {
let mut error_response =
Response::builder().status(StatusCode::BAD_GATEWAY);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full(e)).unwrap());
}
}
}
if let Some(model_id) = json_body.get("model").and_then(|v| v.as_str()) {
log::debug!("Extracted model_id: {model_id}");
// First, check if there's a registered remote provider for this model
let pc = provider_configs.lock().await;
// Try to find a provider that has this model configured
let provider_name = pc
.iter()
.find(|(_, config)| {
// Check if any model in this provider matches
config.models.iter().any(|m| m == model_id)
})
.map(|(_, config)| config.provider.clone())
.or_else(|| {
// Try to find by provider name in model_id (e.g., "anthropic/claude-3-opus")
if let Some(sep_pos) = model_id.find('/') {
let potential_provider: &str = &model_id[..sep_pos];
if pc.contains_key(potential_provider) {
return Some(potential_provider.to_string());
}
}
// Also check if the model_id itself matches a provider name
pc.get(model_id).map(|c| c.provider.clone())
});
drop(pc);
if let Some(ref provider) = provider_name {
// Found a remote provider, stream the response directly
log::info!("Found remote provider '{provider}' for model '{model_id}'");
// Get the provider config
let pc2 = provider_configs.lock().await;
let provider_config = pc2.get(provider.as_str()).cloned();
// Log registered providers for debugging
log::debug!(
"Registered providers: {:?}",
pc2.keys().collect::<Vec<_>>()
);
drop(pc2);
if let Some(provider_cfg) = provider_config {
// A converter only applies to chat/completions; other
// paths keep verbatim forwarding. The OAuth auth
// scheme applies only when the provider is actually
// authenticated with an OAuth account token, not
// merely because openai/anthropic also support
// account login (an API-key sign-in must stay on
// its plain key scheme).
let converter = if destination_path == "/chat/completions" {
// OAuth account login is a `cli` feature; the
// desktop has no OAuth account token here, so it
// must keep the plain API-key scheme rather than
// treat every anthropic provider as an account.
#[cfg(feature = "cli")]
let oauth = crate::core::cli::auth::account::
has_oauth_credential(&provider_cfg.provider);
#[cfg(not(feature = "cli"))]
let oauth = false;
converter_for(provider_cfg.api_type.as_deref(), oauth)
} else {
None
};
if let Some(api_url) = provider_cfg.base_url.clone() {
let path = converter
.as_ref()
.map(|c| c.upstream_path(&json_body))
.unwrap_or_else(|| destination_path.clone());
target_base_url = Some(format!("{api_url}{path}"));
} else {
target_base_url = None;
}
upstream_converter = converter;
session_api_keys = provider_cfg.bearer_key_chain();
} else {
log::error!("Provider config not found for '{provider}'");
}
} else {
let sessions_find_model = model_id;
let mlx_session_info = {
let mlx_guard = mlx_sessions.lock().await;
mlx_guard
.values()
.find(|s| s.info.model_id == sessions_find_model)
.map(|s| s.info.clone())
};
let router_up = engine_upstream(&llama_state, &destination_path).await;
if mlx_session_info.is_none() && router_up.is_none() {
log::warn!(
"Request for model '{model_id}' but no models are running."
);
let mut error_response =
Response::builder().status(StatusCode::SERVICE_UNAVAILABLE);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response
.body(full("No models are available"))
.unwrap());
}
if let Some(info) = mlx_session_info {
let target_port = info.port;
session_api_keys = vec![info.api_key.clone()];
mlx_model_id = Some(model_id.to_string());
log::debug!("Found MLX session for model_id {model_id}");
target_base_url = Some(format!(
"http://127.0.0.1:{target_port}/v1{destination_path}"
));
} else if let Some((url, key)) = router_up {
log::debug!("Routing model_id {model_id} via llamacpp router");
session_api_keys = vec![key];
target_base_url = Some(url);
} else {
log::warn!("No running session found for model_id: {model_id}");
let mut error_response =
Response::builder().status(StatusCode::NOT_FOUND);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response
.body(full(format!(
"No running session found for model '{model_id}'"
)))
.unwrap());
}
}
} else {
let error_msg = "Request body must contain a 'model' field";
log::warn!(
"POST body for {destination_path} is missing 'model' field or it's not a string"
);
let mut error_response =
Response::builder().status(StatusCode::BAD_REQUEST);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full(error_msg)).unwrap());
}
}
Err(e) => {
log::warn!("Failed to parse POST body for {destination_path} as JSON: {e}");
let mut error_response = Response::builder().status(StatusCode::BAD_REQUEST);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
let error_msg = format!("Invalid JSON body: {}", e);
return Ok(error_response.body(full(error_msg)).unwrap());
}
}
}
(hyper::Method::GET, "/models") => {
log::debug!("Handling GET /v1/models request");
let local_models: Vec<_> = engine_list_models(&llama_state, &client)
.await
.into_iter()
.map(|id| {
serde_json::json!({
"id": id,
"object": "model",
"created": 1,
"owned_by": "llama.cpp"
})
})
.collect();
// Get MLX sessions
let mlx_models: Vec<_> = {
let mlx_guard = mlx_sessions.lock().await;
mlx_guard
.values()
.map(|session| {
serde_json::json!({
"id": session.info.model_id,
"object": "model",
"created": 1,
"owned_by": "mlx"
})
})
.collect()
};
// Get remote provider models
let pc = provider_configs.lock().await;
let remote_models: Vec<_> = pc
.values()
.flat_map(|provider_cfg| provider_cfg.models.clone())
.map(|model_id| {
serde_json::json!({
"id": model_id,
"object": "model",
"created": 1,
"owned_by": "remote"
})
})
.collect();
// Store counts before moving
let local_count = local_models.len();
let mlx_count = mlx_models.len();
let remote_count = remote_models.len();
// Combine all models
let mut all_models = Vec::with_capacity(local_count + mlx_count + remote_count);
all_models.extend(local_models);
all_models.extend(mlx_models);
all_models.extend(remote_models);
let response_json = serde_json::json!({
"object": "list",
"data": all_models
});
let body_str =
serde_json::to_string(&response_json).unwrap_or_else(|_| "{}".to_string());
let mut response_builder = Response::builder()
.status(StatusCode::OK)
.header(hyper::header::CONTENT_TYPE, "application/json");
response_builder = add_cors_headers_with_host_and_origin(
response_builder,
&host_header,
&origin_header,
&config.trusted_hosts,
);
log::debug!(
"Returning {} models ({} llama.cpp, {} MLX, {} remote)",
all_models.len(),
local_count,
mlx_count,
remote_count
);
return Ok(response_builder.body(full(body_str)).unwrap());
}
(hyper::Method::GET, "/openapi.json") => {
let static_body = include_str!("../../../static/openapi.json"); // relative to src-tauri/src/
// Parse the static OpenAPI JSON and update the server URL with actual host and port
match serde_json::from_str::<serde_json::Value>(static_body) {
Ok(mut openapi_spec) => {
// Update the servers array with the actual host and port
if let Some(servers) = openapi_spec
.get_mut("servers")
.and_then(|s| s.as_array_mut())
{
for server in servers {
if let Some(server_obj) = server.as_object_mut() {
if let Some(url) = server_obj.get_mut("url") {
let base_url = format!(
"http://{}:{}{}",
config.host, config.port, config.prefix
);
*url = serde_json::Value::String(base_url);
}
}
}
}
let body = serde_json::to_string(&openapi_spec)
.unwrap_or_else(|_| static_body.to_string());
return Ok(Response::builder()
.status(StatusCode::OK)
.header(hyper::header::CONTENT_TYPE, "application/json")
.body(full(body))
.unwrap());
}
Err(_) => {
// If parsing fails, return the static file as fallback
return Ok(Response::builder()
.status(StatusCode::OK)
.header(hyper::header::CONTENT_TYPE, "application/json")
.body(full(static_body))
.unwrap());
}
}
}
// DOCS route
(hyper::Method::GET, "/") => {
let html = r#"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>API Docs</title>
<link rel="stylesheet" type="text/css" href="/docs/swagger-ui.css">
</head>
<body>
<div id="swagger-ui"></div>
<script src="/docs/swagger-ui-bundle.js"></script>
<script>
window.onload = () => {
SwaggerUIBundle({
url: '/openapi.json',
dom_id: '#swagger-ui',
});
};
</script>
</body>
</html>
"#;
let mut response_builder = Response::builder()
.status(StatusCode::OK)
.header(hyper::header::CONTENT_TYPE, "text/html");
response_builder = add_cors_headers_with_host_and_origin(
response_builder,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(response_builder.body(full(html)).unwrap());
}
(hyper::Method::GET, "/docs/swagger-ui.css") => {
let css = include_str!("../../../static/swagger-ui/swagger-ui.css");
return Ok(Response::builder()
.status(StatusCode::OK)
.header(hyper::header::CONTENT_TYPE, "text/css")
.body(full(css))
.unwrap());
}
(hyper::Method::GET, "/docs/swagger-ui-bundle.js") => {
let js = include_str!("../../../static/swagger-ui/swagger-ui-bundle.js");
return Ok(Response::builder()
.status(StatusCode::OK)
.header(hyper::header::CONTENT_TYPE, "application/javascript")
.body(full(js))
.unwrap());
}
(hyper::Method::GET, "/favicon.ico") => {
let icon = include_bytes!("../../../static/swagger-ui/favicon.ico");
return Ok(Response::builder()
.status(StatusCode::OK)
.header(hyper::header::CONTENT_TYPE, "image/x-icon")
.body(full(icon.as_ref()))
.unwrap());
}
_ => {
let is_explicitly_whitelisted_get = method == hyper::Method::GET
&& whitelisted_paths.contains(&destination_path.as_str());
if is_explicitly_whitelisted_get {
log::debug!("Handled whitelisted GET path: {destination_path}");
let mut error_response = Response::builder().status(StatusCode::NOT_FOUND);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full("Not Found")).unwrap());
} else {
log::warn!(
"Unhandled method/path for dynamic routing: {method} {destination_path}"
);
let mut error_response = Response::builder().status(StatusCode::NOT_FOUND);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full("Not Found")).unwrap());
}
}
}
let upstream_url = match target_base_url.clone() {
Some(p) => p,
None => {
log::error!(
"Internal API server routing error: target is None after successful lookup"
);
let mut error_response = Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full("Internal routing error")).unwrap());
}
};
log::info!(
"Proxying request to model server at base URL {upstream_url}, path: {destination_path}"
);
let mut body_bytes_for_proxy = match buffered_body.clone() {
Some(b) => b,
None => {
log::error!(
"Internal logic error: Request reached proxy stage without a buffered body."
);
let mut error_response = Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response
.body(full("Internal server error: unhandled request path"))
.unwrap());
}
};
// Rewrite the chat/completions body into the provider's native request shape.
if let Some(converter) = &upstream_converter {
if let Ok(v) = serde_json::from_slice::<serde_json::Value>(&body_bytes_for_proxy) {
let native = converter.convert_request(&v);
if let Ok(bytes) = serde_json::to_vec(&native) {
body_bytes_for_proxy = Bytes::from(bytes);
}
}
}
// MLX targets carry no router preset, so apply the model's stored sampling
// defaults here for keys the caller omitted (llamacpp uses the preset;
// remote providers are intentionally left untouched).
if let Some(mid) = &mlx_model_id {
let defaults = {
let guard = model_param_defaults.lock().await;
guard.get(mid).cloned()
};
if let Some(defaults) = defaults {
if let Ok(mut v) = serde_json::from_slice::<serde_json::Value>(&body_bytes_for_proxy) {
inject_sampling_defaults(&mut v, &defaults);
if let Ok(bytes) = serde_json::to_vec(&v) {
body_bytes_for_proxy = Bytes::from(bytes);
}
}
}
}
let key_attempts: Vec<Option<String>> = if session_api_keys.is_empty() {
vec![None]
} else {
session_api_keys.iter().cloned().map(Some).collect()
};
// For Anthropic /messages, we need to track if we should transform the response
let destination_path = path.clone();
for (key_idx, key_opt) in key_attempts.iter().enumerate() {
let mut outbound_req = client.request(method.clone(), upstream_url.clone());
// Body is re-buffered/rewritten, so a stale inbound Content-Length would
// mismatch the bytes we send and stall the upstream; reqwest re-derives it.
for (name, value) in headers.iter() {
if name != hyper::header::HOST
&& name != hyper::header::AUTHORIZATION
&& name != hyper::header::CONTENT_LENGTH
&& name != hyper::header::TRANSFER_ENCODING
{
outbound_req = outbound_req.header(name, value);
}
}
if let Some(key) = key_opt {
// The converter decides the auth scheme (Google uses x-goog-api-key).
let (auth_name, auth_value) = match &upstream_converter {
Some(conv) => conv.auth_header(key),
None => ("authorization", format!("Bearer {key}")),
};
outbound_req = outbound_req.header(auth_name, auth_value);
if let Some(conv) = &upstream_converter {
for (name, value) in conv.credential_headers(key) {
outbound_req = outbound_req.header(name, value);
}
}
} else {
log::debug!("No session API key for this attempt");
}
// Fixed headers the native API requires (Anthropic: anthropic-version).
if let Some(conv) = &upstream_converter {
for (name, value) in conv.extra_headers() {
outbound_req = outbound_req.header(name, value);
}
}
let outbound_req_with_body = outbound_req.body(body_bytes_for_proxy.clone());
match outbound_req_with_body.send().await {
Ok(response) => {
let status = response.status();
let is_error = !status.is_success();
if is_error
&& http_status_indicates_api_key_retry(status)
&& key_idx + 1 < key_attempts.len()
{
let _ = response.text().await;
log::warn!("Upstream {status} for API key index {key_idx}, trying next key");
continue;
}
// For Anthropic /messages requests with errors, try /chat/completions
if is_error && is_anthropic_messages {
log::warn!("Request failed for /messages with status {status}, trying /chat/completions...");
// Read the error body to return to client if fallback fails
let error_body = response
.text()
.await
.unwrap_or_else(|e| format!("Failed to read error body: {}", e));
// Clone what we need for the fallback request
let fallback_url = target_base_url.clone().map(|url| {
url.trim_end_matches("/messages")
.trim_end_matches('/')
.to_string()
});
let fallback_api_key = key_opt.clone();
let fallback_body = Some(body_bytes_for_proxy.clone());
// Transform body to OpenAI format for fallback
if let Some((url, openai_body)) = fallback_url.zip(fallback_body).and_then(|(url, body)| {
let json_body = serde_json::from_slice::<serde_json::Value>(&body).ok()?;
match transform_anthropic_to_openai(&json_body) {
Some(transformed) => Some((url, transformed)),
None => {
log::error!("transform_anthropic_to_openai returned None for body: {json_body}");
None
}
}
}) {
let chat_url = format!("{}/chat/completions", url);
log::info!("Fallback to chat completions: {chat_url}");
// Create a fresh client for the fallback to avoid connection pool issues
let fallback_client = Client::builder()
.build()
.expect("Failed to create fallback client");
let mut fallback_req = fallback_client.post(&chat_url);
// Ensure Content-Type is set and prevent compression
fallback_req = fallback_req.header("Content-Type", "application/json");
fallback_req = fallback_req.header("Accept-Encoding", "identity");
for (name, value) in headers.iter() {
if name != hyper::header::HOST
&& name != hyper::header::AUTHORIZATION
&& name != "content-type"
&& name != hyper::header::CONTENT_LENGTH
&& name != hyper::header::ACCEPT_ENCODING
{
fallback_req = fallback_req.header(name, value);
}
}
if let Some(key) = fallback_api_key {
fallback_req = fallback_req.header("Authorization", format!("Bearer {key}"));
}
let fallback_body_str = openai_body.to_string();
let fallback_response = fallback_req.body(fallback_body_str).send().await;
if let Ok(res) = fallback_response {
let fallback_status = res.status();
if !fallback_status.is_success() {
// Return fallback error to client
let fallback_error = res.text().await.unwrap_or_else(|e| format!("Failed to read error: {}", e));
// Return the error to client
let mut error_response = Response::builder().status(fallback_status);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response
.body(full(fallback_error))
.unwrap());
}
let mut builder = Response::builder().status(fallback_status);
for (name, value) in res.headers() {
if !is_cors_header(name.as_str()) && name != hyper::header::CONTENT_LENGTH {
builder = builder.header(name, value);
}
}
builder = add_cors_headers_with_host_and_origin(
builder,
&host_header,
&origin_header,
&config.trusted_hosts,
);
let is_streaming = openai_body
.get("stream")
.and_then(|s| s.as_bool())
.unwrap_or(false);
let (sender, body) = body_channel();
let dest_path = destination_path.clone();
tokio::spawn(async move {
if is_streaming {
let stream = res.bytes_stream();
transform_and_forward_stream(stream, sender, &dest_path).await;
} else {
let response_body = res.bytes().await;
forward_non_streaming(
response_body,
sender,
&dest_path,
)
.await;
}
});
return Ok(builder.body(body).unwrap());
} else if let Err(ref err) = fallback_response {
log::error!("Chat completions fallback failed: {}", err);
}
}
// If fallback failed or wasn't attempted, return error to client
let mut error_response = Response::builder().status(status);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full(error_body)).unwrap());
} else if is_error {
// Non-/messages error - return error response with body
let error_body = response
.text()
.await
.unwrap_or_else(|e| format!("Failed to read error body: {}", e));
let mut error_response = Response::builder().status(status);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full(error_body)).unwrap());
}
// Success case - stream the response
let mut builder = Response::builder().status(status);
for (name, value) in response.headers() {
if !is_cors_header(name.as_str()) && name != hyper::header::CONTENT_LENGTH {
builder = builder.header(name, value);
}
}
builder = add_cors_headers_with_host_and_origin(
builder,
&host_header,
&origin_header,
&config.trusted_hosts,
);
// When the provider fronts a non-chat/completions API, translate the
// response back to chat shape; otherwise forward bytes verbatim.
if let Some(converter) = upstream_converter.take() {
let is_sse = response
.headers()
.get(hyper::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.map(|ct| ct.contains("event-stream"))
.unwrap_or(false);
let (sender, body) = body_channel();
tokio::spawn(async move {
if is_sse {
forward_converted_stream(response.bytes_stream(), sender, converter)
.await;
} else {
forward_converted_non_streaming(response.bytes().await, sender, converter)
.await;
}
});
return Ok(builder.body(body).unwrap());
}
let mut stream = response.bytes_stream();
let (mut sender, body) = body_channel();
tokio::spawn(async move {
// Regular passthrough - when /messages succeeds directly,
// the response is already in the correct format
while let Some(chunk_result) = stream.next().await {
match chunk_result {
Ok(chunk) => {
if sender.send_data(chunk).await.is_err() {
log::debug!("Client disconnected during streaming");
break;
}
}
Err(e) => {
log::error!("Stream error: {e}");
break;
}
}
}
log::debug!("Streaming complete to client");
});
return Ok(builder.body(body).unwrap());
}
Err(e) => {
let error_msg = format!("Proxy request to model failed: {e}");
log::error!("{error_msg}");
let mut error_response = Response::builder().status(StatusCode::BAD_GATEWAY);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
return Ok(error_response.body(full(error_msg)).unwrap());
}
}
}
log::error!("Internal error: proxy key loop exited without a response");
let mut error_response = Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR);
error_response = add_cors_headers_with_host_and_origin(
error_response,
&host_header,
&origin_header,
&config.trusted_hosts,
);
Ok(error_response.body(full("Internal proxy error")).unwrap())
}
/// True when this bind exposes the API to the network with no authentication:
/// a non-loopback host and an empty API key. Every loopback address is safe
/// (127.0.0.0/8, ::1, "localhost"): only this machine can reach it.
fn is_insecure_public_bind(host: &str, api_key: &str) -> bool {
let is_loopback = host == "localhost"
|| host
.trim_matches(['[', ']'])
.parse::<std::net::IpAddr>()
.is_ok_and(|ip| ip.is_loopback());
!is_loopback && api_key.is_empty()
}
/// Convert a TCP bind failure into a user-facing message. Address-in-use
/// (Windows error 10048 / WSAEADDRINUSE, Unix EADDRINUSE) almost always means
/// a leftover Jan process or another service still owns the port after a
/// restart, so name the port and the remedy instead of surfacing a bare OS
/// errno. Any other error is passed through unchanged.
fn map_bind_error(
addr: SocketAddr,
err: std::io::Error,
) -> Box<dyn std::error::Error + Send + Sync> {
if err.kind() == std::io::ErrorKind::AddrInUse {
let msg = format!(
"Port {port} ({addr}) is already in use. A previous Jan process may still be \
running or another application may be using the port. Close the leftover \
process and try again, or pick a different port in Settings > Local API Server.",
port = addr.port()
);
return msg.into();
}
Box::new(err)
}
pub(crate) fn add_cors_headers_with_host_and_origin(
builder: hyper::http::response::Builder,
host: &str,
origin: &str,
trusted_hosts: &[Vec<String>],
) -> hyper::http::response::Builder {
let mut builder = builder;
// Requests from an origin `origin_allowed` refuses never reach a handler,
// so this only decides whether to reflect an already-admitted origin.
let origin_trusted = !origin.is_empty()
&& is_trusted_origin(
origin,
if is_valid_host(host, trusted_hosts) { host } else { "" },
trusted_hosts,
);
builder = builder
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
.header("Access-Control-Allow-Headers", "Authorization, Content-Type, Host, Accept, Accept-Language, Cache-Control, Connection, DNT, If-Modified-Since, Keep-Alive, Origin, User-Agent, X-Requested-With, X-CSRF-Token, X-Forwarded-For, X-Forwarded-Proto, X-Forwarded-Host, authorization, content-type, x-api-key")
.header("Vary", "Origin");
if origin_trusted {
builder = builder
.header("Access-Control-Allow-Origin", origin)
.header("Access-Control-Allow-Credentials", "true");
} else {
log::warn!(
"CORS: Origin '{}' is not trusted, not reflecting origin",
origin
);
}
builder
}
pub async fn is_server_running(server_handle: Arc<Mutex<Option<ServerHandle>>>) -> bool {
let handle_guard = server_handle.lock().await;
handle_guard.is_some()
}
#[allow(clippy::too_many_arguments)]
pub async fn start_server(
server_handle: Arc<Mutex<Option<ServerHandle>>>,
llama_state: Arc<LlamacppState>,
mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,
host: String,
port: u16,
prefix: String,
proxy_api_key: String,
trusted_hosts: Vec<Vec<String>>,
proxy_timeout: u64,
provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,
model_param_defaults: Arc<Mutex<HashMap<String, serde_json::Value>>>,
mcp_servers: SharedMcpServers,
mcp_settings: Arc<Mutex<McpSettings>>,
jan_data_folder: String,
enable_server_tool_execution: bool,
cors_enabled: bool,
) -> Result<u16, Box<dyn std::error::Error + Send + Sync>> {
start_server_internal(
server_handle,
llama_state,
mlx_sessions,
host,
port,
prefix,
proxy_api_key,
trusted_hosts,
proxy_timeout,
provider_configs,
model_param_defaults,
mcp_servers,
mcp_settings,
jan_data_folder,
enable_server_tool_execution,
cors_enabled,
)
.await
}
#[allow(clippy::too_many_arguments)]
async fn start_server_internal(
server_handle: Arc<Mutex<Option<ServerHandle>>>,
llama_state: Arc<LlamacppState>,
mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,
host: String,
port: u16,
prefix: String,
proxy_api_key: String,
trusted_hosts: Vec<Vec<String>>,
proxy_timeout: u64,
provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,
model_param_defaults: Arc<Mutex<HashMap<String, serde_json::Value>>>,
mcp_servers: SharedMcpServers,
mcp_settings: Arc<Mutex<McpSettings>>,
jan_data_folder: String,
enable_server_tool_execution: bool,
cors_enabled: bool,
) -> Result<u16, Box<dyn std::error::Error + Send + Sync>> {
let mut handle_guard = server_handle.lock().await;
if handle_guard.is_some() {
return Err("Server is already running".into());
}
let addr: SocketAddr = format!("{host}:{port}")
.parse()
.map_err(|e| format!("Invalid address: {e}"))?;
// Binding to 0.0.0.0 exposes the server on the LAN, but that must NOT discard
// the user's Trusted Hosts allowlist. LAN clients connect via http://192.168.x.x:port
// and send that literal IP as the Host header; is_valid_host now accepts loopback
// and private-range IP literals, which is safe against DNS rebinding (that sends an
// attacker *hostname*, not an IP). Hostnames still require an explicit allowlist entry.
// Security: a non-loopback bind exposes the OpenAI-compatible API on the
// network, and with no API key any reachable host could call it
// unauthenticated (inference, model enumeration and, when enabled, MCP tool
// execution). Refuse before binding rather than serve it open.
if is_insecure_public_bind(&host, &proxy_api_key) {
return Err(format!(
"The API server is set to listen on {host}, which other devices on the network \
can reach, but no API key is set. Set an API key in Settings > Local API Server, \
or switch the host to 127.0.0.1."
)
.into());
}
let config = ProxyConfig {
prefix,
proxy_api_key,
trusted_hosts,
host: host.clone(),
port,
enable_server_tool_execution,
cors_enabled,
};
let client = Client::builder()
.timeout(std::time::Duration::from_secs(proxy_timeout))
.pool_max_idle_per_host(10)
.pool_idle_timeout(std::time::Duration::from_secs(30))
.build()?;
let listener = match tokio::net::TcpListener::bind(addr).await {
Ok(l) => l,
Err(e) => {
log::error!("Failed to bind to {addr}: {e}");
return Err(map_bind_error(addr, e));
}
};
log::info!("Jan API server started on http://{addr}");
let server_task = tokio::spawn(async move {
loop {
let (stream, _) = match listener.accept().await {
Ok(c) => c,
Err(e) => {
log::error!("Accept error: {e}");
continue;
}
};
let io = TokioIo::new(stream);
let client = client.clone();
let config = config.clone();
let llama_state = llama_state.clone();
let mlx_sessions = mlx_sessions.clone();
let provider_configs = provider_configs.clone();
let model_param_defaults = model_param_defaults.clone();
let mcp_servers = mcp_servers.clone();
let mcp_settings = mcp_settings.clone();
let jan_data_folder = jan_data_folder.clone();
let svc = service_fn(move |req| {
let client = client.clone();
let config = config.clone();
let llama_state = llama_state.clone();
let mlx_sessions = mlx_sessions.clone();
let provider_configs = provider_configs.clone();
let model_param_defaults = model_param_defaults.clone();
let mcp_servers = mcp_servers.clone();
let mcp_settings = mcp_settings.clone();
let jan_data_folder = jan_data_folder.clone();
async move {
// Taken before the request resolves the engine's address and
// kept until its response body is finished, so a device-change
// restart cannot stop the worker between the two. A request
// arriving mid-restart waits here and is then served by the
// new worker instead of failing with "no models are running".
let lease = llama_state.lease().await;
let response = proxy_request(
req,
client,
config,
llama_state,
mlx_sessions,
provider_configs,
model_param_defaults,
mcp_servers,
mcp_settings,
jan_data_folder,
)
.await?;
Ok::<_, hyper::Error>(response.map(|body| hold_lease(body, lease)))
}
});
tokio::spawn(async move {
if let Err(e) = http1::Builder::new().serve_connection(io, svc).await {
log::debug!("Error serving connection: {e}");
}
});
}
#[allow(unreachable_code)]
Ok::<(), Box<dyn std::error::Error + Send + Sync>>(())
});
*handle_guard = Some(server_task);
let actual_port = addr.port();
log::info!("Jan API server started successfully on port {actual_port}");
Ok(actual_port)
}
pub async fn stop_server(
server_handle: Arc<Mutex<Option<ServerHandle>>>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let mut handle_guard = server_handle.lock().await;
if let Some(handle) = handle_guard.take() {
handle.abort();
*handle_guard = None;
log::info!("Jan API server stopped");
} else {
log::debug!("Server was not running");
}
Ok(())
}
/// Helper to format an Anthropic SSE event with proper event type and delimiters
pub(crate) fn sse_event(data: &serde_json::Value) -> Bytes {
let event_type = data
.get("type")
.and_then(|t| t.as_str())
.unwrap_or("message");
Bytes::from(format!("event: {event_type}\ndata: {data}\n\n"))
}
/// Transform and forward streaming OpenAI response as Anthropic /messages chunks.
/// Handles both text content and tool_calls streaming.
/// Stream a native upstream response through an [`UpstreamConverter`], emitting
/// chat/completions SSE chunks. Uses [`SseAccumulator`] so events split across
/// network chunks are reassembled before translation.
async fn forward_converted_stream<S>(
mut stream: S,
mut sender: BodySender,
converter: Box<dyn UpstreamConverter>,
) where
S: futures_util::Stream<Item = Result<Bytes, reqwest::Error>> + Unpin,
{
let mut acc = SseAccumulator::new();
let mut state = StreamState::default();
'outer: while let Some(chunk_result) = stream.next().await {
match chunk_result {
Ok(chunk) => {
let text = String::from_utf8_lossy(&chunk);
for event in acc.push(&text) {
for payload in converter.convert_stream_event(&event, &mut state) {
let framed = Bytes::from(format!("data: {payload}\n\n"));
if sender.send_data(framed).await.is_err() {
break 'outer;
}
}
}
}
Err(e) => {
log::error!("Converter stream error: {e}");
break;
}
}
}
if let Some(event) = acc.finish() {
for payload in converter.convert_stream_event(&event, &mut state) {
let framed = Bytes::from(format!("data: {payload}\n\n"));
if sender.send_data(framed).await.is_err() {
return;
}
}
}
}
/// Translate a non-streaming native upstream response into a chat.completion
/// object and forward it as a single body frame.
async fn forward_converted_non_streaming(
body: Result<Bytes, reqwest::Error>,
mut sender: BodySender,
converter: Box<dyn UpstreamConverter>,
) {
match body {
Ok(bytes) => {
let out = match serde_json::from_slice::<serde_json::Value>(&bytes) {
Ok(v) => serde_json::to_vec(&converter.convert_response(&v))
.unwrap_or_else(|_| bytes.to_vec()),
Err(_) => bytes.to_vec(),
};
let _ = sender.send_data(Bytes::from(out)).await;
}
Err(e) => log::error!("Converter non-streaming error: {e}"),
}
}
async fn transform_and_forward_stream<S>(
mut stream: S,
mut sender: BodySender,
_destination_path: &str,
) where
S: futures_util::Stream<Item = Result<Bytes, reqwest::Error>> + Unpin,
{
let mut is_first = true;
let mut accumulated_content = String::new();
// Track active Anthropic content blocks
let mut text_block_index: Option<usize> = None;
let mut tool_blocks: HashMap<usize, usize> = HashMap::new(); // OAI tool index -> Anthropic block index
let mut next_block_index: usize = 0;
while let Some(chunk_result) = stream.next().await {
match chunk_result {
Ok(chunk) => {
let chunk_str = String::from_utf8_lossy(&chunk);
for line in chunk_str.lines() {
if !line.starts_with("data:") {
continue;
}
let data = line.trim_start_matches("data:").trim();
if data == "[DONE]" {
// Close any remaining open blocks
if let Some(idx) = text_block_index.take() {
let stop =
serde_json::json!({"type": "content_block_stop", "index": idx});
if sender.send_data(sse_event(&stop)).await.is_err() {
return;
}
}
let mut tool_indices: Vec<usize> = tool_blocks.values().copied().collect();
tool_indices.sort();
for idx in tool_indices {
let stop =
serde_json::json!({"type": "content_block_stop", "index": idx});
if sender.send_data(sse_event(&stop)).await.is_err() {
return;
}
}
let stop_reason = if tool_blocks.is_empty() {
"end_turn"
} else {
"tool_use"
};
let output_tokens = accumulated_content.split_whitespace().count() as u64;
let delta_event = serde_json::json!({
"type": "message_delta",
"delta": {
"stop_reason": stop_reason,
"stop_sequence": serde_json::Value::Null
},
"usage": { "output_tokens": output_tokens }
});
if sender.send_data(sse_event(&delta_event)).await.is_err() {
return;
}
let final_stop = serde_json::json!({"type": "message_stop"});
if sender.send_data(sse_event(&final_stop)).await.is_err() {
return;
}
log::debug!("Sent Anthropic final events");
return;
}
let json_chunk = match serde_json::from_str::<serde_json::Value>(data) {
Ok(v) => v,
Err(_) => continue,
};
let choice = json_chunk
.get("choices")
.and_then(|c| c.as_array())
.and_then(|c| c.first());
let delta = match choice.and_then(|c| c.get("delta")) {
Some(d) => d,
None => continue,
};
let finish_reason = choice.and_then(|c| c.get("finish_reason"));
let has_finish = finish_reason.is_some() && !finish_reason.unwrap().is_null();
// First chunk: send message_start
if is_first {
let role = delta
.get("role")
.and_then(|r| r.as_str())
.unwrap_or("assistant");
let message_id = json_chunk
.get("id")
.unwrap_or(&serde_json::json!(""))
.clone();
let model = json_chunk
.get("model")
.unwrap_or(&serde_json::json!(""))
.clone();
let start_event = serde_json::json!({
"type": "message_start",
"message": {
"id": message_id,
"type": "message",
"role": role,
"content": [],
"model": model,
"stop_reason": serde_json::Value::Null,
"stop_sequence": serde_json::Value::Null,
"usage": { "input_tokens": 0, "output_tokens": 0 }
}
});
if sender.send_data(sse_event(&start_event)).await.is_err() {
return;
}
is_first = false;
}
// Handle text content
if let Some(text) =
delta
.get("content")
.and_then(|c| if c.is_null() { None } else { c.as_str() })
{
if !text.is_empty() {
// Open text block if needed
if text_block_index.is_none() {
let idx = next_block_index;
next_block_index += 1;
text_block_index = Some(idx);
let block_start = serde_json::json!({
"type": "content_block_start",
"index": idx,
"content_block": { "type": "text", "text": "" }
});
if sender.send_data(sse_event(&block_start)).await.is_err() {
return;
}
}
accumulated_content.push_str(text);
let delta_event = serde_json::json!({
"type": "content_block_delta",
"index": text_block_index.unwrap(),
"delta": { "type": "text_delta", "text": text }
});
if sender.send_data(sse_event(&delta_event)).await.is_err() {
return;
}
}
}
// Handle tool calls
if let Some(tool_calls) = delta.get("tool_calls").and_then(|tc| tc.as_array()) {
// Close text block before tool blocks
if let Some(idx) = text_block_index.take() {
let stop = serde_json::json!(
{"type": "content_block_stop", "index": idx}
);
if sender.send_data(sse_event(&stop)).await.is_err() {
return;
}
}
for tc in tool_calls {
let tc_index =
tc.get("index").and_then(|i| i.as_u64()).unwrap_or(0) as usize;
// New tool call (has id + function.name)
if let Some(id) = tc.get("id").and_then(|v| v.as_str()) {
let name = tc
.get("function")
.and_then(|f| f.get("name"))
.and_then(|n| n.as_str())
.unwrap_or("");
let idx = next_block_index;
next_block_index += 1;
tool_blocks.insert(tc_index, idx);
let block_start = serde_json::json!({
"type": "content_block_start",
"index": idx,
"content_block": {
"type": "tool_use",
"id": id,
"name": name,
"input": {}
}
});
if sender.send_data(sse_event(&block_start)).await.is_err() {
return;
}
}
// Argument delta
if let Some(args) = tc
.get("function")
.and_then(|f| f.get("arguments"))
.and_then(|a| a.as_str())
{
if !args.is_empty() {
if let Some(&idx) = tool_blocks.get(&tc_index) {
let delta_event = serde_json::json!({
"type": "content_block_delta",
"index": idx,
"delta": {
"type": "input_json_delta",
"partial_json": args
}
});
if sender.send_data(sse_event(&delta_event)).await.is_err()
{
return;
}
}
}
}
}
}
// Handle finish
if has_finish {
// Close text block
if let Some(idx) = text_block_index.take() {
let stop = serde_json::json!(
{"type": "content_block_stop", "index": idx}
);
if sender.send_data(sse_event(&stop)).await.is_err() {
return;
}
}
// Close all tool blocks
let mut tool_indices: Vec<usize> = tool_blocks.values().copied().collect();
tool_indices.sort();
for idx in tool_indices {
let stop = serde_json::json!(
{"type": "content_block_stop", "index": idx}
);
if sender.send_data(sse_event(&stop)).await.is_err() {
return;
}
}
let reason = finish_reason
.and_then(|fr| fr.as_str())
.unwrap_or("end_turn");
let stop_reason = match reason {
"stop" => "end_turn",
"length" => "max_tokens",
"tool_calls" => "tool_use",
_ => reason,
};
let output_tokens = accumulated_content.split_whitespace().count() as u64;
let delta_event = serde_json::json!({
"type": "message_delta",
"delta": {
"stop_reason": stop_reason,
"stop_sequence": serde_json::Value::Null
},
"usage": { "output_tokens": output_tokens }
});
if sender.send_data(sse_event(&delta_event)).await.is_err() {
return;
}
let final_stop = serde_json::json!({"type": "message_stop"});
if sender.send_data(sse_event(&final_stop)).await.is_err() {
return;
}
return;
}
}
}
Err(e) => {
log::error!("Stream error: {e}");
break;
}
}
}
log::debug!("Streaming complete (Anthropic format)");
}
/// Forward non-streaming OpenAI response as Anthropic /messages response
async fn forward_non_streaming(
response_body: Result<Bytes, reqwest::Error>,
mut sender: BodySender,
destination_path: &str,
) {
let bytes = match response_body {
Ok(bytes) => bytes,
Err(e) => {
log::error!("Failed to get response body: {e}");
return;
}
};
if let Ok(json_response) = serde_json::from_slice::<serde_json::Value>(&bytes) {
if destination_path == "/messages" {
// Transform to Anthropic format
let anthropic_response = transform_openai_response_to_anthropic(&json_response);
if sender
.send_data(Bytes::from(anthropic_response.to_string()))
.await
.is_err()
{
log::debug!("Client disconnected");
}
} else {
// Pass through as-is
if sender.send_data(bytes).await.is_err() {
log::debug!("Client disconnected");
}
}
} else {
// Pass through raw response
if sender.send_data(bytes).await.is_err() {
log::debug!("Client disconnected");
}
}
}
#[cfg(test)]
mod tests {
use super::{is_insecure_public_bind, map_bind_error};
use std::net::SocketAddr;
#[test]
fn loopback_hosts_need_no_key() {
for host in ["127.0.0.1", "127.0.0.2", "localhost", "::1", "[::1]"] {
assert!(!is_insecure_public_bind(host, ""), "{host} should be safe");
assert!(!is_insecure_public_bind(host, "secret"));
}
}
#[test]
fn public_bind_without_key_is_insecure() {
for host in ["0.0.0.0", "192.168.1.10", "::", "10.0.0.5"] {
assert!(is_insecure_public_bind(host, ""), "{host} should need a key");
}
}
#[test]
fn public_bind_with_key_is_ok() {
assert!(!is_insecure_public_bind("0.0.0.0", "secret"));
assert!(!is_insecure_public_bind("192.168.1.10", "secret"));
}
#[test]
fn addr_in_use_maps_to_actionable_message() {
let addr: SocketAddr = "127.0.0.1:1337".parse().unwrap();
let err = std::io::Error::new(std::io::ErrorKind::AddrInUse, "Address already in use");
let msg = map_bind_error(addr, err).to_string();
assert!(msg.contains("1337"), "should name the port: {msg}");
assert!(
msg.contains("already in use") && msg.contains("process"),
"should explain the leftover-process remedy: {msg}"
);
}
#[test]
fn non_addr_in_use_error_passes_through() {
let addr: SocketAddr = "127.0.0.1:1337".parse().unwrap();
let err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
let msg = map_bind_error(addr, err).to_string();
assert!(msg.contains("denied"), "should keep the original error: {msg}");
}
}