Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): send provider headers, User-Agent and X-Session-Id on inference
locnguyen1986bf49f25ed789
diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rsindex 41c9ba4f1..40f83b08e 100644--- a/src-tauri/jan-cli/src/main.rs+++ b/src-tauri/jan-cli/src/main.rs@@ -710,6 +710,12 @@ async fn main() {})).init();+ // Inference requests name this client, so a gateway can tell Jan Agent's+ // traffic from the desktop's, which sends none. Set before anything sends.+ app_lib::core::agent::request_headers::set_user_agent(app_lib::core::cli::telemetry::user_agent(+ app_lib::core::cli::updater::build_version(),+ ));+// Inject the logo at runtime so we can use ANSI styling.let logo = make_logo();let matches = Cli::command()diff --git a/src-tauri/src/core/agent/genai_bridge.rs b/src-tauri/src/core/agent/genai_bridge.rsindex 29555c5ae..708899890 100644--- a/src-tauri/src/core/agent/genai_bridge.rs+++ b/src-tauri/src/core/agent/genai_bridge.rs@@ -99,7 +99,7 @@ fn client_for(request_url: &str,api_key: Option<&str>,adapter: AdapterKind,- client_request_id: Option<&str>,+ extra_headers: &[(String, String)],) -> Client {let endpoint = Endpoint::from_owned(endpoint_base.to_string());@@ -122,16 +122,13 @@ fn client_for(if let Some(key) = api_key.filter(|k| !k.is_empty()) {headers.push(("Authorization".to_string(), format!("Bearer {key}")));}- // The correlation id has to go in here rather than through+ // The provider's custom headers and Jan's own (User-Agent, correlation and+ // session ids) have to go in here rather than through// `ChatOptions::with_extra_headers`: genai overwrites the whole header map// with this override's when `RequestOverride` is set, which it always is on- // this path, so extra headers set anywhere else are silently dropped.- if let Some(id) = client_request_id.filter(|id| !id.is_empty()) {- headers.push((- super::correlation::CLIENT_REQUEST_ID_HEADER.to_string(),- id.to_string(),- ));- }+ // this path, so extra headers set anywhere else are silently dropped. genai+ // sets no User-Agent of its own, so this list is exactly what is sent.+ super::request_headers::merge_onto(&mut headers, extra_headers);let auth = AuthData::RequestOverride {url: request_url.to_string(),headers: genai::Headers::from(headers),@@ -727,7 +724,7 @@ pub(crate) async fn stream_chat_completions(api_type: Option<&str>,body: &serde_json::Value,events: &mpsc::UnboundedSender<StreamEvent>,- client_request_id: Option<&str>,+ extra_headers: &[(String, String)],) -> Result<serde_json::Value, String> {let (model, chat_req) = chat_request_from_body(body)?;let options = options_from_body(body);@@ -750,7 +747,7 @@ pub(crate) async fn stream_chat_completions(upstream_url,*key,adapter,- client_request_id,+ extra_headers,);for attempt in 0..MAX_ATTEMPTS {@@ -1461,7 +1458,7 @@ mod tests {async fn run(url: &str, keys: &[String], events: &mpsc::UnboundedSender<StreamEvent>)-> Result<serde_json::Value, String> {- stream_chat_completions(&build_http_client(), url, keys, None, &body(), events, None).await+ stream_chat_completions(&build_http_client(), url, keys, None, &body(), events, &[]).await}#[tokio::test]diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 39e129516..a48e6d5e1 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -415,6 +415,9 @@ async fn request_identity(}}+/// No default headers on purpose, `User-Agent` included: that one rides each+/// request's header list ([`crate::core::agent::request_headers`]), which both+/// send paths share, so the two cannot drift apart.fn converter_http_client() -> reqwest::Client {static CLIENT: LazyLock<reqwest::Client> = LazyLock::new(reqwest::Client::new);CLIENT.clone()@@ -432,13 +435,30 @@ impl ModelInvoker for HttpModelInvoker {// the body must carry the bare model id - providers like OpenCode GO// reject a provider-qualified id with "model not supported".let mut normalized = request.clone();+ // The serving provider's custom headers, looked up through the same+ // routing order the upstream was resolved by, so every invoker -- the+ // turn, compaction, `/goal`, side calls, subagents -- sends the headers+ // of the provider it is actually talking to.+ let mut custom_headers = Vec::new();if let Some(model) = normalized.get("model").and_then(|m| m.as_str()) {let pc = self.provider_configs.lock().await;+ if let Some(config) = crate::core::agent::upstream::pick_provider_for_model(model, &pc)+ .and_then(|provider| pc.get(&provider))+ {+ custom_headers = config.custom_headers.clone();+ }let bare = crate::core::agent::upstream::strip_provider_prefix(model, &pc);if bare != model {normalized["model"] = serde_json::json!(bare);}}+ let extra_headers = crate::core::agent::request_headers::extras(+ &custom_headers,+ crate::core::agent::request_headers::owned(+ crate::core::agent::request_headers::user_agent(),+ self.client_request_id.as_deref(),+ ),+ );// Emitted before the request goes out, so a harness that records// provenance sees the request even when the call then fails. It goes to// the run's stream rather than to `events`: a side call passes a private@@ -460,7 +480,7 @@ impl ModelInvoker for HttpModelInvoker {converter.as_ref(),&normalized,events,- self.client_request_id.as_deref(),+ &extra_headers,).await} else {@@ -472,7 +492,7 @@ impl ModelInvoker for HttpModelInvoker {None,&normalized,events,- self.client_request_id.as_deref(),+ &extra_headers,).await}@@ -5209,6 +5229,101 @@ mod tests {);}+ /// The invoker sends the custom headers of the provider that serves the+ /// request's model -- looked up the way the upstream was resolved, so a+ /// `provider/model` id finds its provider -- plus Jan's session headers, and+ /// never a second `Authorization`. This is also the desktop's path: the+ /// headers it registers for a provider now reach the wire.+ #[tokio::test]+ async fn the_serving_providers_headers_reach_the_default_path() {+ use std::io::{BufRead, BufReader, Write};++ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let url = format!(+ "http://{}/v1/chat/completions",+ listener.local_addr().unwrap()+ );+ let (seen_tx, seen_rx) = std::sync::mpsc::channel::<String>();+ std::thread::spawn(move || {+ let Ok((mut stream, _)) = listener.accept() else { return };+ let mut reader = BufReader::new(stream.try_clone().unwrap());+ let mut headers = String::new();+ loop {+ let mut line = String::new();+ if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {+ break;+ }+ headers.push_str(&line);+ }+ let _ = seen_tx.send(headers);+ let answer = concat!(+ "data: {\"id\":\"s\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"m\",",+ "\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\n",+ "data: [DONE]\n\n",+ );+ let _ = write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{answer}", answer.len());+ });++ let mut configs = HashMap::new();+ configs.insert(+ "gateway".to_string(),+ ProviderConfig {+ provider: "gateway".into(),+ base_url: Some(url.trim_end_matches("/chat/completions").to_string()),+ api_key: Some("real-key".into()),+ api_keys: vec!["real-key".into()],+ custom_headers: vec![+ crate::core::state::ProviderCustomHeader {+ header: "X-Client-Name".into(),+ value: "jan-agent".into(),+ },+ crate::core::state::ProviderCustomHeader {+ header: "authorization".into(),+ value: "Bearer smuggled".into(),+ },+ ],+ ..Default::default()+ },+ );+ let (run, _run_events) = mpsc::unbounded_channel();+ let invoker = HttpModelInvoker {+ client: crate::core::agent::upstream::agent_http_client(),+ upstream_url: url,+ api_keys: vec!["real-key".into()],+ provider_configs: Arc::new(Mutex::new(configs)),+ converter: None,+ converter_client: converter_http_client(),+ client_request_id: crate::core::agent::correlation::session_request_id(Some(+ "sess-9",+ )),+ session_id: Some("sess-9".to_string()),+ provenance: RequestIdentityOwned::default(),+ provenance_events: Some(run),+ };+ let (tx, _rx) = mpsc::unbounded_channel();+ invoker+ .invoke(+ &json!({"model":"gateway/m","messages":[{"role":"user","content":"hi"}]}),+ &tx,+ )+ .await+ .expect("the stub answers");++ let seen = seen_rx+ .recv_timeout(std::time::Duration::from_secs(10))+ .expect("the request reached the stub")+ .to_ascii_lowercase();+ assert!(seen.contains("\r\nx-client-name: jan-agent\r\n"), "{seen}");+ assert!(seen.contains("\r\nx-client-request-id: jan-sess-9\r\n"), "{seen}");+ assert!(seen.contains("\r\nx-session-id: sess-9\r\n"), "{seen}");+ assert_eq!(seen.matches("\r\nauthorization: ").count(), 1, "{seen}");+ assert!(seen.contains("\r\nauthorization: bearer real-key\r\n"), "{seen}");+ assert!(+ !seen.contains("\r\nuser-agent:"),+ "a library build sets no User-Agent; only the jan binary does: {seen}"+ );+ }+#[derive(Default)]struct MockTool {calls: StdMutex<Vec<Vec<serde_json::Value>>>,diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rsindex 2040a88d2..3553dbb15 100644--- a/src-tauri/src/core/agent/mod.rs+++ b/src-tauri/src/core/agent/mod.rs@@ -46,6 +46,7 @@ pub mod project;pub mod prompt;pub mod provenance;pub mod reminder;+pub mod request_headers;pub mod session;pub mod skill_hub;pub mod skills;diff --git a/src-tauri/src/core/agent/request_headers.rs b/src-tauri/src/core/agent/request_headers.rsnew file mode 100644index 000000000..c4a66889e--- /dev/null+++ b/src-tauri/src/core/agent/request_headers.rs@@ -0,0 +1,329 @@+//! The headers an inference request carries beyond its transport's own: the+//! serving provider's configured custom headers, and the ones Jan owns+//! (`User-Agent`, `X-Client-Request-Id`, `X-Session-Id`).+//!+//! Built once per request by the invoker and handed to both send paths -- the+//! `genai` header override and the native converter's request -- so the two+//! cannot disagree about what reaches the wire. Names are compared+//! case-insensitively throughout: `reqwest`'s `RequestBuilder::header` appends+//! rather than replaces, so two spellings of one name would both be sent, and a+//! custom `x-api-key` would become a second credential.+//!+//! Feature-neutral, like [`super::correlation`]: the desktop's agent loop and+//! API-server orchestration send through the same paths, and the custom headers+//! the desktop registers for a provider are honoured here too.++use std::collections::HashSet;+use std::sync::{Mutex, OnceLock};++use crate::core::state::ProviderCustomHeader;++/// Header naming the session a request belongs to: the id the correlation+/// header carries, without its `jan-` prefix, so a gateway can group a session's+/// requests without knowing how the correlation id is derived.+pub const SESSION_ID_HEADER: &str = "X-Session-Id";++/// Names a custom header may never set, lowercase: the transport's own framing,+/// and every credential header either send path writes (the Bearer default and+/// the converters' `x-api-key` / `x-goog-api-key` / `anthropic-version`). A+/// custom value for one of these would either break the stream or send a second+/// credential alongside the real one.+pub const RESERVED: &[&str] = &[+ "authorization",+ "content-type",+ "accept",+ "accept-encoding",+ "x-api-key",+ "x-goog-api-key",+ "anthropic-version",+];++/// Whether `name` is one a custom header may not set.+pub fn is_reserved(name: &str) -> bool {+ let name = name.trim();+ RESERVED.iter().any(|r| r.eq_ignore_ascii_case(name))+}++static USER_AGENT: OnceLock<String> = OnceLock::new();++/// Set the `User-Agent` every inference request carries. Called once, by the+/// binary at startup: the agent loop is compiled into both the CLI and the+/// desktop, and only the binary knows which product it is. The desktop never+/// calls this, so its requests carry no `User-Agent`, exactly as before.+pub fn set_user_agent(value: String) {+ let _ = USER_AGENT.set(value);+}++/// The `User-Agent` set by [`set_user_agent`], if any.+pub fn user_agent() -> Option<&'static str> {+ USER_AGENT.get().map(String::as_str)+}++/// `Jan-Agent/<version> (<os>; <arch>)`, the CLI's product token. "Jan Agent",+/// not "Jan": the desktop's own update checks send `Jan/<version>`, and both+/// share one version number, so the product name is the only thing that tells+/// a gateway which client it is talking to.+pub fn agent_user_agent(version: &str) -> String {+ format!(+ "Jan-Agent/{} ({}; {})",+ version,+ std::env::consts::OS,+ std::env::consts::ARCH+ )+}++/// The headers Jan owns on a request: the `User-Agent` when the binary set one,+/// and the correlation and session ids when the request belongs to a session.+///+/// `X-Session-Id` is derived from the correlation id rather than from the raw+/// session id, so the two always name the same session in the same sanitized+/// form -- one header is the other minus its prefix.+pub fn owned(user_agent: Option<&str>, client_request_id: Option<&str>) -> Vec<(String, String)> {+ let mut out = Vec::new();+ if let Some(ua) = user_agent.filter(|ua| !ua.trim().is_empty()) {+ out.push(("User-Agent".to_string(), ua.to_string()));+ }+ if let Some(id) = client_request_id.filter(|id| !id.is_empty()) {+ out.push((+ super::correlation::CLIENT_REQUEST_ID_HEADER.to_string(),+ id.to_string(),+ ));+ if let Some(session) = id.strip_prefix("jan-").filter(|s| !s.is_empty()) {+ out.push((SESSION_ID_HEADER.to_string(), session.to_string()));+ }+ }+ out+}++/// The extra headers for one request: the provider's custom headers, then the+/// Jan-owned ones, as one list with no name twice.+///+/// A custom header is dropped (with a warning, once per name) when its name is+/// [reserved](RESERVED) or not a valid header, or its value is not a valid+/// header value -- `reqwest` would otherwise fail the whole request at send+/// time. A custom header with the name of a Jan-owned one is dropped silently:+/// Jan's value wins, and saying so on every request would be noise. Two custom+/// headers with one name keep the later, the way a later config layer wins.+pub fn extras(+ custom: &[ProviderCustomHeader],+ owned: Vec<(String, String)>,+) -> Vec<(String, String)> {+ let mut out: Vec<(String, String)> = Vec::new();+ for header in custom {+ let name = header.header.trim();+ let value = header.value.trim();+ if name.is_empty() {+ continue;+ }+ if is_reserved(name) {+ warn_skipped(name, "a reserved header");+ continue;+ }+ if reqwest::header::HeaderName::from_bytes(name.as_bytes()).is_err()+ || reqwest::header::HeaderValue::from_str(value).is_err()+ {+ warn_skipped(name, "not a valid header");+ continue;+ }+ if owned.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)) {+ continue;+ }+ out.retain(|(n, _)| !n.eq_ignore_ascii_case(name));+ out.push((name.to_string(), value.to_string()));+ }+ out.extend(owned);+ out+}++/// Add `extras` to headers a send path already set, skipping any whose name is+/// already there: those are the path's framing and credentials (a converter's+/// `anthropic-beta`, `chatgpt-account-id`, ...), which a custom header must not+/// displace or duplicate.+pub fn merge_onto(base: &mut Vec<(String, String)>, extras: &[(String, String)]) {+ for (name, value) in extras {+ if base.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)) {+ warn_skipped(name, "set by the provider's transport");+ continue;+ }+ base.push((name.clone(), value.clone()));+ }+}++/// Custom header names worth reporting (`jan cli agent status`): the ones that+/// survive the reserved filter, in first-seen order, one per name.+pub fn reportable_names(custom: &[ProviderCustomHeader]) -> Vec<String> {+ let mut names: Vec<String> = Vec::new();+ for header in custom {+ let name = header.header.trim();+ if name.is_empty() || is_reserved(name) {+ continue;+ }+ if !names.iter().any(|n| n.eq_ignore_ascii_case(name)) {+ names.push(name.to_string());+ }+ }+ names+}++/// Warn once per header name: the same configuration is sent on every request,+/// and a warning per request would bury the log. Names only; a header value can+/// carry a credential.+fn warn_skipped(name: &str, why: &str) {+ static WARNED: Mutex<Option<HashSet<String>>> = Mutex::new(None);+ let mut warned = WARNED.lock().unwrap_or_else(|e| e.into_inner());+ if warned+ .get_or_insert_with(HashSet::new)+ .insert(name.to_ascii_lowercase())+ {+ log::warn!("not sending custom header '{name}': {why}");+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn custom(pairs: &[(&str, &str)]) -> Vec<ProviderCustomHeader> {+ pairs+ .iter()+ .map(|(h, v)| ProviderCustomHeader {+ header: (*h).to_string(),+ value: (*v).to_string(),+ })+ .collect()+ }++ fn names(headers: &[(String, String)]) -> Vec<String> {+ headers+ .iter()+ .map(|(n, _)| n.to_ascii_lowercase())+ .collect()+ }++ #[test]+ fn the_session_header_is_the_correlation_id_without_its_prefix() {+ let owned = owned(None, Some("jan-3f7a-91c2"));+ assert_eq!(+ owned,+ vec![+ (+ "X-Client-Request-Id".to_string(),+ "jan-3f7a-91c2".to_string()+ ),+ ("X-Session-Id".to_string(), "3f7a-91c2".to_string()),+ ]+ );+ assert!(super::owned(None, None).is_empty(), "no session, no ids");+ }++ /// The desktop never sets one, so it keeps sending none; the CLI's is the+ /// product token a gateway labels the traffic by.+ #[test]+ fn the_user_agent_is_sent_only_when_the_binary_set_one() {+ assert!(!names(&owned(None, Some("jan-s"))).contains(&"user-agent".to_string()));+ assert!(+ user_agent().is_none(),+ "nothing in the library sets a User-Agent; only the jan binary does"+ );+ let ua = agent_user_agent("0.8.5-1");+ assert!(ua.starts_with("Jan-Agent/0.8.5-1 ("), "{ua}");+ assert_eq!(owned(Some(&ua), None), vec![("User-Agent".to_string(), ua)]);+ }++ #[test]+ fn reserved_and_invalid_custom_headers_are_dropped() {+ let out = extras(+ &custom(&[+ ("Authorization", "Bearer other"),+ ("x-API-key", "second-credential"),+ ("X-Goog-Api-Key", "g"),+ ("anthropic-version", "1999-01-01"),+ ("Content-Type", "text/plain"),+ ("Accept", "*/*"),+ ("Accept-Encoding", "gzip"),+ ("Bad Name", "v"),+ ("X-Newline", "a\r\nInjected: yes"),+ ("X-Client-Name", "jan-agent"),+ ]),+ Vec::new(),+ );+ assert_eq!(+ out,+ vec![("X-Client-Name".to_string(), "jan-agent".to_string())]+ );+ }++ /// Jan's own values win over a custom header of the same name, whatever its+ /// case, and a name never appears twice.+ #[test]+ fn jan_owned_headers_win_over_custom_ones() {+ let out = extras(+ &custom(&[+ ("user-agent", "spoofed/1.0"),+ ("x-session-id", "not-this-one"),+ ("X-CLIENT-REQUEST-ID", "nor-this"),+ ("X-Tokamak-Launch-Id", "abc"),+ ]),+ owned(Some("Jan-Agent/1 (linux; x86_64)"), Some("jan-s1")),+ );+ assert_eq!(+ out,+ vec![+ ("X-Tokamak-Launch-Id".to_string(), "abc".to_string()),+ (+ "User-Agent".to_string(),+ "Jan-Agent/1 (linux; x86_64)".to_string()+ ),+ ("X-Client-Request-Id".to_string(), "jan-s1".to_string()),+ ("X-Session-Id".to_string(), "s1".to_string()),+ ]+ );+ }++ #[test]+ fn a_repeated_custom_name_keeps_the_later_value() {+ let out = extras(&custom(&[("X-Team", "a"), ("x-team", "b")]), Vec::new());+ assert_eq!(out, vec![("x-team".to_string(), "b".to_string())]);+ }++ /// A converter's own headers are its credentials and protocol version; a+ /// custom header with the same name must neither replace nor duplicate one.+ #[test]+ fn merging_never_duplicates_a_header_the_transport_set() {+ let mut base = vec![+ ("x-api-key".to_string(), "real".to_string()),+ ("anthropic-beta".to_string(), "oauth".to_string()),+ ];+ merge_onto(+ &mut base,+ &[+ ("Anthropic-Beta".to_string(), "custom".to_string()),+ ("X-Client-Name".to_string(), "jan-agent".to_string()),+ ],+ );+ assert_eq!(+ base,+ vec![+ ("x-api-key".to_string(), "real".to_string()),+ ("anthropic-beta".to_string(), "oauth".to_string()),+ ("X-Client-Name".to_string(), "jan-agent".to_string()),+ ]+ );+ }++ #[test]+ fn reported_names_are_the_ones_that_can_be_sent() {+ assert_eq!(+ reportable_names(&custom(&[+ ("X-Client-Name", "jan-agent"),+ ("Authorization", "x"),+ ("x-client-name", "dup"),+ ("X-Tokamak-Launch-Id", "abc"),+ ])),+ vec![+ "X-Client-Name".to_string(),+ "X-Tokamak-Launch-Id".to_string()+ ]+ );+ }+}diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rsindex 89ccf097a..4635f4b6e 100644--- a/src-tauri/src/core/agent/upstream.rs+++ b/src-tauri/src/core/agent/upstream.rs@@ -1408,7 +1408,7 @@ pub(crate) async fn stream_openai_chat_completions(api_type: Option<&str>,body: &serde_json::Value,events: &mpsc::UnboundedSender<StreamEvent>,- client_request_id: Option<&str>,+ extra_headers: &[(String, String)],) -> Result<serde_json::Value, String> {super::genai_bridge::stream_chat_completions(client,@@ -1417,7 +1417,7 @@ pub(crate) async fn stream_openai_chat_completions(api_type,body,events,- client_request_id,+ extra_headers,).await}@@ -1434,10 +1434,12 @@ pub(crate) async fn stream_openai_chat_completions(/// [`resolve_upstream_for_model`]); the base is recovered by stripping that/// suffix and the native path appended in its place.///-/// `client_request_id` is sent as the correlation header so this request can be-/// found in the provider's usage records later (see-/// [`crate::core::agent::correlation`]). This path also owns the HTTP response,-/// so unlike the genai path it can read the execution id straight back off it.+/// `extra_headers` are the provider's custom headers plus Jan's own, the+/// correlation id among them, so this request can be found in the provider's+/// usage records later (see [`crate::core::agent::correlation`] and+/// [`crate::core::agent::request_headers`]). This path also owns the HTTP+/// response, so unlike the genai path it can read the execution id straight+/// back off it.pub(crate) async fn stream_converted_chat_completions(client: &Client,upstream_url: &str,@@ -1445,7 +1447,7 @@ pub(crate) async fn stream_converted_chat_completions(converter: &dyn UpstreamConverter,body: &serde_json::Value,events: &mpsc::UnboundedSender<StreamEvent>,- client_request_id: Option<&str>,+ extra_headers: &[(String, String)],) -> Result<serde_json::Value, String> {// Base is upstream_url minus the trailing "/chat/completions". Recover it// the same way the proxy does when it swaps the destination path.@@ -1472,33 +1474,37 @@ pub(crate) async fn stream_converted_chat_completions(let mut last_err = String::new();for (i, key_ref) in attempts.iter().enumerate() {- let mut req = client- .post(&native_url)- .header("Content-Type", "application/json")- .header("Accept", "text/event-stream")- .header("Accept-Encoding", "identity");+ // Built as one list and applied in one pass: `RequestBuilder::header`+ // appends, so a custom header sharing a name with one of these would+ // otherwise reach the wire twice -- a second credential, for `x-api-key`.+ let mut headers: Vec<(String, String)> = vec![+ ("Content-Type".to_string(), "application/json".to_string()),+ ("Accept".to_string(), "text/event-stream".to_string()),+ ("Accept-Encoding".to_string(), "identity".to_string()),+ ];// The converter decides the auth scheme (Bearer default, but Google// uses x-goog-api-key and Anthropic x-api-key).if let Some(key) = key_ref {let (auth_name, auth_value) = converter.auth_header(key);- req = req.header(auth_name, auth_value);+ headers.push((auth_name.to_string(), auth_value));for (name, value) in converter.credential_headers(key) {- req = req.header(name, value);+ headers.push((name.to_string(), value));}}// Fixed headers the native API requires (Anthropic: anthropic-version).for (name, value) in converter.extra_headers() {- req = req.header(name, value);+ headers.push((name.to_string(), value.to_string()));}- // Correlation id, so this request is findable in the provider's usage- // records. Harmless to a provider that does not use it: an unknown- // request header is ignored.- if let Some(id) = client_request_id {- req = req.header(- crate::core::agent::correlation::CLIENT_REQUEST_ID_HEADER,- id,- );+ // The provider's custom headers and Jan's own: the correlation id, so+ // this request is findable in the provider's usage records, and the+ // session id and User-Agent. Harmless to a provider that does not use+ // them: an unknown request header is ignored.+ crate::core::agent::request_headers::merge_onto(&mut headers, extra_headers);++ let mut req = client.post(&native_url);+ for (name, value) in &headers {+ req = req.header(name.as_str(), value.as_str());}let resp = req@@ -2442,7 +2448,7 @@ mod tests {None,&json!({ "model": "m", "messages": [] }),&tx,- None,+ &[],).await.expect("the retry carries the turn");@@ -2502,7 +2508,7 @@ mod tests {"max_tokens": 128,}),&tx,- None,+ &[],).await.expect("request");@@ -2565,7 +2571,7 @@ mod tests {"messages": [{"role": "user", "content": "hi"}],}),&tx,- Some("jan-session-7"),+ &crate::core::agent::request_headers::owned(None, Some("jan-session-7")),).await.expect("request");@@ -2577,6 +2583,12 @@ mod tests {.contains("\r\nx-client-request-id: jan-session-7\r\n"),"the correlation id must reach the wire: {request}");+ assert!(+ request+ .to_ascii_lowercase()+ .contains("\r\nx-session-id: session-7\r\n"),+ "the session id rides next to it: {request}"+ );assert_eq!(crate::core::agent::correlation::execution_id_of(&completion),Some("exec-abc".to_string()),@@ -2584,6 +2596,82 @@ mod tests {);}+ /// Custom headers reach the native path, but never as a second credential:+ /// a custom `x-api-key` would otherwise ride next to the converter's own+ /// (reqwest's `header` appends), and Jan's own ids beat a custom spelling.+ #[tokio::test]+ async fn the_converted_path_sends_custom_headers_without_a_second_credential() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind");+ let addr = listener.local_addr().expect("addr");+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.expect("accept");+ let mut bytes = vec![0u8; 16 * 1024];+ let read = socket.read(&mut bytes).await.expect("read");+ bytes.truncate(read);+ let response = "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n";+ let wire = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\n\r\n{response}",+ response.len()+ );+ socket.write_all(wire.as_bytes()).await.expect("response");+ String::from_utf8(bytes).expect("request is utf-8")+ });++ let converter = crate::core::server::converters::converter_for(Some("anthropic"), false)+ .expect("converter");+ let custom = vec![+ crate::core::state::ProviderCustomHeader {+ header: "X-Api-Key".into(),+ value: "second-credential".into(),+ },+ crate::core::state::ProviderCustomHeader {+ header: "X-Client-Name".into(),+ value: "jan-agent".into(),+ },+ crate::core::state::ProviderCustomHeader {+ header: "x-session-id".into(),+ value: "spoofed".into(),+ },+ ];+ let extras = crate::core::agent::request_headers::extras(+ &custom,+ crate::core::agent::request_headers::owned(+ Some("Jan-Agent/0.0.0 (test; test)"),+ Some("jan-s-1"),+ ),+ );+ let (tx, _rx) = sink();+ let _ = stream_converted_chat_completions(+ &Client::new(),+ &format!("http://{addr}/v1/chat/completions"),+ &["real-key".to_string()],+ converter.as_ref(),+ &json!({"model": "claude", "messages": [{"role": "user", "content": "hi"}]}),+ &tx,+ &extras,+ )+ .await;++ let request = server.await.expect("server task").to_ascii_lowercase();+ assert_eq!(+ request.matches("\r\nx-api-key: ").count(),+ 1,+ "exactly one credential header: {request}"+ );+ assert!(request.contains("\r\nx-api-key: real-key\r\n"), "{request}");+ assert!(request.contains("\r\nx-client-name: jan-agent\r\n"), "{request}");+ assert!(request.contains("\r\nx-session-id: s-1\r\n"), "{request}");+ assert!(!request.contains("spoofed"), "{request}");+ assert!(+ request.contains("\r\nuser-agent: jan-agent/0.0.0 (test; test)\r\n"),+ "{request}"+ );+ }+/// No session means no correlation id, and the header must then be absent/// rather than sent empty -- an empty value would correlate every run that/// had no session.@@ -2624,7 +2712,7 @@ mod tests {converter.as_ref(),&json!({"model": "m", "messages": [{"role": "user", "content": "hi"}]}),&tx,- None,+ &[],).await.expect("request");diff --git a/src-tauri/src/core/cli/telemetry.rs b/src-tauri/src/core/cli/telemetry.rsindex 6352b955b..1f3c8f18a 100644--- a/src-tauri/src/core/cli/telemetry.rs+++ b/src-tauri/src/core/cli/telemetry.rs@@ -61,14 +61,10 @@ pub(super) fn install_id() -> Option<String> {// "Jan Agent", not "Jan": lets the analytics backend tell this apart from a// desktop client, which sends "Jan/{version} (...)" (see// `custom_updater::build_user_agent`) -- both share the same version number,-// so the client name is the only distinguishing signal in the request.-pub(super) fn user_agent(version: &str) -> String {- format!(- "Jan-Agent/{} ({}; {})",- version,- std::env::consts::OS,- std::env::consts::ARCH- )+// so the client name is the only distinguishing signal in the request. The+// format lives with the inference headers, which send the same token.+pub fn user_agent(version: &str) -> String {+ crate::core::agent::request_headers::agent_user_agent(version)}#[cfg(test)]diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex e3b03ad3e..81ea23a58 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -30753,7 +30753,7 @@ mod tests {None,&json!({"model": "m", "messages": [{"role": "user", "content": "go"}]}),&tx,- None,+ &[],),).await