Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cli): run-time provider overrides for gateways
locnguyen19869dd879e4f645
diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rsindex 40f83b08e..e93ba9e8b 100644--- a/src-tauri/jan-cli/src/main.rs+++ b/src-tauri/jan-cli/src/main.rs@@ -423,20 +423,43 @@ struct ProviderArgs {/// API key for the target provider (else JAN_API_KEY / <PROVIDER>_API_KEY)#[arg(long)]api_key: Option<String>,+ /// Base URL for the --provider named, e.g. a gateway (else JAN_BASE_URL)+ #[arg(+ long,+ value_name = "URL",+ requires = "provider",+ value_parser = app_lib::core::cli::providers::parse_base_url+ )]+ base_url: Option<String>,}impl ProviderArgs {+ /// Resolve the flags and their environment fallbacks, and record the result+ /// as this process's session overrides, so every later rebuild of the+ /// provider map (a TUI reload, the `/model` probe) keeps them.fn into_overrides(self) -> ProviderOverrides {// Default the target provider to the desktop app's current selection so// env-key fallback (<PROVIDER>_API_KEY) works without an explicit flag.+ // Only an explicit --provider scopes a base URL or headers, though:+ // redirecting whatever Desktop last had selected would be a surprise.+ let explicit_provider = self.provider.is_some();let provider = self.provider.or_else(|| app_lib::core::cli::providers::desktop_selection().provider);+ let base_url_source = self+ .base_url+ .is_some()+ .then_some(app_lib::core::cli::providers::OverrideSource::Flag);ProviderOverrides {provider,api_key: self.api_key,+ base_url: self.base_url,+ explicit_provider,+ base_url_source,+ ..Default::default()}.with_env()+ .install()}}@@ -1202,7 +1225,7 @@ async fn handle_auth(cmd: AuthCommands) -> Result<(), String> {tokamak::Logout::ClearedOnly => println!("Signed out of Tokamak locally. The key could not be revoked upstream - \remove it at {}",- tokamak::API_KEYS_URL+ tokamak::api_keys_url()),tokamak::Logout::NothingToDo => println!("Not signed in to Tokamak."),}@@ -1302,7 +1325,7 @@ async fn handle_models(cmd: ModelsCommands) {ModelsCommands::List { provider, project } => {let configs = match load_provider_configs(Some(std::path::Path::new(&project)),- &ProviderOverrides::default().with_env(),+ &ProviderOverrides::session(),) {Ok(c) => c,Err(e) => {@@ -1310,7 +1333,7 @@ async fn handle_models(cmd: ModelsCommands) {std::process::exit(1);}};- let catalog = app_lib::core::cli::model_catalog::load();+ let catalog = app_lib::core::cli::model_catalog::effective();let mut output: Vec<serde_json::Value> = configs.values().filter(|c| app_lib::core::cli::providers::is_cli_reachable(c))@@ -2110,4 +2133,60 @@ mod tests {assert!(!output.contains("long description"));assert!(!output.contains("example.com"));}++ /// `--base-url` sits beside `--provider` / `--api-key` on the TUI and on+ /// `run` / `step`, scopes to an explicitly named provider only (so it+ /// requires one), and never takes a plaintext remote URL.+ #[test]+ fn base_url_parses_beside_provider_and_requires_it() {+ let cli = Cli::parse_from([+ "jan",+ "--provider",+ "tokamak",+ "--base-url",+ "https://api-stag.tokamak.sh/v1/",+ ]);+ assert_eq!(+ cli.providers.base_url.as_deref(),+ Some("https://api-stag.tokamak.sh/v1"),+ "normalized: the trailing slash is dropped"+ );+ for sub in ["run", "step"] {+ let cli = Cli::parse_from([+ "jan",+ "cli",+ "agent",+ sub,+ "task",+ "--provider",+ "gw",+ "--base-url",+ "http://localhost:8080/v1",+ ]);+ let providers = match cli.command {+ Some(Commands::Cli {+ cmd:+ CliCommands::Agent {+ cmd:+ AgentCommands::Run { providers, .. }+ | AgentCommands::Step { providers, .. },+ },+ }) => providers,+ _ => panic!("expected `cli agent {sub}`"),+ };+ assert_eq!(providers.base_url.as_deref(), Some("http://localhost:8080/v1"));+ }+ assert!(+ Cli::try_parse_from(["jan", "--base-url", "https://gw.example/v1"]).is_err(),+ "no --provider to scope it to"+ );+ assert!(Cli::try_parse_from([+ "jan",+ "--provider",+ "gw",+ "--base-url",+ "http://gw.example/v1"+ ])+ .is_err());+ }}diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rsindex f5ab526d2..3f26b4a78 100644--- a/src-tauri/src/core/agent/global_config.rs+++ b/src-tauri/src/core/agent/global_config.rs@@ -74,6 +74,7 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.# api_key = "sk-..."# base_url = "https://api.example.com/v1"# models = ["my-model"]+# headers = { "X-Team" = "infra" } # sent with every request to this provider"#;#[derive(Debug, Clone, Default, Deserialize, Serialize)]@@ -224,6 +225,11 @@ struct GlobalProviderEntry {/// guessing an identity endpoint's response shape).#[serde(default, skip_serializing_if = "Option::is_none")]account: Option<String>,+ /// Extra request headers sent with every request to this provider, inference+ /// and `/models` listing alike: `headers = { "X-Team" = "infra" }`. A+ /// session's `JAN_CUSTOM_HEADERS` beats a header of the same name here.+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ headers: BTreeMap<String, String>,}/// Fields to update on a provider entry via [`set_provider`]. `None` leaves the@@ -288,7 +294,14 @@ pub(crate) fn load_global_config() -> Result<HashMap<String, ProviderConfig>, Stapi_key: entry.api_key,api_keys,base_url: entry.base_url,- custom_headers: Vec::new(),+ custom_headers: entry+ .headers+ .into_iter()+ .map(|(header, value)| crate::core::state::ProviderCustomHeader {+ header,+ value,+ })+ .collect(),models: entry.models,api_type: entry.api_type,// `~/.jan/config.toml` describes the desktop app'sdiff --git a/src-tauri/src/core/agent/otel/mod.rs b/src-tauri/src/core/agent/otel/mod.rsindex 06f0cd301..e7861dc7a 100644--- a/src-tauri/src/core/agent/otel/mod.rs+++ b/src-tauri/src/core/agent/otel/mod.rs@@ -61,6 +61,9 @@ const RETRY_DELAY: Duration = Duration::from_secs(1);/// The longest `Retry-After` honoured; a longer one drops the batch instead.const MAX_RETRY_DELAY: Duration = Duration::from_secs(10);+/// Telemetry capabilities this build reports in `jan cli agent status`.+pub const CAPABILITIES: &[&str] = &[];+/// Per-token prices for `(provider, model)`, when the catalog knows them.pub type Pricer = Box<dyn Fn(Option<&str>, &str) -> Option<TokenRates> + Send + Sync>;diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex 62c8f695c..4ab316937 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -1318,7 +1318,7 @@ fn model_window(/// `None`, which is the correct direction here (a refusal, not a guess).#[cfg(feature = "cli")]fn published_rates(model: &str) -> Option<crate::core::agent::session::TokenRates> {- crate::core::cli::model_catalog::load()+ crate::core::cli::model_catalog::effective().get(None, model).and_then(|info| info.rates())}diff --git a/src-tauri/src/core/cli/auth/mod.rs b/src-tauri/src/core/cli/auth/mod.rsindex 9bf7e730d..50e38f9fe 100644--- a/src-tauri/src/core/cli/auth/mod.rs+++ b/src-tauri/src/core/cli/auth/mod.rs@@ -26,8 +26,9 @@ pub enum Transport {/// Non-secret guidance for minting an API key.#[derive(Debug, Clone)]pub struct ApiKeyMetadata {- /// Human-facing page where the user creates/views keys.- pub keys_url: &'static str,+ /// Human-facing page where the user creates/views keys. Owned because+ /// Tokamak's follows the deployment this run signs in to.+ pub keys_url: String,/// Short hint shown above the masked input.pub hint: &'static str,/// Whether the TUI should open the keys page automatically for this provider.@@ -56,7 +57,7 @@ pub fn provider_catalog() -> Vec<ProviderDefinition> {default_base_url: "https://api.openai.com/v1".to_string(),transport: Transport::OpenAi,api_key: ApiKeyMetadata {- keys_url: "https://platform.openai.com/account/api-keys",+ keys_url: "https://platform.openai.com/account/api-keys".to_string(),hint: "get a key at platform.openai.com/account/api-keys",open_in_browser: false,},@@ -67,7 +68,7 @@ pub fn provider_catalog() -> Vec<ProviderDefinition> {default_base_url: "https://api.anthropic.com/v1".to_string(),transport: Transport::Anthropic,api_key: ApiKeyMetadata {- keys_url: "https://console.anthropic.com/settings/keys",+ keys_url: "https://console.anthropic.com/settings/keys".to_string(),hint: "get a key at console.anthropic.com/settings/keys",open_in_browser: false,},@@ -78,7 +79,7 @@ pub fn provider_catalog() -> Vec<ProviderDefinition> {default_base_url: "https://opencode.ai/zen/v1".to_string(),transport: Transport::OpenAi,api_key: ApiKeyMetadata {- keys_url: "https://opencode.ai/auth",+ keys_url: "https://opencode.ai/auth".to_string(),hint: "sign in at opencode.ai/auth to copy your OpenCode API key",open_in_browser: true,},@@ -89,18 +90,22 @@ pub fn provider_catalog() -> Vec<ProviderDefinition> {default_base_url: "https://api.deepseek.com/v1".to_string(),transport: Transport::OpenAi,api_key: ApiKeyMetadata {- keys_url: "https://platform.deepseek.com/api_keys",+ keys_url: "https://platform.deepseek.com/api_keys".to_string(),hint: "get a key at platform.deepseek.com/api_keys",open_in_browser: false,},},+ // Not a fixed endpoint: the deployment this run signs in to (a dev+ // stack's `TOKAMAK_BASE_URL`, or where the last sign-in went), so a+ // paste sign-in verifies and stores the key against the same host the+ // browser flow would, and sends the user to that host's keys page.ProviderDefinition {id: "tokamak",name: "Tokamak",- default_base_url: "https://api.tokamak.sh/v1".to_string(),+ default_base_url: super::tokamak::base_url(),transport: Transport::OpenAi,api_key: ApiKeyMetadata {- keys_url: "https://tokamak.sh/settings/api-keys",+ keys_url: super::tokamak::api_keys_url(),hint: "get a key at tokamak.sh/settings/api-keys",open_in_browser: false,},diff --git a/src-tauri/src/core/cli/auth/providers.rs b/src-tauri/src/core/cli/auth/providers.rsindex fcd54f40d..aed9bd4f0 100644--- a/src-tauri/src/core/cli/auth/providers.rs+++ b/src-tauri/src/core/cli/auth/providers.rs@@ -69,6 +69,11 @@ pub(crate) async fn discover_models(definition.default_base_url.trim_end_matches('/'));let mut request = client.get(&url);+ // The provider's configured headers, as inference sends them: a gateway+ // that requires one for inference usually requires it to list models too.+ for (name, value) in crate::core::cli::providers::listing_headers_for(definition.id) {+ request = request.header(name, value);+ }request = match definition.transport {// An API-key credential identifies itself with `x-api-key`; an OAuth// access token must go as `Authorization: Bearer` (with the oauth betadiff --git a/src-tauri/src/core/cli/device_auth.rs b/src-tauri/src/core/cli/device_auth.rsindex 63d8246bb..ed93baed8 100644--- a/src-tauri/src/core/cli/device_auth.rs+++ b/src-tauri/src/core/cli/device_auth.rs@@ -164,15 +164,42 @@ pub(crate) fn api_root(base_url: &str) -> String {}}-/// Origin of the *web* app, which serves the authorize page. Tokamak splits the-/// two (API at `api.tokamak.sh`, web at `tokamak.sh`), so a plain `api.`-/// subdomain is dropped; anything else is assumed to serve both.-fn web_root(base_url: &str) -> String {+/// Env var naming the web app's origin outright, for a deployment whose web+/// host cannot be derived from the API host -- a local stack serving the API on+/// `localhost:8080` and the web app on `localhost:3001`.+pub const WEB_URL_ENV: &str = "TOKAMAK_WEB_URL";++/// Origin of the *web* app, which serves the authorize page and the API-keys+/// page: `$TOKAMAK_WEB_URL` when set, else derived from `base_url` (see+/// [`derive_web_root`]).+pub(crate) fn web_root(base_url: &str) -> String {+ resolve_web_root(base_url, std::env::var(WEB_URL_ENV).ok().as_deref())+}++/// Split from [`web_root`] so the precedence is testable without mutating the+/// process environment.+fn resolve_web_root(base_url: &str, from_env: Option<&str>) -> String {+ from_env+ .map(|v| v.trim().trim_end_matches('/'))+ .filter(|v| !v.is_empty())+ .map_or_else(|| derive_web_root(base_url), str::to_string)+}++/// The web origin for an API base. Tokamak splits the two -- API at+/// `api.tokamak.sh`, web at `tokamak.sh`; and per band, API at+/// `api-<band>.tokamak.sh`, web at `<band>.tokamak.sh` -- so an `api.` or+/// `api-` first label is dropped; anything else is assumed to serve both.+fn derive_web_root(base_url: &str) -> String {let Some(mut url) = origin_of(base_url) else {return base_url.trim_end_matches('/').to_string();};- if let Some(host) = url.host_str().and_then(|h| h.strip_prefix("api.")) {- let host = host.to_string();+ let web_host = url.host_str().and_then(|h| {+ h.strip_prefix("api.")+ .or_else(|| h.strip_prefix("api-"))+ .filter(|rest| !rest.is_empty())+ .map(str::to_string)+ });+ if let Some(host) = web_host {if url.set_host(Some(&host)).is_err() {return url.as_str().trim_end_matches('/').to_string();}@@ -742,14 +769,55 @@ mod tests {/// base -- `tokamak.sh/cli/authorize`, never `tokamak.sh/v1/cli/authorize`.#[test]fn web_root_drops_the_api_subdomain_and_the_path() {- assert_eq!(web_root("https://api.tokamak.sh/v1"), "https://tokamak.sh");- assert_eq!(web_root("https://tokamak.sh/v1"), "https://tokamak.sh");assert_eq!(- web_root("http://localhost:8080/v1"),+ derive_web_root("https://api.tokamak.sh/v1"),+ "https://tokamak.sh"+ );+ assert_eq!(+ derive_web_root("https://tokamak.sh/v1"),+ "https://tokamak.sh"+ );+ assert_eq!(+ derive_web_root("http://localhost:8080/v1"),"http://localhost:8080");}+ /// A band's API lives at `api-<band>.`, its web app at `<band>.`: sign-in on+ /// a non-production band must land on that band's web app, not on a host+ /// that does not exist.+ #[test]+ fn web_root_maps_a_band_api_host_to_its_web_host() {+ assert_eq!(+ derive_web_root("https://api-stag.tokamak.sh/v1"),+ "https://stag.tokamak.sh"+ );+ assert_eq!(+ derive_web_root("https://api-dev.tokamak.sh"),+ "https://dev.tokamak.sh"+ );+ // Only the first label is the API marker.+ assert_eq!(+ derive_web_root("https://gateway.api-stag.example/v1"),+ "https://gateway.api-stag.example"+ );+ }++ /// A local stack's web app is on another port entirely, which nothing can+ /// derive: `TOKAMAK_WEB_URL` names it.+ #[test]+ fn the_web_url_override_wins() {+ assert_eq!(+ resolve_web_root("http://localhost:8080/v1", Some("http://localhost:3001/")),+ "http://localhost:3001"+ );+ assert_eq!(+ resolve_web_root("https://api-stag.tokamak.sh/v1", Some(" ")),+ "https://stag.tokamak.sh",+ "a blank override is no override"+ );+ }+#[test]fn authorize_url_matches_the_reference_shape() {let url = build_authorize_url("https://tokamak.sh", "ABCD-2345", None);diff --git a/src-tauri/src/core/cli/login.rs b/src-tauri/src/core/cli/login.rsindex 307cb5dd7..066ecb628 100644--- a/src-tauri/src/core/cli/login.rs+++ b/src-tauri/src/core/cli/login.rs@@ -100,7 +100,7 @@ async fn device_login_interactive() -> Result<(), DeviceLogin> {async fn login_by_paste() -> Result<(), String> {println!();println!("Sign in to Tokamak and create an API key:");- println!(" {}", tokamak::API_KEYS_URL);+ println!(" {}", tokamak::api_keys_url());match tokamak::open_api_keys_page() {Ok(()) => println!(" (opening that page in your browser)"),Err(e) => println!(" (open that URL yourself: {e})"),diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 9a5388acd..9831a0071 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -25,6 +25,7 @@ pub mod rpc;pub mod rpc_schema;pub mod run_report;pub mod providers;+pub(crate) mod session_provider;mod secret_input;pub mod stream_input;pub mod telemetry;@@ -773,6 +774,24 @@ use tokio::sync::{mpsc, Mutex};/// cancellation are what actually stop a runaway loop.const DEFAULT_MAX_SESSION_TOKENS: u64 = 128_000;+/// How long `run` and `step` wait for the session-scoped provider's startup+/// model listing: a cost ceiling is priced at startup from it. The TUI waits+/// this long too when a ceiling is configured.+const SESSION_PROBE_WAIT: std::time::Duration = std::time::Duration::from_secs(20);++/// How long the TUI waits for that listing otherwise: its first frame waits on+/// it, and a slow endpoint's listing is picked up by the first `/model` anyway.+const TUI_SESSION_PROBE_WAIT: std::time::Duration = std::time::Duration::from_secs(5);++/// A provider id as the user knows it, for the startup listing's lines.+fn provider_label(provider: &str) -> String {+ if provider == tokamak::PROVIDER {+ "Tokamak".to_string()+ } else {+ provider.to_string()+ }+}+/// Where the session token ceiling in effect came from, so `agent status` can/// say which source won and the TUI knows whether a model switch moves it.#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -888,7 +907,7 @@ fn resolve_cost_ceiling("a cost ceiling must be a non-negative amount in USD, not {max_usd}"));}- let rates = model_catalog::load()+ let rates = model_catalog::effective().get(provider, model).and_then(|info| info.rates()).ok_or_else(|| {@@ -933,6 +952,36 @@ pub(crate) fn take_migration_notice() -> Option<String> {MIGRATION_NOTICE.lock().unwrap_or_else(|e| e.into_inner()).take()}+/// What this build supports that a caller (a launcher) must be able to check+/// before relying on it, as `jan cli agent status` reports it. Only features+/// this build implements; telemetry's own follow in+/// [`crate::core::agent::otel::CAPABILITIES`].+///+/// - `provider-overrides`: `--base-url` / `JAN_BASE_URL` for an explicit+/// `--provider`, and its `<PROVIDER>_API_KEY`.+/// - `session-overrides`: those overrides survive the whole session (reloads,+/// the `/model` probe) -- the TUI, `run` and `step`; RPC takes none.+/// - `custom-headers`: `JAN_CUSTOM_HEADERS` and `[providers.<id>].headers`.+/// - `user-agent`: inference sends `User-Agent: Jan-Agent/<version> (<os>; <arch>)`.+/// - `session-header`: inference sends `X-Session-Id`.+/// - `session-scoped-providers`: a session-scoped provider's models and prices+/// stay in memory, and its sign-in cannot be changed from inside the session.+pub const CAPABILITIES: &[&str] = &[+ "provider-overrides",+ "session-overrides",+ "custom-headers",+ "user-agent",+ "session-header",+ "session-scoped-providers",+];++/// [`CAPABILITIES`], then telemetry's, in that order.+fn capabilities() -> Vec<&'static str> {+ let mut all = CAPABILITIES.to_vec();+ all.extend(crate::core::agent::otel::CAPABILITIES);+ all+}+/// Resolved-config + provider snapshot for `jan cli agent status`.pub fn cli_agent_status(project: &str,@@ -941,7 +990,8 @@ pub fn cli_agent_status(let project_root = resolve_project_root(project);ensure_project(&project_root)?;let cfg = load_agent_config(&project_root)?;- let provider_configs = load_provider_configs(Some(&project_root), overrides)?;+ let (provider_configs, base_url_sources) =+ providers::load_provider_configs_with_sources(Some(&project_root), overrides)?;// Resolved once, and reported for every registered composer: "which of my// contributors is writing into the cached prefix" is one command, not an@@ -964,7 +1014,8 @@ pub fn cli_agent_status(.collect();// Only providers this build can reach: local-engine entries inherited from- // the desktop store have no upstream here (see `is_cli_reachable`).+ // the desktop store have no upstream here (see `is_cli_reachable`). Header+ // *names* only, never their values, which can carry a credential.let mut providers: Vec<serde_json::Value> = provider_configs.values().filter(|c| crate::core::cli::providers::is_cli_reachable(c))@@ -974,6 +1025,12 @@ pub fn cli_agent_status("base_url": c.base_url,"has_api_key": crate::core::cli::providers::has_credential(c),"models": c.models.len(),+ "header_names": crate::core::agent::request_headers::reportable_names(+ &c.custom_headers+ ),+ "base_url_source": base_url_sources+ .get(&c.provider)+ .map(|source| source.as_str()),})}).collect();@@ -1021,6 +1078,7 @@ pub fn cli_agent_status(let session_budget = resolve_session_budget(None, cfg.budget.max_tokens, status_window);Ok(serde_json::json!({+ "capabilities": capabilities(),"project": project_root.to_string_lossy(),"data_folder": resolve_jan_data_folder().to_string_lossy(),"model": cfg.agent.model,@@ -1392,6 +1450,9 @@ pub(crate) struct AgentSession {/// `Some` only when one was asked for and the session fell back to the/// project directory.pub workspace_note: Option<String>,+ /// Whether `--model` named `model`. A resumed thread then keeps it instead+ /// of switching to the model it was saved with.+ pub model_pinned: bool,}/// The request body for one turn, as a free function of the parts that shape@@ -1636,9 +1697,15 @@ fn prepare_agent_session(cfg.telemetry.enabled,crate::core::agent::global_config::telemetry_setting(),|| {+ // The disk catalog once, and the session overlay on every call: a+ // session-scoped provider's prices can arrive after this is built+ // (a slow startup probe filled by the first `/model` or Ctrl-R).let catalog = crate::core::cli::model_catalog::load();Some(Box::new(move |provider: Option<&str>, model: &str| {- catalog.get(provider, model).and_then(|info| info.rates())+ catalog+ .with_session_overlay()+ .get(provider, model)+ .and_then(|info| info.rates())}))},crate::core::cli::updater::build_version(),@@ -1658,6 +1725,7 @@ fn prepare_agent_session(// the notice instead. An explicit --model, agent.toml, or ~/.jan default is// unaffected: all three outrank this.let explicit = model_override.is_some() || overrides.api_key.is_some();+ let model_pinned = model_override.is_some();let model = model_override.or_else(|| cfg.agent.model.clone()).or_else(|| crate::core::agent::global_config::default_model().ok().flatten())@@ -1835,6 +1903,7 @@ fn prepare_agent_session(mcp_task,workspace,workspace_note,+ model_pinned,})}@@ -2063,6 +2132,19 @@ async fn run_agent_loop(return Err(e);}};+ // A session-scoped provider's models and prices exist only in memory: list+ // them before the run resolves its cost ceiling (`--max-budget-usd` is+ // priced at startup) and its telemetry pricer. A failure is not fatal -- a+ // `provider/model` id still routes by its prefix -- but it is said.+ if let Some((provider, Err(e))) = providers::probe_session_provider(+ Some(&resolve_project_root(project)),+ &overrides,+ SESSION_PROBE_WAIT,+ )+ .await+ {+ eprintln!("(could not list {} models: {e})", provider_label(&provider));+ }let prepared = prepare_agent_run(project,task,@@ -2823,6 +2905,32 @@ pub async fn cli_agent_ui(if overrides.api_key.is_none() {login::reject_headless_without_provider(Some(&project_root))?;}+ // A session-scoped provider's models and prices exist only in memory, so+ // they are listed before the session resolves its pricer and cost ceiling.+ // Briefly, since the first frame waits on it -- unless a ceiling is set,+ // which cannot be priced without the listing and would refuse to start.+ let ceiling_configured = flags.max_budget_usd.is_some()+ || crate::core::agent::project::load_agent_config(&project_root)+ .ok()+ .and_then(|cfg| cfg.budget.max_usd)+ .is_some();+ let wait = if ceiling_configured {+ SESSION_PROBE_WAIT+ } else {+ TUI_SESSION_PROBE_WAIT+ };+ if let Some(provider) = overrides.session_scoped_provider() {+ // Before the alternate screen, which would hide anything printed later.+ eprintln!("fetching {} models...", provider_label(provider));+ }+ if let Some((provider, Err(e))) =+ providers::probe_session_provider(Some(&project_root), &overrides, wait).await+ {+ session_provider::set_startup_notice(format!(+ "could not list {} models ({e}); /model retries",+ provider_label(&provider)+ ));+ }// Fresh install with a terminal attached: launch with no model rather than// forcing sign-in here. The TUI shows a one-line notice and `/login` (or// `jan login`) picks a model up once the user is ready.@@ -4638,4 +4746,79 @@ mod tests {assert_eq!(zero["max_turns"], 0);assert_eq!(zero["max_session_tokens"], 0);}++ /// The contract a launcher checks before relying on any of this: the+ /// capability tokens in a fixed order, and per provider the header *names*+ /// (never values) and where its base URL came from. Existing fields keep+ /// their shape.+ #[test]+ fn agent_status_reports_capabilities_header_names_and_base_url_sources() {+ let overrides = ProviderOverrides {+ provider: Some("tokamak".into()),+ api_key: Some("tk-session".into()),+ base_url: Some("http://127.0.0.1:9/v1".into()),+ base_url_source: Some(crate::core::cli::providers::OverrideSource::Env),+ headers: vec![+ ("X-Client-Name".into(), "jan-agent".into()),+ ("X-Tokamak-Launch-Id".into(), "abc".into()),+ ],+ explicit_provider: true,+ };+ crate::core::cli::session_provider::with_session(overrides.clone(), |_| {+ crate::core::agent::global_config::set_provider(+ "openai",+ crate::core::agent::global_config::ProviderUpdate {+ api_key: Some("sk".into()),+ base_url: Some("https://api.openai.com/v1".into()),+ models: Some(vec!["gpt-x".into()]),+ ..Default::default()+ },+ )+ .unwrap();+ let dir = tempfile::tempdir().unwrap();+ let status = cli_agent_status(dir.path().to_str().unwrap(), &overrides).expect("status");++ let mut expected: Vec<serde_json::Value> = [+ "provider-overrides",+ "session-overrides",+ "custom-headers",+ "user-agent",+ "session-header",+ "session-scoped-providers",+ ]+ .iter()+ .map(|c| serde_json::json!(c))+ .collect();+ expected.extend(+ crate::core::agent::otel::CAPABILITIES+ .iter()+ .map(|c| serde_json::json!(c)),+ );+ assert_eq!(status["capabilities"], serde_json::Value::Array(expected));++ let providers = status["providers"].as_array().expect("providers");+ let tokamak = providers+ .iter()+ .find(|p| p["provider"] == "tokamak")+ .expect("tokamak listed");+ assert_eq!(tokamak["base_url"], "http://127.0.0.1:9/v1");+ assert_eq!(tokamak["base_url_source"], "env");+ assert_eq!(tokamak["has_api_key"], true);+ assert_eq!(tokamak["models"], 0);+ assert_eq!(+ tokamak["header_names"],+ serde_json::json!(["X-Client-Name", "X-Tokamak-Launch-Id"])+ );+ let openai = providers+ .iter()+ .find(|p| p["provider"] == "openai")+ .expect("openai listed");+ assert_eq!(openai["base_url_source"], "config");+ assert_eq!(openai["header_names"], serde_json::json!([]));+ assert_eq!(openai["models"], 1);++ let text = status.to_string();+ assert!(!text.contains("tk-session") && !text.contains("\"abc\""), "no secrets or header values: {text}");+ });+ }}diff --git a/src-tauri/src/core/cli/model_capabilities.rs b/src-tauri/src/core/cli/model_capabilities.rsindex 8514fbb4c..8248b97d7 100644--- a/src-tauri/src/core/cli/model_capabilities.rs+++ b/src-tauri/src/core/cli/model_capabilities.rs@@ -125,7 +125,7 @@ fn catalog_window(model_id: &str) -> Option<u64> {/// list the same id with different deployments, so an unqualified lookup can/// report a window the request will not get.pub(crate) fn reported_window(provider: Option<&str>, model_id: &str) -> Option<u64> {- super::model_catalog::load()+ super::model_catalog::effective().get(provider, model_id).and_then(|info| info.context_length).filter(|tokens| *tokens > 0)diff --git a/src-tauri/src/core/cli/model_catalog.rs b/src-tauri/src/core/cli/model_catalog.rsindex 8072c0129..a98ebcb8d 100644--- a/src-tauri/src/core/cli/model_catalog.rs+++ b/src-tauri/src/core/cli/model_catalog.rs@@ -161,6 +161,12 @@ fn catalog_path() -> Result<PathBuf, String> {/// Read the cache. A missing or unreadable file is an empty catalog, never an/// error: this is metadata that improves a display, so a corrupt cache must/// never block a run.+///+/// Disk only, on purpose: every catalog write starts from this (`probe_models`,+/// [`cache_listing`], [`forget`]), so anything merged in here would be saved to+/// `model_catalog.json` by the next write for any provider. A reader that must+/// see the session-scoped provider's in-memory prices goes through+/// [`effective`] instead.pub fn load() -> Catalog {let Ok(path) = catalog_path() else {return Catalog::default();@@ -171,6 +177,15 @@ pub fn load() -> Catalog {.unwrap_or_default()}+/// The catalog as this session sees it: [`load`], with the session-scoped+/// provider's entries replaced by what its endpoint listed (see+/// [`super::session_provider`]). For reading only -- never save it.+pub fn effective() -> Catalog {+ let mut catalog = load();+ super::session_provider::apply_catalog(&mut catalog);+ catalog+}+impl Catalog {/// Replace one provider's entries, dropping the provider when it reported/// nothing worth keeping.@@ -186,6 +201,28 @@ impl Catalog {self.providers.remove(provider);}+ /// Replace one provider's entries and keep the provider even when `models`+ /// is empty: unlike [`Self::set_provider`], an empty map here means "this+ /// provider prices nothing", so [`Self::get`] under it answers `None`+ /// instead of falling through to another provider's rates.+ pub(crate) fn overlay_provider(&mut self, provider: &str, models: BTreeMap<String, ModelInfo>) {+ self.providers.insert(provider.to_string(), models);+ }++ /// This catalog with the session overlay applied, borrowing it untouched+ /// when there is nothing to overlay: the telemetry pricer asks per request,+ /// and the overlay can be filled after the pricer was built.+ pub(crate) fn with_session_overlay(&self) -> std::borrow::Cow<'_, Catalog> {+ match super::session_provider::overlay_catalog() {+ Some((provider, models)) => {+ let mut view = self.clone();+ view.overlay_provider(&provider, models);+ std::borrow::Cow::Owned(view)+ }+ None => std::borrow::Cow::Borrowed(self),+ }+ }+/// Metadata for `model_id` as `provider` reports it, matching the exact id/// first and then a unique match on the bare id behind a `<vendor>/`/// qualifier, since a user may name a model either way.diff --git a/src-tauri/src/core/cli/providers.rs b/src-tauri/src/core/cli/providers.rsindex de78a9c69..203127779 100644--- a/src-tauri/src/core/cli/providers.rs+++ b/src-tauri/src/core/cli/providers.rs@@ -23,39 +23,247 @@ use crate::core::state::ProviderConfig;const MODEL_PROVIDER_KEY: &str = "model-provider";const API_KEY_SETTING_KEYS: [&str; 2] = ["api-key", "api_key"];+/// Base URL for the explicitly named provider, when `--base-url` is not given.+pub const BASE_URL_ENV: &str = "JAN_BASE_URL";+/// Extra request headers for the explicitly named provider: newline-separated+/// `Name: Value` lines, the format of Claude Code's `ANTHROPIC_CUSTOM_HEADERS`.+pub const CUSTOM_HEADERS_ENV: &str = "JAN_CUSTOM_HEADERS";+/// CLI/env overrides applied after loading the persisted store.-#[derive(Debug, Default, Clone)]+///+/// The key applies the way it always has: to `provider`, or to every provider+/// when none is targeted. The base URL and the headers apply only to a provider+/// named with an explicit `--provider` (`explicit_provider`): the Desktop+/// selection that fills `provider` in otherwise is a default for the key+/// fallback, not a statement about where this run should go, and pointing+/// whatever Desktop last had selected at a gateway would be a surprise.+#[derive(Debug, Default, Clone, PartialEq)]pub struct ProviderOverrides {/// Restrict/target a single provider (e.g. `anthropic`).pub provider: Option<String>,/// API key to inject for `provider` (or all providers when `provider` is None).pub api_key: Option<String>,+ /// Base URL for `provider` (`--base-url`, else `JAN_BASE_URL`). Applied+ /// only when `explicit_provider`.+ pub base_url: Option<String>,+ /// Extra request headers for `provider` (`JAN_CUSTOM_HEADERS`), beating a+ /// configured header of the same name. Applied only when `explicit_provider`.+ pub headers: Vec<(String, String)>,+ /// Whether `provider` came from `--provider`, rather than being defaulted+ /// from the Desktop selection.+ pub explicit_provider: bool,+ /// Where `base_url` came from, for `jan cli agent status`.+ pub base_url_source: Option<OverrideSource>,+}++/// Which session override supplied a value.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum OverrideSource {+ /// A command-line flag.+ Flag,+ /// An environment variable.+ Env,}impl ProviderOverrides {- /// Fold in environment fallbacks for the API key when not set explicitly.- /// `JAN_API_KEY` wins, then a provider-specific var (`ANTHROPIC_API_KEY`,- /// `OPENAI_API_KEY`, ...) when a provider is targeted.- pub fn with_env(mut self) -> Self {+ /// Fold in environment fallbacks for whatever was not set explicitly.+ ///+ /// The key: `JAN_API_KEY` wins, then a provider-specific var+ /// (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, ...) when a provider is targeted.+ /// For an explicitly named provider, `JAN_BASE_URL` and `JAN_CUSTOM_HEADERS`+ /// too; with no explicit provider those two are ignored, and a warning says+ /// so once per process (every provider-map rebuild comes through here, and+ /// the TUI must not have its screen drawn over on each one).+ pub fn with_env(self) -> Self {+ self.with_env_from(|name| std::env::var(name).ok())+ }++ /// [`Self::with_env`] against an injected environment, so the precedence+ /// is testable without mutating the process environment every other test+ /// in this binary shares.+ fn with_env_from(mut self, env: impl Fn(&str) -> Option<String>) -> Self {+ let non_empty = |name: &str| env(name).filter(|v| !v.trim().is_empty());if self.api_key.is_none() {- if let Ok(k) = std::env::var("JAN_API_KEY") {- if !k.is_empty() {- self.api_key = Some(k);- }+ if let Some(k) = env("JAN_API_KEY").filter(|k| !k.is_empty()) {+ self.api_key = Some(k);}}if self.api_key.is_none() {if let Some(provider) = &self.provider {let var = format!("{}_API_KEY", provider.to_ascii_uppercase());- if let Ok(k) = std::env::var(&var) {- if !k.is_empty() {- self.api_key = Some(k);+ if let Some(k) = env(&var).filter(|k| !k.is_empty()) {+ self.api_key = Some(k);+ }+ }+ }+ let base_url = non_empty(BASE_URL_ENV);+ let headers = non_empty(CUSTOM_HEADERS_ENV);+ if !self.explicit_provider {+ if base_url.is_some() || headers.is_some() {+ warn_once_unscoped();+ }+ return self;+ }+ if self.base_url.is_none() {+ if let Some(raw) = base_url {+ match parse_base_url(&raw) {+ Ok(url) => {+ self.base_url = Some(url);+ self.base_url_source = Some(OverrideSource::Env);}+ Err(e) => warn_once_bad_base_url(&e),}}}+ if self.headers.is_empty() {+ if let Some(raw) = headers {+ self.headers = parse_custom_headers(&raw);+ }+ }+ self+ }++ /// The overrides this CLI session was started with, as recorded by+ /// [`Self::install`]. Every rebuild of the provider map in the CLI goes+ /// through this, so a key or base URL from the command line or the+ /// environment survives a TUI reload, the `/model` probe and `cli models+ /// list` instead of being dropped on the first rebuild. Before anything was+ /// installed (a command that takes no provider flags), the environment+ /// fallbacks alone, which is what those rebuilds always used.+ pub fn session() -> Self {+ super::session_provider::overrides().unwrap_or_else(|| Self::default().with_env())+ }++ /// Record these as the session's overrides (see [`Self::session`]) and hand+ /// them back. Called once, by the binary, when it resolves its flags.+ pub fn install(self) -> Self {+ super::session_provider::install(&self);self}++ /// The provider this session scopes to itself: one named with an explicit+ /// `--provider` whose base URL or key came from these overrides. Its model+ /// roster and prices describe the session's endpoint rather than whatever+ /// `~/.jan` was written for, so they are kept in memory and never persisted+ /// (see [`super::session_provider`]).+ ///+ /// `JAN_API_KEY` with no `--provider`, and a Desktop-default provider's+ /// `<PROVIDER>_API_KEY`, do not make a provider session-scoped: those users+ /// keep persisting refresh results exactly as before.+ pub fn session_scoped_provider(&self) -> Option<&str> {+ if self.base_url.is_none() && self.api_key.is_none() {+ return None;+ }+ self.explicit_provider_name()+ }++ /// The provider named with an explicit `--provider`, if any -- never the+ /// Desktop-selection default, which only steers the key fallback. The one+ /// provider a base URL, headers, and anything else scoped to "the provider+ /// this session named" apply to.+ pub fn explicit_provider_name(&self) -> Option<&str> {+ self.provider.as_deref().filter(|_| self.explicit_provider)+ }+}++fn warn_once_unscoped() {+ static WARNED: std::sync::Once = std::sync::Once::new();+ WARNED.call_once(|| {+ log::warn!(+ "{BASE_URL_ENV} and {CUSTOM_HEADERS_ENV} apply only to a provider named with \+ --provider; ignoring them"+ )+ });+}++fn warn_once_bad_base_url(error: &str) {+ static WARNED: std::sync::Once = std::sync::Once::new();+ WARNED.call_once(|| log::warn!("ignoring {BASE_URL_ENV}: {error}"));+}++/// Validate and normalize a base URL given on the command line or in the+/// environment: an absolute `https://` URL, or `http://` for a loopback host --+/// the same rule the `/models` probe and the provider settings form apply, so a+/// key is never sent over a plaintext remote connection. The trailing slash is+/// dropped, since every caller appends a path.+pub fn parse_base_url(raw: &str) -> Result<String, String> {+ let url = raw.trim().trim_end_matches('/');+ let parsed = reqwest::Url::parse(url).map_err(|e| format!("'{url}' is not a URL: {e}"))?;+ match parsed.scheme() {+ "https" => {}+ "http" if is_loopback_url(url) => {}+ "http" => {+ return Err(format!(+ "'{url}' is plaintext http on a remote host; use https:// (http:// is only \+ accepted for localhost)"+ ))+ }+ other => return Err(format!("'{url}' has an unsupported scheme '{other}'")),+ }+ if parsed.host_str().is_none_or(str::is_empty) {+ return Err(format!("'{url}' has no host"));+ }+ Ok(url.to_string())+}++/// Parse `JAN_CUSTOM_HEADERS`: one `Name: Value` per line. Blank lines are+/// skipped; a line with no `:`, an invalid name or value, or a+/// [reserved](crate::core::agent::request_headers::RESERVED) name is dropped+/// with a warning naming the header (never its value, which can be a+/// credential). A repeated name keeps the later value.+pub fn parse_custom_headers(raw: &str) -> Vec<(String, String)> {+ let mut out: Vec<(String, String)> = Vec::new();+ for line in raw.lines() {+ let line = line.trim();+ if line.is_empty() {+ continue;+ }+ let Some((name, value)) = line.split_once(':') else {+ log::warn!("{CUSTOM_HEADERS_ENV}: skipping a line with no `Name: Value` separator");+ continue;+ };+ let (name, value) = (name.trim(), value.trim());+ if crate::core::agent::request_headers::is_reserved(name) {+ log::warn!("{CUSTOM_HEADERS_ENV}: '{name}' is a reserved header; skipping it");+ continue;+ }+ if reqwest::header::HeaderName::from_bytes(name.as_bytes()).is_err()+ || reqwest::header::HeaderValue::from_str(value).is_err()+ {+ log::warn!("{CUSTOM_HEADERS_ENV}: '{name}' is not a valid header; skipping it");+ continue;+ }+ out.retain(|(n, _)| !n.eq_ignore_ascii_case(name));+ out.push((name.to_string(), value.to_string()));+ }+ out+}++/// Where a provider's base URL came from, as `jan cli agent status` reports it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum BaseUrlSource {+ /// `--base-url`.+ Flag,+ /// `JAN_BASE_URL`.+ Env,+ /// The project's `agent.toml` `[provider]`.+ Project,+ /// `~/.jan/config.toml`.+ Config,+ /// Inherited from Jan Desktop's `settings.json`.+ Desktop,+}++impl BaseUrlSource {+ pub fn as_str(self) -> &'static str {+ match self {+ BaseUrlSource::Flag => "flag",+ BaseUrlSource::Env => "env",+ BaseUrlSource::Project => "project",+ BaseUrlSource::Config => "config",+ BaseUrlSource::Desktop => "desktop",+ }+ }}/// The desktop app's current selection (`state.selectedProvider` /@@ -141,7 +349,7 @@ fn warn_load_failure_once(context: &str, err: &str) {/// triggers the sign-in flow. A remote entry with no key does not count: the/// request would only fail later with a 401.pub fn has_usable_provider(project_root: Option<&std::path::Path>) -> bool {- let overrides = ProviderOverrides::default().with_env();+ let overrides = ProviderOverrides::session();match load_provider_configs(project_root, &overrides) {Ok(configs) => configs.values().any(is_usable),Err(e) => {@@ -160,11 +368,19 @@ pub fn provider_is_signed_in(project_root: Option<&Path>, provider: &str) -> booreturn true;}- let overrides = ProviderOverrides {- provider: Some(provider.to_string()),- api_key: None,- }- .with_env();+ // The session's own overrides only for the provider they name: merging+ // them into another provider's answer would report it signed in on a key+ // that was never meant for it.+ let session = ProviderOverrides::session();+ let overrides = if session.provider.as_deref() == Some(provider) {+ session+ } else {+ ProviderOverrides {+ provider: Some(provider.to_string()),+ ..Default::default()+ }+ .with_env()+ };load_provider_configs(project_root, &overrides).ok()@@ -258,7 +474,7 @@ pub fn unreachable_local_provider(/// exactly what a run can reach, including `~/.jan/config.toml` providers the/// desktop store knows nothing about.pub fn list_provider_models(project_root: Option<&std::path::Path>) -> Vec<(String, String)> {- match load_provider_configs(project_root, &ProviderOverrides::default().with_env()) {+ match load_provider_configs(project_root, &ProviderOverrides::session()) {Ok(configs) => reachable_models(&configs),Err(e) => {warn_load_failure_once(" for the model picker", &e);@@ -309,7 +525,9 @@ pub struct ModelRefresh {}impl ModelRefresh {- /// Whether anything was written to disk.+ /// Whether any provider's roster changed: on disk, or in the session-scoped+ /// provider's in-memory overlay. Either way the caller's provider snapshot+ /// is stale.pub fn changed_any(&self) -> bool {self.listed.iter().any(|p| p.changed)}@@ -406,10 +624,53 @@ pub async fn refresh_models(Ok(refresh)}+/// List the session-scoped provider's models once, at session start, into the+/// in-memory overlay ([`super::session_provider`]) -- its roster and prices are+/// never on disk, so without this a fresh home would start with neither. `None`+/// when the session has no session-scoped provider, which is every native+/// launch: no extra request is made then.+///+/// The answer replaces whatever the overlay held. `wait` bounds the whole+/// request: the caller decides how long its startup can afford.+pub(crate) async fn probe_session_provider(+ project_root: Option<&std::path::Path>,+ overrides: &ProviderOverrides,+ wait: Duration,+) -> Option<(String, Result<usize, String>)> {+ let provider = overrides.session_scoped_provider()?.to_string();+ let outcome = async {+ let configs = load_provider_configs(project_root, overrides)?;+ let config = configs+ .get(&provider)+ .filter(|c| is_cli_reachable(c))+ .ok_or_else(|| "no base URL to list them from".to_string())?;+ let client = reqwest::Client::builder()+ .timeout(wait)+ .build()+ .map_err(|e| e.to_string())?;+ let base_url = config.base_url.clone().unwrap_or_default();+ let listing = fetch_models(+ &client,+ &base_url,+ &config.bearer_key_chain(),+ &listing_headers(config),+ )+ .await?;+ if listing.ids.is_empty() {+ return Err("the endpoint listed no models".to_string());+ }+ let count = listing.ids.len();+ super::session_provider::record_listing(&provider, listing.ids, listing.info);+ Ok(count)+ }+ .await;+ Some((provider, outcome))+}+/// Why `provider` could not be refreshed, for the report above. Reads only/// local config: the endpoint was never reached.fn unrefreshable_reason(project_root: Option<&std::path::Path>, provider: &str) -> String {- let known = load_provider_configs(project_root, &ProviderOverrides::default().with_env())+ let known = load_provider_configs(project_root, &ProviderOverrides::session()).ok().and_then(|configs| configs.get(provider).cloned());let Some(config) = known else {@@ -446,19 +707,31 @@ fn mark_probed(/// per-model metadata into the model catalog.////// Only providers present in the global store are touched -- writing a-/// models-only entry for a Desktop-inherited provider would shadow it. An-/// endpoint that cannot be listed is reported in [`ModelRefresh::failed`] rather-/// than failing the call, so one dead credential never blocks the others.+/// models-only entry for a Desktop-inherited provider would shadow it. The one+/// exception is the session-scoped provider (see+/// [`ProviderOverrides::session_scoped_provider`]), which is probed wherever its+/// entry came from and whose answer goes to the in-memory overlay+/// ([`super::session_provider`]), never to disk. An endpoint that cannot be+/// listed is reported in [`ModelRefresh::failed`] rather than failing the call,+/// so one dead credential never blocks the others.+///+/// Invariant: the roster written back is computed from `load_provider_configs`,+/// which applies that overlay. That is safe only because the overlay changes the+/// session-scoped provider's entry alone, and nothing here writes that provider+/// back; widening the overlay to another provider would persist it.async fn probe_models(project_root: Option<&std::path::Path>,roster: Roster,mut select: impl FnMut(&ProviderConfig) -> bool,) -> Result<ModelRefresh, String> {let global = load_global_config()?;- let configs = load_provider_configs(project_root, &ProviderOverrides::default().with_env())?;+ let overrides = ProviderOverrides::session();+ let scoped = overrides.session_scoped_provider().map(str::to_string);+ let is_scoped = |provider: &str| scoped.as_deref() == Some(provider);+ let configs = load_provider_configs(project_root, &overrides)?;let mut to_fetch: Vec<(ProviderConfig, Vec<String>)> = configs.values()- .filter(|c| global.contains_key(&c.provider) && is_cli_reachable(c))+ .filter(|c| (global.contains_key(&c.provider) || is_scoped(&c.provider)) && is_cli_reachable(c))// Filtered before the key is fetched so a re-open cannot re-prompt for// a provider already probed..filter(|c| select(c))@@ -485,7 +758,8 @@ async fn probe_models(let client = &client;async move {let base_url = config.base_url.clone().unwrap_or_default();- let listing = fetch_models(client, &base_url, &keys).await;+ let headers = listing_headers(&config);+ let listing = fetch_models(client, &base_url, &keys, &headers).await;(config, listing)}}))@@ -530,6 +804,23 @@ async fn probe_models(merged}};+ let changed = stored != config.models;+ // The session's own endpoint: its answer lives in memory for this+ // process only. `changed` still counts, so the caller reloads and a+ // model the endpoint added mid-session routes without a restart.+ if is_scoped(&config.provider) {+ super::session_provider::record_listing(&config.provider, stored.clone(), listing.info);+ refresh.listed.push(ProviderModels {+ provider: config.provider,+ models: stored.len(),+ changed,+ kept_unlisted: match roster {+ Roster::Additive => unlisted.len(),+ Roster::Replace => 0,+ },+ });+ continue;+ }// Only a provider that *used to* offer the default can retire it; one// that never listed it says nothing about it either way, and an// additive probe drops nothing at all.@@ -538,7 +829,6 @@ async fn probe_models(default_dropped = true;}}- let changed = stored != config.models;if changed {crate::core::agent::global_config::set_provider(&config.provider,@@ -588,6 +878,46 @@ async fn probe_models(Ok(refresh)}+/// The headers a `/models` listing for `config` sends besides its key: the+/// provider's custom headers and the `User-Agent`, the same set inference sends+/// (reserved names dropped). No correlation ids: a listing belongs to no session.+pub(crate) fn listing_headers(config: &ProviderConfig) -> Vec<(String, String)> {+ use crate::core::agent::request_headers::{extras, owned, user_agent};+ extras(&config.custom_headers, owned(user_agent(), None))+}++/// [`listing_headers`] for a provider known only by id -- a sign-in, which+/// holds a provider definition rather than a resolved config: its configured+/// headers, with the session's `JAN_CUSTOM_HEADERS` on top when the session+/// names it. Read from `~/.jan/config.toml` directly, so no credential store+/// is touched on the way.+pub(crate) fn listing_headers_for(provider: &str) -> Vec<(String, String)> {+ let mut config = load_global_config()+ .ok()+ .and_then(|configs| configs.get(provider).cloned())+ .unwrap_or_default();+ let session = ProviderOverrides::session();+ if session.explicit_provider_name() == Some(provider) {+ merge_custom_headers(&mut config.custom_headers, &session.headers);+ }+ listing_headers(&config)+}++/// Layer `headers` over `existing`: a header of the same name, in any case, is+/// replaced, so an environment header beats a configured one.+fn merge_custom_headers(+ existing: &mut Vec<crate::core::state::ProviderCustomHeader>,+ headers: &[(String, String)],+) {+ for (name, value) in headers {+ existing.retain(|h| !h.header.eq_ignore_ascii_case(name));+ existing.push(crate::core::state::ProviderCustomHeader {+ header: name.clone(),+ value: value.clone(),+ });+ }+}+/// What one `/models` response carried: the ids the config stores, plus the/// per-model metadata the catalog caches.struct ModelListing {@@ -601,11 +931,14 @@ struct ModelListing {/// per-model metadata it reported. A provider with no key (a keyless local/// endpoint) is queried unauthenticated. A remote plaintext-`http` base URL is/// rejected up front so a bearer key is never sent over a cleartext connection-/// (loopback `http` is allowed).+/// (loopback `http` is allowed). `headers` are sent too (see+/// [`listing_headers`]): a gateway that requires a header for inference+/// usually requires it for the listing.async fn fetch_models(client: &reqwest::Client,base_url: &str,keys: &[String],+ headers: &[(String, String)],) -> Result<ModelListing, String> {if !(base_url.starts_with("https://")|| (base_url.starts_with("http://") && is_loopback_url(base_url)))@@ -623,6 +956,9 @@ async fn fetch_models(};for key in attempts {let mut request = client.get(&url);+ for (name, value) in headers {+ request = request.header(name.as_str(), value.as_str());+ }if let Some(key) = key {request = request.header("Authorization", format!("Bearer {key}"));}@@ -663,17 +999,51 @@ pub fn load_provider_configs(project_root: Option<&std::path::Path>,overrides: &ProviderOverrides,) -> Result<HashMap<String, ProviderConfig>, String> {+ load_provider_configs_with_sources(project_root, overrides).map(|(configs, _)| configs)+}++/// Providers by id, and which layer each one's base URL came from.+pub(crate) type LayeredConfigs = (HashMap<String, ProviderConfig>, HashMap<String, BaseUrlSource>);++/// [`load_provider_configs`], plus which layer each provider's base URL came+/// from (for `jan cli agent status`). One implementation, so the reported+/// source can never describe a different layering than the one that ran.+///+/// The session-scoped provider's roster is the in-memory overlay's+/// ([`super::session_provider::apply_roster`]). Safe here because nothing+/// writes a config back from this map: config writes merge into+/// `global_config::load_raw`, and the one writer that computes a roster from+/// this map, `probe_models`, never writes the session-scoped provider.+pub(crate) fn load_provider_configs_with_sources(+ project_root: Option<&std::path::Path>,+ overrides: &ProviderOverrides,+) -> Result<LayeredConfigs, String> {let mut configs = load_global_config()?;+ let mut sources: HashMap<String, BaseUrlSource> = configs+ .keys()+ .map(|name| (name.clone(), BaseUrlSource::Config))+ .collect();- inherit_desktop_providers(&mut configs);+ for name in inherit_desktop_providers(&mut configs) {+ sources.insert(name, BaseUrlSource::Desktop);+ }if let Some(root) = project_root {- apply_local_override(&mut configs, root)?;+ if let Some(name) = apply_local_override(&mut configs, root)? {+ sources.insert(name, BaseUrlSource::Project);+ }}- apply_overrides(&mut configs, overrides);+ if let Some((name, source)) = apply_overrides(&mut configs, overrides) {+ let source = match source {+ OverrideSource::Flag => BaseUrlSource::Flag,+ OverrideSource::Env => BaseUrlSource::Env,+ };+ sources.insert(name, source);+ }+ super::session_provider::apply_roster(&mut configs, overrides);seed_from_credential_store(&mut configs);- Ok(configs)+ Ok((configs, sources))}/// Fill a login-created provider's key chain from the auth credential store@@ -709,15 +1079,20 @@ fn seed_from_credential_store(configs: &mut HashMap<String, ProviderConfig>) {/// providers a run will never select. Keys are fetched by/// [`hydrate_provider_keys`] for the one provider that is actually used;/// [`has_stored_key`] answers presence without touching the secret.-fn inherit_desktop_providers(configs: &mut HashMap<String, ProviderConfig>) {+fn inherit_desktop_providers(configs: &mut HashMap<String, ProviderConfig>) -> Vec<String> {let path = resolve_jan_data_folder().join("settings.json");let desktop_configs = match std::fs::read_to_string(&path) {Ok(raw) => parse_provider_store(&raw),- Err(_) => return,+ Err(_) => return Vec::new(),};+ let mut inherited = Vec::new();for (name, cfg) in desktop_configs {- configs.entry(name).or_insert(cfg);+ if let std::collections::hash_map::Entry::Vacant(slot) = configs.entry(name.clone()) {+ slot.insert(cfg);+ inherited.push(name);+ }}+ inherited}/// Apply the project's `agent.toml` `[provider]` section, if present. Highest@@ -726,15 +1101,16 @@ fn inherit_desktop_providers(configs: &mut HashMap<String, ProviderConfig>) {fn apply_local_override(configs: &mut HashMap<String, ProviderConfig>,project_root: &std::path::Path,-) -> Result<(), String> {+) -> Result<Option<String>, String> {let cfg = match crate::core::agent::project::load_agent_config(project_root) {Ok(cfg) => cfg,- Err(_) => return Ok(()),+ Err(_) => return Ok(None),};- if let Some(section) = cfg.provider {- configs.insert(section.name.clone(), provider_config_from_section(section));- }- Ok(())+ Ok(cfg.provider.map(|section| {+ let name = section.name.clone();+ configs.insert(name.clone(), provider_config_from_section(section));+ name+ }))}fn provider_config_from_section(section: ProviderSection) -> ProviderConfig {@@ -884,35 +1260,65 @@ fn provider_from_json(p: &serde_json::Value) -> Option<ProviderConfig> {})}-/// Inject the override API key into the targeted provider(s). When a provider-/// is named but absent from the store, a minimal config is synthesized so the-/// CLI can reach it purely from flags/env.-fn apply_overrides(configs: &mut HashMap<String, ProviderConfig>, overrides: &ProviderOverrides) {- let Some(api_key) = &overrides.api_key else {- return;- };- match &overrides.provider {- Some(provider) => {- let cfg = configs- .entry(provider.clone())- .or_insert_with(|| ProviderConfig {- provider: provider.clone(),- api_key: None,- api_keys: Vec::new(),- base_url: None,- custom_headers: Vec::new(),- models: Vec::new(),- api_type: None,- compaction_ratio: None,- });- set_key(cfg, api_key);- }- None => {- for cfg in configs.values_mut() {+/// Inject the override API key into the targeted provider(s), and the base URL+/// and headers into an explicitly named one. When a provider is named but+/// absent from the store, a minimal config is synthesized so the CLI can reach+/// it purely from flags/env -- reachable once a base URL is given.+///+/// Each part applies on its own: a base URL with no key (a keyless gateway, or+/// a key the store already holds) is as valid as a key with no base URL.+/// Returns the provider whose base URL an override set, and which override did.+fn apply_overrides(+ configs: &mut HashMap<String, ProviderConfig>,+ overrides: &ProviderOverrides,+) -> Option<(String, OverrideSource)> {+ if let Some(api_key) = &overrides.api_key {+ match &overrides.provider {+ Some(provider) => {+ let cfg = configs+ .entry(provider.clone())+ .or_insert_with(|| synthesized(provider));set_key(cfg, api_key);}+ None => {+ for cfg in configs.values_mut() {+ set_key(cfg, api_key);+ }+ }}}+ let provider = overrides.explicit_provider_name()?;+ let mut base_url_set = None;+ if let Some(base_url) = &overrides.base_url {+ configs+ .entry(provider.to_string())+ .or_insert_with(|| synthesized(provider))+ .base_url = Some(base_url.clone());+ base_url_set = Some((+ provider.to_string(),+ overrides.base_url_source.unwrap_or(OverrideSource::Flag),+ ));+ }+ // Headers alone do not conjure an entry: with neither a key nor a base URL+ // there is nothing to send them to.+ if let Some(cfg) = configs.get_mut(provider) {+ merge_custom_headers(&mut cfg.custom_headers, &overrides.headers);+ }+ base_url_set+}++/// A minimal entry for a provider named only by flags/env.+fn synthesized(provider: &str) -> ProviderConfig {+ ProviderConfig {+ provider: provider.to_string(),+ api_key: None,+ api_keys: Vec::new(),+ base_url: None,+ custom_headers: Vec::new(),+ models: Vec::new(),+ api_type: None,+ compaction_ratio: None,+ }}fn set_key(cfg: &mut ProviderConfig, api_key: &str) {@@ -988,6 +1394,7 @@ mod tests {let ov = ProviderOverrides {provider: Some("openai".to_string()),api_key: Some("sk-new".to_string()),+ ..Default::default()};apply_overrides(&mut configs, &ov);let openai = configs.get("openai").unwrap();@@ -1001,6 +1408,7 @@ mod tests {let ov = ProviderOverrides {provider: Some("anthropic".to_string()),api_key: Some("sk-ant".to_string()),+ ..Default::default()};apply_overrides(&mut configs, &ov);assert_eq!(@@ -1015,6 +1423,7 @@ mod tests {let ov = ProviderOverrides {provider: None,api_key: Some("shared".to_string()),+ ..Default::default()};apply_overrides(&mut configs, &ov);assert!(configs@@ -2102,6 +2511,7 @@ mod tests {let overrides = ProviderOverrides {provider: Some("deepseek".into()),api_key: Some("sk-flag".into()),+ ..Default::default()};let configs = load_provider_configs(None, &overrides).unwrap();assert_eq!(@@ -2111,4 +2521,558 @@ mod tests {});});}++ // ── Run-time overrides for gateways ─────────────────────────────────────++ fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {+ let map: HashMap<String, String> = pairs+ .iter()+ .map(|(k, v)| ((*k).to_string(), (*v).to_string()))+ .collect();+ move |name| map.get(name).cloned()+ }++ fn named(provider: &str) -> ProviderOverrides {+ ProviderOverrides {+ provider: Some(provider.to_string()),+ explicit_provider: true,+ ..Default::default()+ }+ }++ /// The Desktop selection defaults `provider` for the key fallback only: a+ /// gateway URL or headers must never be pointed at whatever Desktop last+ /// had selected.+ #[test]+ fn a_desktop_default_provider_does_not_count_as_named() {+ let env = env_of(&[+ ("JAN_BASE_URL", "https://api-stag.tokamak.sh/v1"),+ ("JAN_CUSTOM_HEADERS", "X-Client-Name: jan-agent"),+ ("TOKAMAK_API_KEY", "tk-env"),+ ]);+ let defaulted = ProviderOverrides {+ provider: Some("tokamak".into()),+ ..Default::default()+ }+ .with_env_from(&env);+ assert_eq!(defaulted.api_key.as_deref(), Some("tk-env"), "the key fallback stays");+ assert_eq!(defaulted.base_url, None);+ assert!(defaulted.headers.is_empty());+ assert_eq!(defaulted.session_scoped_provider(), None);++ let explicit = named("tokamak").with_env_from(&env);+ assert_eq!(explicit.base_url.as_deref(), Some("https://api-stag.tokamak.sh/v1"));+ assert_eq!(explicit.base_url_source, Some(OverrideSource::Env));+ assert_eq!(+ explicit.headers,+ vec![("X-Client-Name".to_string(), "jan-agent".to_string())]+ );+ assert_eq!(explicit.session_scoped_provider(), Some("tokamak"));+ }++ /// `JAN_API_KEY` keeps its old meaning (every provider, or the targeted+ /// one), and on its own scopes nothing to the session.+ #[test]+ fn jan_api_key_alone_scopes_nothing() {+ let env = env_of(&[("JAN_API_KEY", "shared")]);+ let unnamed = ProviderOverrides::default().with_env_from(&env);+ assert_eq!(unnamed.api_key.as_deref(), Some("shared"));+ assert_eq!(unnamed.session_scoped_provider(), None);+ let named = named("openai").with_env_from(&env);+ assert_eq!(named.api_key.as_deref(), Some("shared"));+ assert_eq!(named.session_scoped_provider(), Some("openai"));+ }++ #[test]+ fn the_base_url_flag_beats_the_env() {+ let overrides = ProviderOverrides {+ base_url: Some("https://flag.example/v1".into()),+ base_url_source: Some(OverrideSource::Flag),+ ..named("gw")+ }+ .with_env_from(env_of(&[("JAN_BASE_URL", "https://env.example/v1")]));+ assert_eq!(overrides.base_url.as_deref(), Some("https://flag.example/v1"));+ assert_eq!(overrides.base_url_source, Some(OverrideSource::Flag));+ }++ /// A key is never sent over a plaintext remote connection, whichever way+ /// the base URL arrived.+ #[test]+ fn a_base_url_must_be_https_or_loopback() {+ assert_eq!(+ parse_base_url(" https://api-stag.tokamak.sh/v1/ ").as_deref(),+ Ok("https://api-stag.tokamak.sh/v1")+ );+ assert_eq!(+ parse_base_url("http://127.0.0.1:8080/v1").as_deref(),+ Ok("http://127.0.0.1:8080/v1")+ );+ assert!(parse_base_url("http://gateway.example/v1").is_err());+ assert!(parse_base_url("not a url").is_err());+ assert!(parse_base_url("ftp://files.example").is_err());+ // From the environment an unusable value is ignored, not half-applied.+ let ignored = named("gw").with_env_from(env_of(&[("JAN_BASE_URL", "http://gw.example/v1")]));+ assert_eq!(ignored.base_url, None);+ }++ #[test]+ fn custom_headers_parse_like_claudes() {+ let headers = parse_custom_headers(+ "X-Client-Name: jan-agent\r\nX-Tokamak-Launch-Id: abc \n\n\+ Authorization: Bearer nope\nno separator here\nBad Name: v\n\+ x-client-name: again\n",+ );+ assert_eq!(+ headers,+ vec![+ ("X-Tokamak-Launch-Id".to_string(), "abc".to_string()),+ ("x-client-name".to_string(), "again".to_string()),+ ]+ );+ }++ /// A gateway that needs no key (or whose key the store already holds) is+ /// reachable from a base URL alone, and the entry is synthesized for it.+ #[test]+ fn a_keyless_override_synthesizes_a_reachable_entry() {+ let mut configs = HashMap::new();+ let source = apply_overrides(+ &mut configs,+ &ProviderOverrides {+ base_url: Some("http://localhost:9999/v1".into()),+ headers: vec![("X-Team".into(), "infra".into())],+ ..named("gw")+ },+ );+ assert_eq!(source, Some(("gw".to_string(), OverrideSource::Flag)));+ let gw = configs.get("gw").expect("synthesized");+ assert!(is_cli_reachable(gw));+ assert!(gw.bearer_key_chain().is_empty());+ assert_eq!(gw.custom_headers.len(), 1);+ }++ #[test]+ fn a_base_url_and_headers_reach_only_an_explicit_provider() {+ let mut configs = parse_provider_store(STORE);+ configs.get_mut("openai").unwrap().custom_headers = vec![+ crate::core::state::ProviderCustomHeader {+ header: "X-Team".into(),+ value: "from-config".into(),+ },+ ];+ let overrides = ProviderOverrides {+ provider: Some("openai".into()),+ base_url: Some("https://gateway.example/v1".into()),+ headers: vec![("x-team".into(), "from-env".into())],+ ..Default::default()+ };+ assert_eq!(apply_overrides(&mut configs, &overrides), None);+ let openai = configs.get("openai").unwrap();+ assert_eq!(openai.base_url.as_deref(), Some("https://api.openai.com/v1"));+ assert_eq!(openai.custom_headers[0].value, "from-config");++ let explicit = ProviderOverrides {+ explicit_provider: true,+ ..overrides+ };+ apply_overrides(&mut configs, &explicit);+ let openai = configs.get("openai").unwrap();+ assert_eq!(openai.base_url.as_deref(), Some("https://gateway.example/v1"));+ assert_eq!(openai.custom_headers.len(), 1, "one header per name");+ assert_eq!(openai.custom_headers[0].value, "from-env", "the env beats the config");+ // The key the store held survives a base-URL-only override.+ assert_eq!(openai.api_key, None);+ assert_eq!(+ configs.get("anthropic").unwrap().base_url.as_deref(),+ Some("https://api.anthropic.com/v1"),+ "no other provider moves"+ );+ }++ #[test]+ fn configured_headers_load_from_config_toml() {+ crate::core::agent::global_config::with_temp_home(|home| {+ let dir = home.join(".jan");+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(+ dir.join("config.toml"),+ "[providers.gw]\nbase_url = \"https://gw.example/v1\"\n\+ headers = { \"X-Team\" = \"infra\" }\n",+ )+ .unwrap();+ let configs = load_global_config().unwrap();+ let gw = configs.get("gw").unwrap();+ assert_eq!(gw.custom_headers.len(), 1);+ assert_eq!(gw.custom_headers[0].header, "X-Team");+ // A provider write keeps them.+ crate::core::agent::global_config::set_provider(+ "gw",+ crate::core::agent::global_config::ProviderUpdate {+ models: Some(vec!["m".into()]),+ ..Default::default()+ },+ )+ .unwrap();+ assert_eq!(load_global_config().unwrap()["gw"].custom_headers.len(), 1);+ });+ }++ /// A `/models` stub that also reports each request's head, for asserting+ /// what a listing sent.+ fn capturing_stub(+ body: String,+ connections: usize,+ ) -> (std::net::SocketAddr, std::sync::mpsc::Receiver<String>) {+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let addr = listener.local_addr().unwrap();+ let (tx, rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ for stream in listener.incoming().take(connections) {+ let Ok(mut stream) = stream else { continue };+ let mut buf = [0u8; 8192];+ let n = std::io::Read::read(&mut stream, &mut buf).unwrap_or(0);+ let _ = tx.send(String::from_utf8_lossy(&buf[..n]).to_ascii_lowercase());+ let resp = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",+ body.len(),+ body+ );+ let _ = std::io::Write::write_all(&mut stream, resp.as_bytes());+ }+ });+ (addr, rx)+ }++ fn priced_listing(ids: &[&str]) -> String {+ let data: Vec<serde_json::Value> = ids+ .iter()+ .map(|id| {+ serde_json::json!({+ "id": id,+ "context_length": 200000,+ "pricing": {"prompt": "0.000003", "completion": "0.000015"},+ })+ })+ .collect();+ serde_json::json!({ "data": data }).to_string()+ }++ fn session_tokamak(addr: std::net::SocketAddr) -> ProviderOverrides {+ ProviderOverrides {+ api_key: Some("tk-session".into()),+ base_url: Some(format!("http://{addr}/v1")),+ base_url_source: Some(OverrideSource::Env),+ headers: vec![("X-Client-Name".into(), "jan-agent".into())],+ ..named("tokamak")+ }+ }++ /// Every file under `home` with its bytes, so a test can prove nothing was+ /// written -- byte-identical, not merely "still parses".+ fn home_files(home: &std::path::Path) -> std::collections::BTreeMap<String, Vec<u8>> {+ fn walk(dir: &std::path::Path, out: &mut std::collections::BTreeMap<String, Vec<u8>>) {+ let Ok(entries) = std::fs::read_dir(dir) else { return };+ for entry in entries.flatten() {+ let path = entry.path();+ if path.is_dir() {+ walk(&path, out);+ } else if let Ok(bytes) = std::fs::read(&path) {+ out.insert(path.to_string_lossy().into_owned(), bytes);+ }+ }+ }+ let mut out = std::collections::BTreeMap::new();+ walk(home, &mut out);+ out+ }++ /// The session's key must survive every rebuild of the provider map:+ /// before this it was dropped by the first TUI reload and by the `/model`+ /// probe, which then listed the band with the stored (production) key.+ #[test]+ fn session_overrides_survive_every_rebuild() {+ let (addr, seen) = capturing_stub(priced_listing(&["m-1"]), 1);+ super::super::session_provider::with_session(session_tokamak(addr), |_| {+ assert_eq!(ProviderOverrides::session(), session_tokamak(addr));+ assert!(has_usable_provider(None));+ let configs = load_provider_configs(None, &ProviderOverrides::session()).unwrap();+ assert_eq!(+ configs["tokamak"].bearer_key_chain(),+ vec!["tk-session".to_string()]+ );++ let rt = tokio::runtime::Runtime::new().unwrap();+ rt.block_on(refresh_models_once(None, &mut std::collections::HashSet::new()))+ .expect("probe");+ let request = seen.recv_timeout(Duration::from_secs(10)).expect("listed");+ assert!(request.contains("\r\nauthorization: bearer tk-session\r\n"), "{request}");+ assert!(request.contains("\r\nx-client-name: jan-agent\r\n"), "{request}");+ });+ }++ /// The whole point of the overlay, on a home that has never signed in:+ /// the band's models and prices are usable -- listed, routable by bare id,+ /// priced for a spend cap -- and nothing about them reaches a file.+ #[test]+ fn a_session_scoped_provider_works_on_a_fresh_home_and_writes_nothing() {+ let (addr, _seen) = capturing_stub(priced_listing(&["anthropic/claude-x", "m-2"]), 2);+ super::super::session_provider::with_session(session_tokamak(addr), |home| {+ let before = home_files(home);+ let rt = tokio::runtime::Runtime::new().unwrap();+ let probed = rt.block_on(probe_session_provider(+ None,+ &ProviderOverrides::session(),+ Duration::from_secs(10),+ ));+ assert_eq!(probed, Some(("tokamak".to_string(), Ok(2))));++ let pairs = list_provider_models(None);+ assert!(+ pairs.contains(&("tokamak".to_string(), "m-2".to_string())),+ "the picker lists the band's models: {pairs:?}"+ );+ let configs = load_provider_configs(None, &ProviderOverrides::session()).unwrap();+ assert_eq!(provider_for_model("m-2", &configs).as_deref(), Some("tokamak"));+ let info = super::super::model_catalog::effective();+ assert!(info+ .get(Some("tokamak"), "anthropic/claude-x")+ .and_then(|i| i.rates())+ .is_some());+ let ceiling = super::super::resolve_cost_ceiling(+ Some(1.0),+ None,+ Some("tokamak"),+ "anthropic/claude-x",+ )+ .expect("a priced model can be capped");+ assert!(ceiling.is_some());++ // The first `/model` open re-lists it, into memory again.+ let refreshed = rt+ .block_on(refresh_models_once(None, &mut std::collections::HashSet::new()))+ .expect("probe");+ assert_eq!(refreshed.listed.len(), 1);+ assert_eq!(home_files(home), before, "config.toml and model_catalog.json untouched");+ });+ }++ /// A failed startup probe must price nothing: not at the native entry's+ /// rates for the same id, and not at another provider's, which is what+ /// `Catalog::get` falls through to for a provider it has never seen.+ #[test]+ fn a_failed_startup_probe_prices_nothing() {+ let overrides = ProviderOverrides {+ base_url: Some("http://127.0.0.1:9/v1".into()),+ ..session_tokamak("127.0.0.1:9".parse().unwrap())+ };+ super::super::session_provider::with_session(overrides, |_| {+ let mut catalog = super::super::model_catalog::Catalog::default();+ for provider in ["openrouter", "tokamak"] {+ catalog.set_provider(+ provider,+ super::super::model_catalog::parse_listing(+ &serde_json::from_str(&priced_listing(&["anthropic/claude-x"])).unwrap(),+ ),+ );+ }+ catalog.save().unwrap();++ let rt = tokio::runtime::Runtime::new().unwrap();+ let probed = rt.block_on(probe_session_provider(+ None,+ &ProviderOverrides::session(),+ Duration::from_secs(5),+ ));+ assert!(matches!(probed, Some((_, Err(_)))), "{probed:?}");++ let effective = super::super::model_catalog::effective();+ assert!(effective.get(Some("tokamak"), "anthropic/claude-x").is_none());+ assert!(super::super::model_catalog::load()+ .with_session_overlay()+ .get(Some("tokamak"), "anthropic/claude-x")+ .is_none());+ assert!(super::super::resolve_cost_ceiling(+ Some(1.0),+ None,+ Some("tokamak"),+ "anthropic/claude-x"+ )+ .is_err());+ let configs = load_provider_configs(None, &ProviderOverrides::session()).unwrap();+ assert!(configs["tokamak"].models.is_empty(), "no roster from another endpoint");+ });+ }++ /// The catalog's write paths all start from the disk file, and must stay+ /// that way: a refresh of another provider, a sign-in to it and a sign-out+ /// from it each save the whole catalog, and the session's `tokamak` entry+ /// must not ride along -- absent on a fresh home, the native one otherwise.+ #[test]+ fn another_providers_writes_leave_the_tokamak_catalog_entry_alone() {+ for native in [false, true] {+ let (band, _b) = capturing_stub(priced_listing(&["band-only"]), 1);+ let (other, _o) = capturing_stub(priced_listing(&["gpt-x"]), 1);+ super::super::session_provider::with_session(session_tokamak(band), |home| {+ crate::core::agent::global_config::set_provider(+ "openrouter",+ crate::core::agent::global_config::ProviderUpdate {+ api_key: Some("k".into()),+ base_url: Some(format!("http://{other}/v1")),+ ..Default::default()+ },+ )+ .unwrap();+ if native {+ crate::core::agent::global_config::set_provider(+ "tokamak",+ crate::core::agent::global_config::ProviderUpdate {+ api_key: Some("tk-native".into()),+ base_url: Some("https://api.tokamak.sh/v1".into()),+ models: Some(vec!["native-model".into()]),+ ..Default::default()+ },+ )+ .unwrap();+ let mut catalog = super::super::model_catalog::Catalog::default();+ catalog.set_provider(+ "tokamak",+ super::super::model_catalog::parse_listing(+ &serde_json::from_str(&priced_listing(&["native-model"])).unwrap(),+ ),+ );+ catalog.save().unwrap();+ }+ let tokamak_entry = || {+ let raw = std::fs::read_to_string(home.join(".jan").join("model_catalog.json"))+ .unwrap_or_default();+ serde_json::from_str::<serde_json::Value>(&raw)+ .ok()+ .and_then(|v| v["providers"].get("tokamak").cloned())+ };+ let config_entry = || load_global_config().unwrap().get("tokamak").cloned().map(|c| (c.models, c.base_url, c.api_key));+ let (catalog_before, config_before) = (tokamak_entry(), config_entry());++ let rt = tokio::runtime::Runtime::new().unwrap();+ let refreshed = rt+ .block_on(refresh_models_once(None, &mut std::collections::HashSet::new()))+ .expect("probe");+ assert_eq!(refreshed.listed.len(), 2, "{refreshed:?}");+ // The sign-in to another provider and a sign-out from it.+ super::super::model_catalog::cache_listing(+ "openrouter",+ &serde_json::from_str(&priced_listing(&["gpt-y"])).unwrap(),+ );+ super::super::model_catalog::forget("openrouter");++ assert_eq!(tokamak_entry(), catalog_before, "native={native}");+ assert_eq!(config_entry(), config_before, "native={native}");+ assert_eq!(catalog_before.is_some(), native);+ });+ }+ }++ /// The exception to "only global providers are probed" is the+ /// session-scoped provider alone: a Desktop-inherited or project provider+ /// is still never probed (and so never has its key read from the keychain,+ /// nor a models-only entry written that would shadow it).+ #[test]+ fn desktop_and_project_providers_are_still_not_probed() {+ with_temp_secrets(|| {+ let (band, _seen) = capturing_stub(priced_listing(&["m"]), 1);+ super::super::session_provider::with_session(session_tokamak(band), |home| {+ let store = r#"{"model-provider":"{\"state\":{\"providers\":[{\"provider\":\"desk\",\"base_url\":\"http://127.0.0.1:9/v1\",\"models\":[{\"id\":\"d\"}]}]}}"}"#;+ let data = crate::core::app::commands::resolve_jan_data_folder();+ std::fs::create_dir_all(&data).unwrap();+ std::fs::write(data.join("settings.json"), store).unwrap();+ let project = tempfile::tempdir().unwrap();+ let agent_toml = crate::core::agent::project::agent_toml_path(project.path());+ std::fs::create_dir_all(agent_toml.parent().unwrap()).unwrap();+ std::fs::write(+ &agent_toml,+ "[provider]\nname = \"proj\"\nbase_url = \"http://127.0.0.1:9/v1\"\n",+ )+ .unwrap();+ let before = home_files(home);++ let rt = tokio::runtime::Runtime::new().unwrap();+ let refreshed = rt+ .block_on(refresh_models_once(+ Some(project.path()),+ &mut std::collections::HashSet::new(),+ ))+ .expect("probe");+ let touched: Vec<&str> = refreshed+ .listed+ .iter()+ .map(|p| p.provider.as_str())+ .chain(refreshed.failed.iter().map(|(p, _)| p.as_str()))+ .collect();+ assert_eq!(touched, vec!["tokamak"]);+ assert_eq!(home_files(home), before);+ });+ });+ }++ /// Neither `JAN_API_KEY` alone nor a Desktop-default provider's key makes a+ /// provider session-scoped, so those users keep persisting what a refresh+ /// finds, exactly as before.+ #[test]+ fn keys_that_scope_nothing_still_persist_refresh_results() {+ for overrides in [+ ProviderOverrides {+ api_key: Some("shared".into()),+ ..Default::default()+ },+ ProviderOverrides {+ provider: Some("prov".into()),+ api_key: Some("desktop-default".into()),+ ..Default::default()+ },+ ] {+ let addr = models_stub(serde_json::json!({"data": [{"id": "m-a"}]}).to_string(), 1);+ super::super::session_provider::with_session(overrides, |_| {+ crate::core::agent::global_config::set_provider(+ "prov",+ crate::core::agent::global_config::ProviderUpdate {+ base_url: Some(format!("http://{addr}/v1")),+ models: Some(vec![]),+ ..Default::default()+ },+ )+ .unwrap();+ let rt = tokio::runtime::Runtime::new().unwrap();+ let refreshed = rt+ .block_on(refresh_models_once(None, &mut std::collections::HashSet::new()))+ .expect("probe");+ assert!(refreshed.changed_any());+ assert_eq!(load_global_config().unwrap()["prov"].models, vec!["m-a".to_string()]);+ });+ }+ }++ /// `provider_is_signed_in` asks about an arbitrary provider: the session's+ /// key answers only for the provider it was given for.+ #[test]+ fn the_session_key_signs_in_only_its_own_provider() {+ with_temp_secrets(|| {+ let overrides = ProviderOverrides {+ api_key: Some("sk-or".into()),+ ..named("openrouter")+ };+ super::super::session_provider::with_session(overrides, |_| {+ for name in ["openrouter", "deepseek"] {+ crate::core::agent::global_config::set_provider(+ name,+ crate::core::agent::global_config::ProviderUpdate {+ base_url: Some(format!("https://{name}.example/v1")),+ ..Default::default()+ },+ )+ .unwrap();+ }+ assert!(provider_is_signed_in(None, "openrouter"));+ assert!(!provider_is_signed_in(None, "deepseek"));+ });+ });+ }}diff --git a/src-tauri/src/core/cli/rpc.rs b/src-tauri/src/core/cli/rpc.rsindex bfce65b60..dafb248a9 100644--- a/src-tauri/src/core/cli/rpc.rs+++ b/src-tauri/src/core/cli/rpc.rs@@ -401,6 +401,9 @@ fn rebuild_agent(source: &Session, model: Option<String>) -> Result<AgentSession.project_root.as_deref().ok_or_else(|| "session has no project root".to_owned())?;+ // No session overrides here, on purpose: RPC takes none (an ADK host brings+ // its own provider setup), so its sessions see the configured providers+ // alone. See `session_provider` for the TUI/run/step side.let mut agent = prepare_agent_session(&project.to_string_lossy(),Some(model.unwrap_or_else(|| source.agent.model.clone())),diff --git a/src-tauri/src/core/cli/run_report.rs b/src-tauri/src/core/cli/run_report.rsindex 13468015f..6dda5b79f 100644--- a/src-tauri/src/core/cli/run_report.rs+++ b/src-tauri/src/core/cli/run_report.rs@@ -220,7 +220,7 @@ StreamEvent::TurnUsage {// prices, rather than reported as zero.estimated_cost_usd: self.usage- .cost_usd(super::model_catalog::load().get(provider, model)),+ .cost_usd(super::model_catalog::effective().get(provider, model)),execution_ids: (!self.execution_ids.is_empty()).then(|| self.execution_ids.clone()),},diff --git a/src-tauri/src/core/cli/session_provider.rs b/src-tauri/src/core/cli/session_provider.rsnew file mode 100644index 000000000..ccd560a04--- /dev/null+++ b/src-tauri/src/core/cli/session_provider.rs@@ -0,0 +1,434 @@+//! One CLI session's run-time provider overrides, and the in-memory model+//! roster of its *session-scoped* provider.+//!+//! The overrides (`--provider`, `--api-key`, `--base-url` and their environment+//! fallbacks, see [`ProviderOverrides::with_env`]) are resolved once by the+//! binary and recorded here, so every later rebuild of the provider map -- a+//! TUI reload after `/login`, the `/model` probe, `cli models list` -- applies+//! the same set rather than silently dropping the session's key on the first+//! one. The agent loop never reads this module: it sees only the+//! `ProviderConfig`s built from it, and the desktop does not compile `core::cli`+//! at all.+//!+//! **RPC** installs nothing: `jan cli agent rpc` takes no provider overrides by+//! design, because an ADK host brings its own per session, so its sessions build+//! with `ProviderOverrides::default()`. The `session-overrides` capability+//! describes the TUI, `run` and `step`.+//!+//! **Session-scoped provider.** One named with an explicit `--provider` whose+//! base URL or key came from these overrides+//! ([`ProviderOverrides::session_scoped_provider`]). Its model ids and prices+//! describe the endpoint this session points at, not the one `~/.jan` was+//! written for, so they live here, in memory, and never reach `config.toml` or+//! `model_catalog.json`:+//!+//! - the overlay **replaces** that provider's roster and catalog entries; it+//! never merges with them, since a native entry's ids are ids the session's+//! endpoint may not serve;+//! - once the base URL came from the session, the overlay is authoritative even+//! while empty. A failed probe then leaves no roster and no prices, rather+//! than the file's (another endpoint's) or another provider's for the same id+//! -- a price nobody quoted would meter a spend cap against the wrong rates;+//! - when only the key came from the session, the endpoint is the configured+//! one, so until a probe answers the file's roster and prices still describe+//! it and stay in effect.++use std::collections::{BTreeMap, HashMap};+use std::sync::{Mutex, RwLock};++use super::model_catalog::{Catalog, ModelInfo};+use super::providers::ProviderOverrides;+use crate::core::state::ProviderConfig;++#[derive(Debug, Clone)]+struct State {+ overrides: ProviderOverrides,+ overlay: Option<Overlay>,+}++#[derive(Debug, Clone)]+struct Overlay {+ provider: String,+ /// Whether the file's roster and prices describe this provider's endpoint:+ /// only the key came from the session, not the base URL.+ inherit_disk: bool,+ /// What the endpoint listed, once a probe answered.+ listing: Option<Listing>,+}++#[derive(Debug, Clone, Default, PartialEq)]+struct Listing {+ ids: Vec<String>,+ info: BTreeMap<String, ModelInfo>,+}++static STATE: RwLock<Option<State>> = RwLock::new(None);++/// A one-line report of the startup probe, for a surface that could not print+/// it when it happened (the TUI's alternate screen hides stderr).+static STARTUP_NOTICE: Mutex<Option<String>> = Mutex::new(None);++fn read() -> std::sync::RwLockReadGuard<'static, Option<State>> {+ STATE.read().unwrap_or_else(|e| e.into_inner())+}++fn write() -> std::sync::RwLockWriteGuard<'static, Option<State>> {+ STATE.write().unwrap_or_else(|e| e.into_inner())+}++/// Record `overrides` as the session's, starting an empty overlay for the+/// session-scoped provider when there is one. Replaces anything recorded before.+pub(crate) fn install(overrides: &ProviderOverrides) {+ let overlay = overrides.session_scoped_provider().map(|provider| Overlay {+ provider: provider.to_string(),+ inherit_disk: overrides.base_url.is_none(),+ listing: None,+ });+ *write() = Some(State {+ overrides: overrides.clone(),+ overlay,+ });+}++/// The overrides recorded by [`install`], if any.+pub(crate) fn overrides() -> Option<ProviderOverrides> {+ read().as_ref().map(|state| state.overrides.clone())+}++/// The session-scoped provider, if this session has one.+pub(crate) fn scoped_provider() -> Option<String> {+ read()+ .as_ref()+ .and_then(|state| state.overlay.as_ref())+ .map(|overlay| overlay.provider.clone())+}++/// Whether `provider` is this session's session-scoped provider.+pub(crate) fn is_session_scoped(provider: &str) -> bool {+ scoped_provider().as_deref() == Some(provider)+}++/// Whether Tokamak is the session-scoped provider: its entry and credential+/// then belong to whoever started this session (a launcher), and nothing in+/// the session may sign in to it, out of it, or edit it.+pub(crate) fn tokamak_is_session_scoped() -> bool {+ is_session_scoped(super::tokamak::PROVIDER)+}++/// What a refused Tokamak sign-in change says.+pub(crate) const TOKAMAK_REFUSAL: &str = "this session's Tokamak credential comes from the \+ environment (the launcher); run `jan login` outside it";++/// The session's Tokamak key, when Tokamak is the explicitly named session+/// provider and the key came from the session. Account calls (`/usage`, `auth+/// status`) use this and nothing else from the session: a key given for any+/// other provider, or a `JAN_API_KEY` that reached a Desktop-selected one, is+/// never sent to Tokamak.+pub(crate) fn tokamak_key() -> Option<String> {+ let guard = read();+ let overrides = &guard.as_ref()?.overrides;+ (overrides.explicit_provider_name() == Some(super::tokamak::PROVIDER))+ .then(|| overrides.api_key.clone())+ .flatten()+}++/// The session's Tokamak base URL, under the same rule as [`tokamak_key`].+pub(crate) fn tokamak_base_url() -> Option<String> {+ let guard = read();+ let overrides = &guard.as_ref()?.overrides;+ (overrides.explicit_provider_name() == Some(super::tokamak::PROVIDER))+ .then(|| overrides.base_url.clone())+ .flatten()+}++/// Put the overlay's roster on the session-scoped provider's config. Only for a+/// load made with the session's own overrides naming that provider, so a load+/// with other overrides (RPC's `default()`, a test) sees the files alone.+pub(crate) fn apply_roster(+ configs: &mut HashMap<String, ProviderConfig>,+ overrides: &ProviderOverrides,+) {+ let Some(provider) = overrides.session_scoped_provider() else {+ return;+ };+ let guard = read();+ let Some(overlay) = guard+ .as_ref()+ .and_then(|state| state.overlay.as_ref())+ .filter(|overlay| overlay.provider == provider)+ else {+ return;+ };+ let Some(config) = configs.get_mut(provider) else {+ return;+ };+ match &overlay.listing {+ Some(listing) => config.models = listing.ids.clone(),+ None if !overlay.inherit_disk => config.models.clear(),+ None => {}+ }+}++/// The overlay as a one-provider catalog, when it is authoritative for its+/// provider (see the module docs); `None` when the disk catalog still speaks+/// for it, or there is no session-scoped provider.+pub(crate) fn overlay_catalog() -> Option<(String, BTreeMap<String, ModelInfo>)> {+ let guard = read();+ let overlay = guard.as_ref()?.overlay.as_ref()?;+ match &overlay.listing {+ Some(listing) => Some((overlay.provider.clone(), listing.info.clone())),+ None if !overlay.inherit_disk => Some((overlay.provider.clone(), BTreeMap::new())),+ None => None,+ }+}++/// Lay the overlay over `catalog`, replacing the session-scoped provider's+/// entries -- with an empty map when that is what the overlay holds, so a+/// lookup under that provider finds nothing rather than searching the others.+pub(crate) fn apply_catalog(catalog: &mut Catalog) {+ if let Some((provider, models)) = overlay_catalog() {+ catalog.overlay_provider(&provider, models);+ }+}++/// Store what the session-scoped provider's endpoint listed. `info` empty keeps+/// metadata an earlier answer carried, the rule the disk catalog follows too: an+/// id-only answer says nothing about prices. Returns whether the roster moved.+pub(crate) fn record_listing(+ provider: &str,+ ids: Vec<String>,+ info: BTreeMap<String, ModelInfo>,+) -> bool {+ let mut guard = write();+ let Some(overlay) = guard+ .as_mut()+ .and_then(|state| state.overlay.as_mut())+ .filter(|overlay| overlay.provider == provider)+ else {+ return false;+ };+ let previous = overlay.listing.take().unwrap_or_default();+ let info = if info.is_empty() { previous.info } else { info };+ let changed = previous.ids != ids;+ overlay.listing = Some(Listing { ids, info });+ changed+}++/// Leave a line for the TUI to show once it is on screen.+pub(crate) fn set_startup_notice(notice: String) {+ *STARTUP_NOTICE.lock().unwrap_or_else(|e| e.into_inner()) = Some(notice);+}++/// The startup probe's report, handed out once.+pub(crate) fn take_startup_notice() -> Option<String> {+ STARTUP_NOTICE+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .take()+}++/// Forget everything recorded, for tests: the store is process-wide and the+/// test binary runs every test in one process.+#[cfg(test)]+pub(crate) fn reset() {+ *write() = None;+ STARTUP_NOTICE+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .take();+}++/// Run `f` in a temp home with `overrides` installed as the session's, then+/// reset. Nested inside `with_temp_home` so it is serialized with every other+/// test that touches `~/.jan` -- the provider rebuilds read both.+#[cfg(test)]+pub(crate) fn with_session<T>(+ overrides: ProviderOverrides,+ f: impl FnOnce(&std::path::Path) -> T,+) -> T {+ struct Reset;+ impl Drop for Reset {+ fn drop(&mut self) {+ reset();+ }+ }+ crate::core::agent::global_config::with_temp_home(|home| {+ let _reset = Reset;+ reset();+ overrides.install();+ f(home)+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::core::agent::global_config::{load_global_config, set_provider, ProviderUpdate};+ use crate::core::cli::providers::load_provider_configs;++ fn tokamak(base_url: Option<&str>) -> ProviderOverrides {+ ProviderOverrides {+ provider: Some("tokamak".into()),+ api_key: Some("tk-session".into()),+ base_url: base_url.map(str::to_string),+ explicit_provider: true,+ ..Default::default()+ }+ }++ fn native_tokamak() {+ set_provider(+ "tokamak",+ ProviderUpdate {+ api_key: Some("tk-native".into()),+ base_url: Some("https://api.tokamak.sh/v1".into()),+ models: Some(vec!["native-only".into()]),+ ..Default::default()+ },+ )+ .unwrap();+ let mut catalog = Catalog::default();+ catalog.set_provider(+ "tokamak",+ BTreeMap::from([(+ "native-only".to_string(),+ ModelInfo {+ prompt_usd: Some(1.0),+ completion_usd: Some(2.0),+ ..Default::default()+ },+ )]),+ );+ catalog.save().unwrap();+ }++ /// With the base URL from the session, the file's roster and prices+ /// describe another endpoint: they are replaced, never merged, even before+ /// (or without) an answer from the session's endpoint.+ #[test]+ fn a_session_base_url_replaces_the_native_roster_and_prices() {+ with_session(tokamak(Some("https://api-stag.tokamak.sh/v1")), |_| {+ native_tokamak();+ let configs = load_provider_configs(None, &ProviderOverrides::session()).unwrap();+ assert!(+ configs["tokamak"].models.is_empty(),+ "nothing from the native roster"+ );+ let effective = crate::core::cli::model_catalog::effective();+ assert!(effective.get(Some("tokamak"), "native-only").is_none());++ assert!(record_listing(+ "tokamak",+ vec!["band-only".into()],+ BTreeMap::from([(+ "band-only".to_string(),+ ModelInfo {+ context_length: Some(1000),+ ..Default::default()+ },+ )]),+ ));+ let configs = load_provider_configs(None, &ProviderOverrides::session()).unwrap();+ assert_eq!(configs["tokamak"].models, vec!["band-only".to_string()]);+ let effective = crate::core::cli::model_catalog::effective();+ assert!(effective.get(Some("tokamak"), "band-only").is_some());+ assert!(effective.get(Some("tokamak"), "native-only").is_none());+ // The disk is where it was.+ assert_eq!(+ load_global_config().unwrap()["tokamak"].models,+ vec!["native-only".to_string()]+ );+ assert!(crate::core::cli::model_catalog::load()+ .get(Some("tokamak"), "native-only")+ .is_some());+ });+ }++ /// With only the key from the session the endpoint is the configured one,+ /// so its roster and prices stand until the endpoint says otherwise.+ #[test]+ fn a_session_key_alone_keeps_the_files_roster_until_a_probe_answers() {+ with_session(tokamak(None), |_| {+ native_tokamak();+ let configs = load_provider_configs(None, &ProviderOverrides::session()).unwrap();+ assert_eq!(configs["tokamak"].models, vec!["native-only".to_string()]);+ assert_eq!(+ configs["tokamak"].bearer_key_chain(),+ vec!["tk-session".to_string()]+ );+ assert!(crate::core::cli::model_catalog::effective()+ .get(Some("tokamak"), "native-only")+ .is_some());++ record_listing("tokamak", vec!["listed".into()], BTreeMap::new());+ let configs = load_provider_configs(None, &ProviderOverrides::session()).unwrap();+ assert_eq!(configs["tokamak"].models, vec!["listed".to_string()]);+ });+ }++ /// The overlay applies to a load made with the session's own overrides+ /// only: RPC builds with `default()` and must see the files alone.+ #[test]+ fn a_load_with_other_overrides_sees_only_the_files() {+ with_session(tokamak(Some("https://api-stag.tokamak.sh/v1")), |_| {+ native_tokamak();+ record_listing("tokamak", vec!["band-only".into()], BTreeMap::new());+ let configs = load_provider_configs(None, &ProviderOverrides::default()).unwrap();+ assert_eq!(configs["tokamak"].models, vec!["native-only".to_string()]);+ assert_eq!(+ configs["tokamak"].base_url.as_deref(),+ Some("https://api.tokamak.sh/v1")+ );+ });+ }++ /// An id-only answer keeps the prices an earlier one carried, as the disk+ /// catalog does; a roster change is reported as one.+ #[test]+ fn an_id_only_answer_keeps_earlier_prices() {+ with_session(tokamak(Some("https://api-stag.tokamak.sh/v1")), |_| {+ let priced = BTreeMap::from([(+ "m".to_string(),+ ModelInfo {+ prompt_usd: Some(1.0),+ completion_usd: Some(1.0),+ ..Default::default()+ },+ )]);+ assert!(record_listing("tokamak", vec!["m".into()], priced));+ assert!(!record_listing(+ "tokamak",+ vec!["m".into()],+ BTreeMap::new()+ ));+ assert!(crate::core::cli::model_catalog::effective()+ .get(Some("tokamak"), "m")+ .and_then(|i| i.rates())+ .is_some());+ assert!(+ !record_listing("openrouter", vec!["x".into()], BTreeMap::new()),+ "not ours"+ );+ });+ }++ #[test]+ fn only_an_explicit_session_provider_is_scoped() {+ with_session(+ ProviderOverrides {+ explicit_provider: false,+ ..tokamak(None)+ },+ |_| {+ assert_eq!(scoped_provider(), None);+ assert!(!tokamak_is_session_scoped());+ assert_eq!(tokamak_key(), None);+ },+ );+ with_session(tokamak(None), |_| {+ assert!(tokamak_is_session_scoped());+ assert_eq!(tokamak_key().as_deref(), Some("tk-session"));+ assert_eq!(tokamak_base_url(), None);+ });+ }+}diff --git a/src-tauri/src/core/cli/tokamak.rs b/src-tauri/src/core/cli/tokamak.rsindex d64027f01..1fcf351b5 100644--- a/src-tauri/src/core/cli/tokamak.rs+++ b/src-tauri/src/core/cli/tokamak.rs@@ -41,23 +41,73 @@ pub const BASE_URL: &str = "https://api.tokamak.sh/v1";/// against a dev stack before it reaches production.pub const BASE_URL_ENV: &str = "TOKAMAK_BASE_URL";-/// The API root this run talks to: `$TOKAMAK_BASE_URL` when set, else-/// [`BASE_URL`].+/// The API root this run's account calls (sign-in, `/usage`, `auth status`)+/// talk to, first match wins:+///+/// 1. the session's base URL, when this session named `--provider tokamak` and+/// gave it one (`--base-url` / `JAN_BASE_URL`), so a launched session reads+/// the band it runs on rather than production;+/// 2. `$TOKAMAK_BASE_URL`, with `/v1` appended when it names only a host -- the+/// form the Tokamak CLI itself uses;+/// 3. the stored `[providers.tokamak].base_url`, where the last sign-in went;+/// 4. [`BASE_URL`].pub fn base_url() -> String {- resolve_base_url(std::env::var(BASE_URL_ENV).ok().as_deref())+ resolve_base_url(+ super::session_provider::tokamak_base_url().as_deref(),+ std::env::var(BASE_URL_ENV).ok().as_deref(),+ stored_base_url().as_deref(),+ )}/// Split from [`base_url`] so the precedence is testable without mutating the/// process environment (which every other test in this binary shares).-fn resolve_base_url(from_env: Option<&str>) -> String {- from_env- .map(|v| v.trim().trim_end_matches('/'))+fn resolve_base_url(session: Option<&str>, from_env: Option<&str>, stored: Option<&str>) -> String {+ let clean = |v: &str| v.trim().trim_end_matches('/').to_string();+ session+ .map(clean).filter(|v| !v.is_empty())- .map_or_else(|| BASE_URL.to_string(), str::to_string)+ .or_else(|| {+ from_env+ .map(clean)+ .filter(|v| !v.is_empty())+ .map(|v| with_api_prefix(&v))+ })+ .or_else(|| stored.map(clean).filter(|v| !v.is_empty()))+ .unwrap_or_else(|| BASE_URL.to_string())}-/// Where the user signs in and mints a key.++/// `https://api.tokamak.sh` -> `https://api.tokamak.sh/v1`: a bare origin gets+/// the OpenAI-compatible prefix every caller appends paths to. A URL with any+/// path is taken as given.+fn with_api_prefix(url: &str) -> String {+ match reqwest::Url::parse(url) {+ Ok(parsed) if parsed.path().trim_matches('/').is_empty() => format!("{url}/v1"),+ _ => url.to_string(),+ }+}++fn stored_base_url() -> Option<String> {+ crate::core::agent::global_config::load_global_config()+ .ok()?+ .get(PROVIDER)?+ .base_url+ .clone()+}++/// The production API-keys page. Read through [`api_keys_url`], which follows+/// the deployment this run signs in to.pub const API_KEYS_URL: &str = "https://tokamak.sh/settings/api-keys";+/// Where the user signs in and mints a key, on the web app of the deployment+/// [`base_url`] points at (see [`super::device_auth::web_root`]).+pub fn api_keys_url() -> String {+ api_keys_url_for(&super::device_auth::web_root(&base_url()))+}++fn api_keys_url_for(web_root: &str) -> String {+ format!("{}/settings/api-keys", web_root.trim_end_matches('/'))+}+const VERIFY_TIMEOUT: Duration = Duration::from_secs(20);/// What a successful sign-in changed, for the caller to report.@@ -105,8 +155,11 @@ async fn verify_key(api_key: &str) -> Result<Roster, String> {.build().map_err(|e| e.to_string())?;let root = base_url();- let response = client- .get(format!("{root}/models"))+ let mut request = client.get(format!("{root}/models"));+ for (name, value) in super::providers::listing_headers_for(PROVIDER) {+ request = request.header(name, value);+ }+ let response = request.header("Authorization", format!("Bearer {api_key}")).send().await@@ -121,8 +174,12 @@ async fn verify_key(api_key: &str) -> Result<Roster, String> {.map_err(|e| format!("Tokamak returned a response we could not read: {e}"))?;// The listing carries per-model `context_length` and pricing; caching it// here is what lets `/context` and `/usage` report the real window and an- // actual cost rather than a catalog guess.- super::model_catalog::cache_listing(PROVIDER, &parsed);+ // actual cost rather than a catalog guess. Never for a session-scoped+ // Tokamak: that listing describes the session's endpoint, not the one the+ // cache is kept for.+ if !super::session_provider::tokamak_is_session_scoped() {+ super::model_catalog::cache_listing(PROVIDER, &parsed);+ }Ok(roster_of(&parsed))}@@ -280,6 +337,15 @@ pub async fn logout() -> Result<Logout, String> {})}+/// The key account calls authenticate with: the session's, when this session+/// named `--provider tokamak` with a key; otherwise the stored one. Never the+/// key of any other provider (`--provider openrouter --api-key ...`, or a+/// `JAN_API_KEY` that reached a Desktop-selected provider): that one is not+/// Tokamak's to see.+pub(crate) fn account_api_key() -> Option<String> {+ super::session_provider::tokamak_key().or_else(stored_api_key)+}+fn stored_api_key() -> Option<String> {use crate::core::agent::global_config::load_global_config;load_global_config()@@ -317,12 +383,28 @@ pub struct AuthStatus {pub account: Option<String>,pub key_id: Option<String>,pub key_expires_at: Option<u64>,+ /// Where the key comes from: `"session"` when this session's environment+ /// (a launcher) supplied Tokamak's provider, `"config"` otherwise.+ pub source: &'static str,}/// Read the local auth state for Tokamak.+///+/// While Tokamak is the session-scoped provider, the stored entry says nothing+/// about the credential in use, so none of its metadata (account, key id,+/// expiry) is mixed in: that would describe a different key, possibly for a+/// different deployment.pub fn auth_status() -> AuthStatus {use crate::core::agent::global_config::provider_key_meta;+ if super::session_provider::tokamak_is_session_scoped() {+ return AuthStatus {+ signed_in: account_api_key().is_some(),+ endpoint: base_url(),+ source: "session",+ ..Default::default()+ };+ }let meta = provider_key_meta(PROVIDER).unwrap_or_default();AuthStatus {signed_in: stored_api_key().is_some(),@@ -330,6 +412,7 @@ pub fn auth_status() -> AuthStatus {account: meta.account,key_id: meta.key_id,key_expires_at: meta.key_expires_at,+ source: "config",}}@@ -339,8 +422,13 @@ pub const EXPIRY_WARNING_WINDOW: Duration = Duration::from_secs(7 * 24 * 60 * 60/// A one-line warning when the stored key is expired or about to be. `None` when/// there is no key, no recorded expiry (a legacy paste login records none), or-/// the expiry is comfortably far off.+/// the expiry is comfortably far off -- and while Tokamak is the session-scoped+/// provider, whose key is not the stored one: telling a launched session to run+/// `jan login` would only overwrite the native sign-in to no effect.pub fn expiry_warning() -> Option<String> {+ if super::session_provider::tokamak_is_session_scoped() {+ return None;+ }let expires_at = auth_status().key_expires_at?;describe_expiry(expires_at, unix_now())}@@ -388,11 +476,16 @@ pub fn account() -> Option<String> {/// in), otherwise the pass/fail. A network the CLI cannot reach is reported as/// `None` so a blip does not read as an invalid key.pub async fn live_valid() -> Option<bool> {- use crate::core::agent::global_config::load_global_config;- let key = load_global_config()- .ok()- .and_then(|c| c.get(PROVIDER).cloned())- .and_then(|c| c.api_key)?;+ let key = match super::session_provider::tokamak_key() {+ Some(key) => key,+ None => {+ use crate::core::agent::global_config::load_global_config;+ load_global_config()+ .ok()+ .and_then(|c| c.get(PROVIDER).cloned())+ .and_then(|c| c.api_key)?+ }+ };if key.is_empty() {return Some(false);}@@ -453,7 +546,7 @@ pub(crate) fn parse_models(value: &serde_json::Value) -> Vec<String> {/// unconditionally anyway, since a spawned launcher reports nothing about/// whether a page actually appeared.pub fn open_api_keys_page() -> Result<(), String> {- super::browser::open(API_KEYS_URL)+ super::browser::open(&api_keys_url())}#[cfg(test)]@@ -764,18 +857,62 @@ mod tests {/// an unset/blank var must not produce an empty base url.#[test]fn base_url_prefers_the_env_override() {- assert_eq!(resolve_base_url(None), BASE_URL);- assert_eq!(resolve_base_url(Some("")), BASE_URL);- assert_eq!(resolve_base_url(Some(" ")), BASE_URL);+ assert_eq!(resolve_base_url(None, None, None), BASE_URL);+ assert_eq!(resolve_base_url(None, Some(""), None), BASE_URL);+ assert_eq!(resolve_base_url(None, Some(" "), None), BASE_URL);assert_eq!(- resolve_base_url(Some("https://api.dev.tokamak.sh/v1")),+ resolve_base_url(None, Some("https://api.dev.tokamak.sh/v1"), None),"https://api.dev.tokamak.sh/v1");// A trailing slash would double up in `{base}/models`.assert_eq!(- resolve_base_url(Some(" http://localhost:8080/v1/ ")),+ resolve_base_url(None, Some(" http://localhost:8080/v1/ "), None),+ "http://localhost:8080/v1"+ );+ }++ /// The Tokamak CLI's own `TOKAMAK_BASE_URL` names only the origin; every+ /// caller here appends an OpenAI-compatible path to the base, so a bare+ /// origin gets `/v1` rather than a `/models` that 404s.+ #[test]+ fn a_bare_origin_in_the_env_gets_the_api_prefix() {+ assert_eq!(+ resolve_base_url(None, Some("https://api-stag.tokamak.sh"), None),+ "https://api-stag.tokamak.sh/v1"+ );+ assert_eq!(+ resolve_base_url(None, Some("http://localhost:8080/"), None),"http://localhost:8080/v1");+ // A path of any kind is taken as given.+ assert_eq!(+ resolve_base_url(None, Some("https://gw.example/tokamak/v1"), None),+ "https://gw.example/tokamak/v1"+ );+ }++ /// Account calls go where the session runs, then where the environment+ /// points, then where the last sign-in went -- never to production just+ /// because nothing said otherwise.+ #[test]+ fn base_url_precedence_is_session_env_stored_default() {+ let session = Some("https://api-stag.tokamak.sh/v1");+ let env = Some("https://api-dev.tokamak.sh");+ let stored = Some("https://api.self-hosted.example/v1/");+ assert_eq!(resolve_base_url(session, env, stored), "https://api-stag.tokamak.sh/v1");+ assert_eq!(resolve_base_url(None, env, stored), "https://api-dev.tokamak.sh/v1");+ assert_eq!(resolve_base_url(None, None, stored), "https://api.self-hosted.example/v1");+ assert_eq!(resolve_base_url(None, None, None), BASE_URL);+ }++ /// The keys page is on the web app of the deployment signed in to.+ #[test]+ fn the_keys_page_follows_the_web_root() {+ assert_eq!(api_keys_url_for("https://tokamak.sh"), API_KEYS_URL);+ assert_eq!(+ api_keys_url_for("https://stag.tokamak.sh/"),+ "https://stag.tokamak.sh/settings/api-keys"+ );}/// The warning window is the point of storing `key_expires_at` at all: a@@ -866,4 +1003,135 @@ mod tests {assert!(!auth_status().signed_in);});}++ // ── Account calls under session overrides ───────────────────────────────++ fn session(provider: &str, explicit: bool, base_url: Option<String>) -> super::super::providers::ProviderOverrides {+ super::super::providers::ProviderOverrides {+ provider: Some(provider.to_string()),+ api_key: Some(format!("{provider}-session-key")),+ base_url,+ explicit_provider: explicit,+ ..Default::default()+ }+ }++ /// Only a session that named `--provider tokamak` may hand its key to+ /// Tokamak's account API. `--provider openrouter --api-key ...` and a key+ /// that reached a Desktop-selected `tokamak` by default both fall back to+ /// the stored Tokamak key.+ #[test]+ fn account_calls_use_the_session_key_only_for_an_explicit_tokamak() {+ use super::super::session_provider::with_session;+ let stored = || persist("tk-stored", roster(&["m"])).expect("persist");+ with_session(session("openrouter", true, None), |_| {+ stored();+ assert_eq!(account_api_key().as_deref(), Some("tk-stored"));+ assert_eq!(auth_status().source, "config");+ });+ with_session(session("tokamak", false, None), |_| {+ stored();+ assert_eq!(account_api_key().as_deref(), Some("tk-stored"));+ });+ with_session(+ session("tokamak", true, Some("https://api-stag.tokamak.sh/v1".into())),+ |_| {+ stored();+ assert_eq!(account_api_key().as_deref(), Some("tokamak-session-key"));+ assert_eq!(base_url(), "https://api-stag.tokamak.sh/v1");+ },+ );+ }++ /// Against a live endpoint: the key that reaches `/usage` is Tokamak's own,+ /// never the one a session was given for another provider.+ #[test]+ fn usage_never_carries_another_providers_key() {+ use super::super::session_provider::with_session;+ fn stub() -> (std::net::SocketAddr, std::sync::mpsc::Receiver<String>) {+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let addr = listener.local_addr().unwrap();+ let (tx, rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ let Ok((mut stream, _)) = listener.accept() else { return };+ let mut buf = [0u8; 8192];+ let n = std::io::Read::read(&mut stream, &mut buf).unwrap_or(0);+ let _ = tx.send(String::from_utf8_lossy(&buf[..n]).to_ascii_lowercase());+ let body = "{}";+ let _ = std::io::Write::write_all(+ &mut stream,+ format!(+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ )+ .as_bytes(),+ );+ });+ (addr, rx)+ }+ let fetch = || {+ tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap()+ .block_on(usage::fetch(&usage::Query::Summary))+ .expect("usage")+ };++ let (addr, seen) = stub();+ with_session(session("openrouter", true, None), |_| {+ crate::core::agent::global_config::set_provider(+ PROVIDER,+ ProviderUpdate {+ api_key: Some("tk-stored".into()),+ base_url: Some(format!("http://{addr}/v1")),+ ..Default::default()+ },+ )+ .unwrap();+ fetch();+ let request = seen.recv().unwrap();+ assert!(request.contains("authorization: bearer tk-stored\r\n"), "{request}");+ assert!(!request.contains("openrouter-session-key"), "{request}");+ });++ let (addr, seen) = stub();+ with_session(session("tokamak", true, Some(format!("http://{addr}/v1"))), |_| {+ fetch();+ let request = seen.recv().unwrap();+ assert!(+ request.contains("authorization: bearer tokamak-session-key\r\n"),+ "{request}"+ );+ });+ }++ /// While the session provides Tokamak, the stored entry describes some+ /// other key: none of its metadata may be reported, and its expiry must not+ /// tell a launched session to run `jan login`.+ #[test]+ fn a_session_tokamak_reports_its_own_source_and_no_stored_expiry() {+ use super::super::session_provider::with_session;+ let soon = unix_now() + 2 * 24 * 60 * 60;+ with_session(+ session("tokamak", true, Some("https://api-stag.tokamak.sh/v1".into())),+ |_| {+ persist_minted(&minted(Some("k-native"), Some(soon)), roster(&[])).expect("persist");+ let status = auth_status();+ assert!(status.signed_in);+ assert_eq!(status.source, "session");+ assert_eq!(status.endpoint, "https://api-stag.tokamak.sh/v1");+ assert_eq!(status.key_id, None);+ assert_eq!(status.key_expires_at, None);+ assert_eq!(status.account, None);+ assert_eq!(expiry_warning(), None);+ },+ );+ // The same stored key outside such a session still warns.+ with_temp_home(|_| {+ persist_minted(&minted(Some("k-native"), Some(soon)), roster(&[])).expect("persist");+ assert!(expiry_warning().is_some());+ assert_eq!(auth_status().source, "config");+ });+ }}diff --git a/src-tauri/src/core/cli/tokamak/usage.rs b/src-tauri/src/core/cli/tokamak/usage.rsindex 85fe813b9..b3fb3decc 100644--- a/src-tauri/src/core/cli/tokamak/usage.rs+++ b/src-tauri/src/core/cli/tokamak/usage.rs@@ -377,12 +377,14 @@ impl Query {/// Perform `query` against the configured Tokamak deployment and return the raw/// body.///-/// Honours `TOKAMAK_BASE_URL` through [`super::base_url`], so a dev stack is-/// reachable without a rebuild, and shapes failures through the same-/// [`super::describe_failure`] the sign-in path uses -- one voice for upstream-/// problems regardless of which endpoint hit them.+/// Honours `TOKAMAK_BASE_URL` (and a launched session's own Tokamak endpoint)+/// through [`super::base_url`], so a dev stack is reachable without a rebuild,+/// and shapes failures through the same [`super::describe_failure`] the sign-in+/// path uses -- one voice for upstream problems regardless of which endpoint+/// hit them. The key is [`super::account_api_key`]: the session's only when the+/// session named Tokamak, so another provider's key never reaches this API.pub async fn fetch(query: &Query) -> Result<Payload, UsageError> {- let api_key = super::stored_api_key().ok_or(UsageError::NotSignedIn)?;+ let api_key = super::account_api_key().ok_or(UsageError::NotSignedIn)?;let client = reqwest::Client::builder().timeout(USAGE_TIMEOUT).build()diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 81ea23a58..362baca87 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -912,14 +912,14 @@ enum LoginStage {impl LoginStage {/// The page this stage would send the user to, while that is still unasked.- fn unconfirmed_url(&self) -> Option<&str> {+ fn unconfirmed_url(&self) -> Option<String> {match self {Self::Approving {authorize_url,confirm_open: true,..- } => Some(authorize_url),- Self::Paste { confirm_open: true } => Some(super::tokamak::API_KEYS_URL),+ } => Some(authorize_url.clone()),+ Self::Paste { confirm_open: true } => Some(super::tokamak::api_keys_url()),_ => None,}}@@ -979,7 +979,7 @@ impl LoginPrompt {crate::core::cli::auth::provider_by_id(&self.provider).map(|provider| provider.api_key.keys_url.to_string())}- _ => self.stage.unconfirmed_url().map(str::to_string),+ _ => self.stage.unconfirmed_url(),}}@@ -2222,6 +2222,10 @@ struct App {/// on every bare `/model` -- that would freeze the render loop for the whole/// request timeout -- so only unprobed providers are fetched once.probed_models: std::collections::HashSet<String>,+ /// Whether `--model` named the model this session started on. A resumed+ /// thread then keeps it rather than switching to the model the thread+ /// was saved with: the flag is the more explicit, more recent choice.+ model_pinned: bool,/// Key handed off to the loop to verify off the render loop. Taken once.login_submit: Option<(String, String)>,/// Active OAuth account prompt; owns the keyboard while open.@@ -2831,6 +2835,7 @@ impl App {mcp_auth_cancel: false,provider_prompt: None,probed_models: std::collections::HashSet::new(),+ model_pinned: false,login_submit: None,plugin_setup: None,plugin_setup_queue: Default::default(),@@ -5125,10 +5130,22 @@ impl App {fn set_model(&mut self, model: String) {self.model = model;self.refresh_context_window();+ // A model the session-scoped provider serves is this session's choice+ // only: its id names the session's endpoint, and saving it would start+ // the next native `jan` in this project on a model nothing it has+ // configured may serve.+ let session_only = self+ .serving_provider()+ .as_deref()+ .is_some_and(super::session_provider::is_session_scoped);// Persistence warning preserved verbatim from the prior behaviour.- let persistence = match super::cli_set_project_model(&self.agent_dir, &self.model) {- Ok(()) => String::new(),- Err(e) => format!(" (not saved: {e})"),+ let persistence = if session_only {+ " (this session only)".to_string()+ } else {+ match super::cli_set_project_model(&self.agent_dir, &self.model) {+ Ok(()) => String::new(),+ Err(e) => format!(" (not saved: {e})"),+ }};self.note(&format!("model set to {} (context {}K, {}){}",@@ -6829,7 +6846,7 @@ impl UsageKey {fn session_cost(usage: &std::collections::BTreeMap<UsageKey, super::model_catalog::TokenUsage>,) -> Option<(f64, bool)> {- let catalog = super::model_catalog::load();+ let catalog = super::model_catalog::effective();let mut total = 0.0;let mut priced = false;let mut unpriced = false;@@ -6873,7 +6890,7 @@ fn usage_lines(usage: &std::collections::BTreeMap<UsageKey, super::model_catalog::TokenUsage>,all_models: bool,) -> Vec<Vec<Span<'static>>> {- let catalog = super::model_catalog::load();+ let catalog = super::model_catalog::effective();let mut rows: Vec<UsageRow> = Vec::new();let mut totals = super::model_catalog::TokenUsage::default();let mut total_cost = 0.0;@@ -9774,6 +9791,7 @@ pub async fn run(mcp_task,workspace,workspace_note,+ model_pinned,} = session;let ask_requests = crate::core::agent::interaction::new_registry();args.ask_requests = Some(ask_requests.clone());@@ -9848,6 +9866,7 @@ pub async fn run(repo_root,);app.set_workspace(workspace);+ app.model_pinned = model_pinned;app.smol_model = smol_model;app.stream_reasoning = stream_reasoning;app.send_reasoning = send_reasoning;@@ -9878,6 +9897,11 @@ pub async fn run(if let Some(note) = super::take_migration_notice() {app.note(¬e);}+ // The startup model listing ran before the alternate screen, where a+ // failure printed to stderr would be wiped by the first frame.+ if let Some(note) = super::session_provider::take_startup_notice() {+ app.note(¬e);+ }if let Some(note) = workspace_note {app.note(¬e);}@@ -11987,6 +12011,10 @@ async fn handle_key(// The watermark row: nothing to delete.return;}+ if tokamak_change_refused(&name) {+ app.note(super::session_provider::TOKAMAK_REFUSAL);+ return;+ }let sel = picker.selected;if picker.armed_delete == Some(sel) {// Second `d` on the same row confirms the delete.@@ -12011,6 +12039,9 @@ async fn handle_key(if name.is_empty() {return;}+ if refuse_tokamak_change(app, &name) {+ return;+ }sign_out_provider(app, &name);}// `/todo` editor: d/Enter = done, x = abandon (drop), r = remove.@@ -12085,6 +12116,9 @@ async fn handle_key(// for a provider that is currently signed in.KeyCode::Char('x') if picker.kind == PickerKind::LoginProvider => {let name = picker.items[picker.selected].value.clone();+ if refuse_tokamak_change(app, &name) {+ return;+ }if !crate::core::cli::providers::provider_is_signed_in(Some(&app.project_root),&name,@@ -12158,6 +12192,9 @@ async fn handle_key(resume_thread(app, &value).await}PickerKind::LoginProvider => {+ if refuse_tokamak_change(app, &value) {+ return;+ }if crate::core::cli::auth::account::AccountProvider::from_credential_provider(&value).is_some(){@@ -12201,6 +12238,9 @@ async fn handle_key(}// `/settings > providers`: open the wizard for the row.PickerKind::ProviderSettings => {+ if refuse_tokamak_change(app, &value) {+ return;+ }let entry = crate::core::agent::global_config::load_global_config().ok().and_then(|c| c.get(&value).cloned());@@ -14290,6 +14330,13 @@ impl ProviderPrompt {if name.is_empty() {return Err("provider name is required".to_string());}+ // The add wizard takes any name, and `set_provider` merges into an+ // existing entry: `tokamak` here would overwrite (or create) the entry+ // a launched session must leave alone.+ if name == super::tokamak::PROVIDER && super::session_provider::tokamak_is_session_scoped()+ {+ return Err(super::session_provider::TOKAMAK_REFUSAL.to_string());+ }if let Some(err) = self.validate_base_url() {return Err(err);}@@ -16480,7 +16527,11 @@ fn login_command(app: &mut App, arg: &str) {return;}match arg.split_whitespace().next() {- Some("--paste-token" | "--paste") => open_login_prompt(app, "tokamak"),+ Some("--paste-token" | "--paste") => {+ if !refuse_tokamak_change(app, super::tokamak::PROVIDER) {+ open_login_prompt(app, "tokamak")+ }+ }Some(other) => app.note(&format!("/login: unknown option {other} (try --paste-token)")),@@ -16492,6 +16543,9 @@ fn login_command(app: &mut App, arg: &str) {/// there is something to Esc out of while the session is being created, and/// `chat_loop` picks the request up off the render loop.fn open_login(app: &mut App) {+ if refuse_tokamak_change(app, super::tokamak::PROVIDER) {+ return;+ }app.login = Some(LoginPrompt::connecting());app.login_device_request = true;}@@ -16614,10 +16668,34 @@ fn open_browser(url: &str) -> Result<(), String> {.map_err(|_| "could not open the browser".to_string())}+/// Refuse a change to the Tokamak entry or its credential while Tokamak is the+/// session-scoped provider -- the credential in use then comes from whoever+/// started the session, and a sign-in, sign-out or edit here would only rewrite+/// the user's native Tokamak setup (or orphan a live key) while the session+/// carried on with the launcher's. `true` when refused; the note says why.+/// Other providers are never refused.+fn refuse_tokamak_change(app: &mut App, provider: &str) -> bool {+ if tokamak_change_refused(provider) {+ app.note(super::session_provider::TOKAMAK_REFUSAL);+ return true;+ }+ false+}++/// The predicate behind [`refuse_tokamak_change`], for a caller still holding a+/// borrow into `App` (a picker row) when it asks.+fn tokamak_change_refused(provider: &str) -> bool {+ provider.trim() == super::tokamak::PROVIDER+ && super::session_provider::tokamak_is_session_scoped()+}+fn logout_command(app: &mut App, provider: &str) {if provider.trim().is_empty() {return app.note("usage: /logout <provider>");}+ if refuse_tokamak_change(app, provider) {+ return;+ }let owned_model = crate::core::agent::global_config::load_global_config().ok().and_then(|configs| configs.get(provider).cloned())@@ -16645,6 +16723,9 @@ fn sign_out_provider(app: &mut App, provider: &str) {}fn open_login_prompt(app: &mut App, provider: &str) {+ if refuse_tokamak_change(app, provider) {+ return;+ }let Some(definition) = crate::core::cli::auth::provider_by_id(provider) else {return app.note("selected provider is unavailable");};@@ -16823,6 +16904,16 @@ fn adopt_account_login_model(app: &mut App, provider: &str) {adopt_login_model(app, &login);}fn adopt_login_model(app: &mut App, login: &crate::core::cli::auth::LoginResult) {+ // Signing in to another provider inside a session served by its+ // session-scoped provider (a launched session) must not move the session+ // off it, nor write the other provider's model into agent.toml.+ if app+ .serving_provider()+ .as_deref()+ .is_some_and(super::session_provider::is_session_scoped)+ {+ return;+ }let runnable = super::providers::list_provider_models(Some(&app.project_root));if runnable.iter().any(|(_, model)| *model == app.model) {return;@@ -16847,9 +16938,12 @@ async fn reload_provider_configs(app: &mut App) {return;};let project_root = app.project_root.clone();+ // The session's own overrides, so a key or base URL given on the command+ // line or in the environment survives the reload instead of being dropped+ // for whatever the files say.match super::providers::load_provider_configs(Some(&project_root),- &super::providers::ProviderOverrides::default().with_env(),+ &super::providers::ProviderOverrides::session(),) {Ok(configs) => {*args.provider_configs.lock().await = configs;@@ -17933,11 +18027,15 @@ async fn load_thread(app: &mut App, thread: &serde_json::Value, verb: &str) {}}- // Adopt the thread's model so continuation stays coherent.+ // Adopt the thread's model so continuation stays coherent -- unless+ // `--model` named one: resuming under an explicit model is asking to+ // continue this conversation *on that model*, and a launcher that pins its+ // provider's model must not be moved off it by a thread saved elsewhere.if let Some(model) = thread.get("model").and_then(|m| m.get("id")).and_then(|v| v.as_str())+ .filter(|_| !app.model_pinned){app.model = model.to_string();}@@ -19043,10 +19141,11 @@ fn login_prompt_lines(prompt: &LoginPrompt, width: u16) -> Vec<Line<'static>> {],LoginStage::Paste { .. } => {let keys_url = crate::core::cli::auth::provider_by_id(&prompt.provider)- .map_or("", |provider| provider.api_key.keys_url);+ .map(|provider| provider.api_key.keys_url)+ .unwrap_or_default();vec![Span::styled("get a key at ", dim),- Span::styled(keys_url.to_string(), Style::new().cyan()),+ Span::styled(keys_url, Style::new().cyan()),]}};@@ -25997,7 +26096,7 @@ mod tests {let prompt = app.login.as_ref().unwrap();assert_eq!(prompt.stage.unconfirmed_url(),- Some(crate::core::cli::tokamak::API_KEYS_URL)+ Some(crate::core::cli::tokamak::api_keys_url()));let screen = render_rows(&mut app, 80, 24).join("\n");assert!(@@ -26009,7 +26108,7 @@ mod tests {let mut app = test_app();super::show_login_approval(&mut app, &test_session());assert_eq!(- app.login.as_ref().unwrap().stage.unconfirmed_url(),+ app.login.as_ref().unwrap().stage.unconfirmed_url().as_deref(),Some("https://tokamak.sh/cli/authorize?code=ABCD-2345"));let screen = render_rows(&mut app, 80, 24).join("\n");@@ -41657,4 +41756,254 @@ mod tests {"throbber still present in {row:?}");}++ // ── Session-scoped providers (gateway launches) ─────────────────────────++ /// A resumed thread keeps the model `--model` named: a launcher pins its+ /// provider's model, and a thread saved elsewhere must not move it off.+ #[tokio::test]+ async fn resuming_under_an_explicit_model_keeps_it() {+ let app = test_app();+ let history = vec![json!({ "role": "user", "content": "hi" })];+ super::super::cli_save_thread(&app.agent_dir, None, "saved-model", &history, None).unwrap();++ let mut pinned = test_app();+ pinned.agent_dir = app.agent_dir.clone();+ pinned.model = "tokamak/claude-x".into();+ pinned.model_pinned = true;+ apply_resume(&mut pinned, &ResumeRequest::resume(ResumeTarget::Latest)).await;+ assert!(pinned.thread_id.is_some(), "the thread was resumed");+ assert_eq!(pinned.model, "tokamak/claude-x");++ let mut unpinned = test_app();+ unpinned.agent_dir = app.agent_dir.clone();+ apply_resume(&mut unpinned, &ResumeRequest::resume(ResumeTarget::Latest)).await;+ assert_eq!(unpinned.model, "saved-model", "without --model the thread's model wins");+ }++ /// `with_isolated_login_state`, with Tokamak installed as the session-scoped+ /// provider for its duration.+ fn with_session_tokamak<T>(f: impl FnOnce() -> T) -> T {+ struct Reset;+ impl Drop for Reset {+ fn drop(&mut self) {+ super::super::session_provider::reset();+ }+ }+ with_isolated_login_state(|| {+ let _reset = Reset;+ super::super::session_provider::reset();+ super::super::providers::ProviderOverrides {+ provider: Some("tokamak".into()),+ api_key: Some("tk-session".into()),+ base_url: Some("https://api-stag.tokamak.sh/v1".into()),+ explicit_provider: true,+ ..Default::default()+ }+ .install();+ f()+ })+ }++ /// A native sign-in the launched session must leave exactly as it was.+ fn seed_native_tokamak() -> Vec<u8> {+ use crate::core::cli::auth::{Credential, CredentialStore};+ CredentialStore::store("tokamak", &Credential::ApiKey("tk-native".into())).unwrap();+ crate::core::agent::global_config::set_provider(+ "tokamak",+ crate::core::agent::global_config::ProviderUpdate {+ api_key: Some("tk-native".into()),+ base_url: Some("https://api.tokamak.sh/v1".into()),+ models: Some(vec!["native-model".into()]),+ ..Default::default()+ },+ )+ .unwrap();+ std::fs::read(crate::core::agent::global_config::global_config_path().unwrap()).unwrap()+ }++ fn assert_native_tokamak_untouched(before: &[u8], sink: &str) {+ let after =+ std::fs::read(crate::core::agent::global_config::global_config_path().unwrap()).unwrap();+ assert_eq!(after, before, "{sink}: config.toml must be byte-identical");+ assert!(+ crate::core::cli::auth::CredentialStore::load("tokamak")+ .unwrap()+ .is_some(),+ "{sink}: the stored Tokamak credential must survive"+ );+ }++ /// Whether the refusal was said, however the transcript wrapped it.+ fn refused(app: &App) -> bool {+ let text = transcript_text(app);+ let flat = text+ .split_whitespace()+ .filter(|word| *word != "•")+ .collect::<Vec<_>>()+ .join(" ");+ flat.contains(super::super::session_provider::TOKAMAK_REFUSAL)+ }++ #[test]+ fn a_session_tokamak_refuses_login_paste_token() {+ with_session_tokamak(|| {+ let before = seed_native_tokamak();+ let mut app = test_app();+ let rt = tokio::runtime::Runtime::new().unwrap();+ rt.block_on(run_command(&mut app, "login --paste-token", &no_mcp()));+ assert!(app.login.is_none(), "no key field opens");+ assert!(refused(&app), "{}", transcript_text(&app));+ assert_native_tokamak_untouched(&before, "/login --paste-token");+ });+ }++ #[test]+ fn a_session_tokamak_refuses_the_login_pickers_enter_and_x() {+ with_session_tokamak(|| {+ let before = seed_native_tokamak();+ let rt = tokio::runtime::Runtime::new().unwrap();++ let mut app = test_app();+ super::open_login_picker(&mut app);+ assert_eq!(app.picker.as_ref().unwrap().items[0].value, "tokamak");+ rt.block_on(press(&mut app, KeyCode::Enter, KeyModifiers::NONE));+ assert!(app.login.is_none() && !app.login_device_request, "no sign-in starts");+ assert!(refused(&app), "Enter: {}", transcript_text(&app));++ let mut app = test_app();+ super::open_login_picker(&mut app);+ rt.block_on(press(&mut app, KeyCode::Char('x'), KeyModifiers::NONE));+ assert!(refused(&app), "x: {}", transcript_text(&app));+ assert_native_tokamak_untouched(&before, "/login picker");+ });+ }++ #[test]+ fn a_session_tokamak_refuses_logout_but_not_for_other_providers() {+ with_session_tokamak(|| {+ let before = seed_native_tokamak();+ let rt = tokio::runtime::Runtime::new().unwrap();++ let mut app = test_app();+ rt.block_on(run_command(&mut app, "logout", &no_mcp()));+ assert!(transcript_text(&app).contains("usage: /logout <provider>"));+ rt.block_on(run_command(&mut app, "logout tokamak", &no_mcp()));+ assert!(refused(&app), "{}", transcript_text(&app));+ assert_native_tokamak_untouched(&before, "/logout tokamak");++ rt.block_on(run_command(&mut app, "logout openai", &no_mcp()));+ assert!(transcript_text(&app).contains("signed out of openai"));+ });+ }++ #[test]+ fn a_session_tokamak_refuses_the_provider_settings_x_d_and_edit() {+ with_session_tokamak(|| {+ let before = seed_native_tokamak();+ let rt = tokio::runtime::Runtime::new().unwrap();+ for code in [KeyCode::Char('x'), KeyCode::Char('d'), KeyCode::Enter] {+ let mut app = test_app();+ super::open_provider_settings(&mut app);+ assert_eq!(app.picker.as_ref().unwrap().items[0].value, "tokamak");+ rt.block_on(press(&mut app, code, KeyModifiers::NONE));+ if code == KeyCode::Char('d') {+ // A second `d` would confirm a delete: it must not either.+ rt.block_on(press(&mut app, code, KeyModifiers::NONE));+ }+ assert!(app.provider_prompt.is_none(), "{code:?}: no edit form opens");+ assert!(refused(&app), "{code:?}: {}", transcript_text(&app));+ assert_native_tokamak_untouched(&before, &format!("/settings > providers {code:?}"));+ }+ });+ }++ /// The add wizard's name is free text, and saving merges into an existing+ /// entry: `tokamak` there would overwrite the native one.+ #[test]+ fn a_session_tokamak_refuses_the_add_wizard_named_tokamak() {+ with_session_tokamak(|| {+ let before = seed_native_tokamak();+ let mut app = test_app();+ let mut prompt = super::ProviderPrompt::new();+ prompt.name = "tokamak".into();+ prompt.base_url = "https://evil.example/v1".into();+ prompt.api_key = "sk-other".into();+ app.provider_prompt = Some(prompt);+ let rt = tokio::runtime::Runtime::new().unwrap();+ rt.block_on(press(&mut app, KeyCode::Enter, KeyModifiers::NONE));+ let prompt = app.provider_prompt.as_ref().expect("the form stays open on the refusal");+ assert_eq!(+ prompt.error.as_deref(),+ Some(super::super::session_provider::TOKAMAK_REFUSAL)+ );+ assert_native_tokamak_untouched(&before, "/settings > providers add");++ // Any other name still saves.+ let mut other = super::ProviderPrompt::new();+ other.name = "mine".into();+ other.base_url = "https://mine.example/v1".into();+ assert!(other.save().is_ok());+ });+ }++ /// Signing in to another provider inside a launched session neither moves+ /// the session off its provider nor writes that provider's model into+ /// agent.toml; a `/model` pick the session provider serves is not saved+ /// either.+ #[test]+ fn a_session_served_by_its_own_provider_stays_there() {+ with_session_tokamak(|| {+ let mut app = test_app();+ let mut configs = std::collections::HashMap::new();+ configs.insert(+ "tokamak".to_string(),+ crate::core::state::ProviderConfig {+ provider: "tokamak".into(),+ base_url: Some("https://api-stag.tokamak.sh/v1".into()),+ api_key: Some("tk-session".into()),+ models: vec!["band-model".into()],+ ..Default::default()+ },+ );+ app.args = Some(test_args(&app, configs));+ app.model = "tokamak/band-model".into();+ let agent_toml = app.agent_dir.join("agent.toml");++ super::adopt_login_model(+ &mut app,+ &crate::core::cli::auth::LoginResult {+ provider: "openai".into(),+ models: vec!["gpt-x".into()],+ config_path: std::path::PathBuf::new(),+ default_model: Some("gpt-x".into()),+ },+ );+ assert_eq!(app.model, "tokamak/band-model");+ assert!(!agent_toml.exists(), "no agent.toml write");++ app.set_model("band-model".into());+ assert!(!agent_toml.exists(), "a session-provider pick is not persisted");+ assert!(transcript_text(&app).contains("(this session only)"));+ });+ }++ /// The reload after a sign-in rebuilds the provider map with the session's+ /// overrides, so the launcher's key and base URL survive it.+ #[test]+ fn a_reload_keeps_the_session_key_and_base_url() {+ with_session_tokamak(|| {+ seed_native_tokamak();+ let mut app = test_app();+ let args = test_args(&app, std::collections::HashMap::new());+ app.args = Some(args.clone());+ let rt = tokio::runtime::Runtime::new().unwrap();+ rt.block_on(super::reload_provider_configs(&mut app));+ let map = rt.block_on(args.provider_configs.lock());+ let tokamak = map.get("tokamak").expect("present");+ assert_eq!(tokamak.bearer_key_chain(), vec!["tk-session".to_string()]);+ assert_eq!(tokamak.base_url.as_deref(), Some("https://api-stag.tokamak.sh/v1"));+ assert!(tokamak.models.is_empty(), "not the native roster");+ });+ }}