Initial public release

Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
Evan Whittaker
2026-10-17 12:08:30 -05:00
commit 09a7de2520
1730 changed files with 412952 additions and 0 deletions

View File

@@ -0,0 +1,345 @@
//! Configuration loading — auth/models, permissions, command hooks, and env resolution.
//!
//! Every reader treats its file as read-if-present: a missing or malformed config degrades to
//! defaults rather than failing, so Luxe runs the same with or without user config.
use std::path::PathBuf;
use luxe_providers::config::ModelsConfig;
/// The API-key environment variables a provider answers to, most specific first.
///
/// The provider catalog is the source of truth; an unrecognized provider falls back to
/// `OPENAI_API_KEY`, which is what an unknown OpenAI-compatible endpoint is most likely
/// authenticated by.
pub(crate) fn provider_key_env(provider: &str) -> &'static [&'static str] {
match luxe_providers::auth::provider_descriptor(provider) {
Some(descriptor) => descriptor.env,
None => &["OPENAI_API_KEY"],
}
}
/// A non-empty environment variable value, or `None`.
pub(crate) fn env_nonempty(key: &str) -> Option<String> {
std::env::var(key).ok().filter(|s| !s.trim().is_empty())
}
/// Path to the on-disk models.dev catalog cache (`~/.cache/luxe/models-dev.json`).
///
/// Derived data, so it lives in the cache dir rather than next to the user's config; deleting it
/// only costs a refresh. `LUXE_MODELS_DEV_PATH` points at a specific file instead (a mirror, an
/// air-gapped copy, or a pinned catalog for reproducible runs).
pub(crate) fn models_dev_cache_path() -> PathBuf {
if let Some(path) = env_nonempty("LUXE_MODELS_DEV_PATH") {
return PathBuf::from(path);
}
luxe_core::user_dirs::luxe_cache_dir().join("models-dev.json")
}
/// Load and merge `~/.config/luxe/auth.json` (nested schema) with `models.json`.
///
/// `models.json` overrides win: its `models`/`providers` entries replace matching keys and
/// its `default_*` fields override when set.
pub(crate) fn load_luxe_config() -> ModelsConfig {
let auth_path = luxe_core::user_dirs::luxe_config_file("auth.json");
let models_path = luxe_core::user_dirs::luxe_config_file("models.json");
// Nudge (once) if a secrets file is group/world-readable — parity with ssh/aws-cli.
static WARN_ONCE: std::sync::Once = std::sync::Once::new();
WARN_ONCE.call_once(|| {
warn_if_loose_perms(&auth_path);
warn_if_loose_perms(&models_path);
});
let mut config = read_json_config(&auth_path).unwrap_or_default();
if let Some(models) = read_json_config(&models_path) {
config.models.extend(models.models);
config.providers.extend(models.providers);
if models.default_provider.is_some() {
config.default_provider = models.default_provider;
}
if models.default_model.is_some() {
config.default_model = models.default_model;
}
}
config
}
/// Warn if a secrets file is readable by group or other.
///
/// Luxe writes its own secret files `0600` (MCP token store, review stores), but `auth.json`/
/// `models.json` are user-authored, so we can only nudge: ssh and aws-cli take the same stance
/// (warn/refuse on loose credential permissions). Unix-only; a no-op elsewhere.
#[cfg(unix)]
pub(crate) fn warn_if_loose_perms(path: &std::path::Path) {
use std::os::unix::fs::PermissionsExt;
let Ok(meta) = std::fs::metadata(path) else { return };
let mode = meta.permissions().mode() & 0o777;
if perms_are_loose(mode) {
tracing::warn!(
path = %path.display(),
mode = format!("{mode:#o}"),
"secrets file is readable by group/other; run `chmod 600` on it"
);
}
}
#[cfg(not(unix))]
pub(crate) fn warn_if_loose_perms(_path: &std::path::Path) {}
/// A file mode is "loose" for a secret if any group/other bit is set.
#[cfg(unix)]
pub(crate) fn perms_are_loose(mode: u32) -> bool {
mode & 0o077 != 0
}
/// Load command hooks (external commands run at agent-loop hook points).
///
/// Trust: the *global* `~/.config/luxe/hooks.json` is always honored; a project's
/// `.luxe/hooks.json` is loaded ONLY under `--trust-project`. A hook runs an arbitrary command,
/// so honoring project hooks by default would let a cloned repo execute code on the next tool
/// call — the same footgun as malicious git hooks. Returns `None` when no hooks are configured.
pub(crate) fn load_command_hooks(
repo_root: &std::path::Path,
trust_project: bool,
) -> Option<luxe_core::command_hooks::CommandHook> {
use luxe_core::command_hooks::{CommandHook, HooksFile};
let parse = |path: std::path::PathBuf| -> HooksFile {
let file = match std::fs::read_to_string(&path) {
Ok(text) => HooksFile::from_json(&text).unwrap_or_else(|e| {
tracing::warn!(path = %path.display(), error = %e, "ignoring malformed hooks.json");
HooksFile::default()
}),
Err(_) => HooksFile::default(),
};
// A key naming no hook point is the one failure a user cannot see: the hook is simply
// never called, on the machine where it matters. Say so, and say what they probably meant.
for key in &file.unknown_points {
match luxe_core::hook::HookPoint::closest(key) {
Some(nearest) => tracing::warn!(
path = %path.display(),
point = %key,
did_you_mean = %nearest,
"ignoring hook at an unknown hook point"
),
None => tracing::warn!(
path = %path.display(),
point = %key,
"ignoring hook at an unknown hook point"
),
}
}
file
};
let mut merged = parse(luxe_config_dir().join("hooks.json")).hooks;
if trust_project {
for (point, defs) in parse(repo_root.join(".luxe").join("hooks.json")).hooks {
merged.entry(point).or_default().extend(defs);
}
}
let hook =
CommandHook::new(HooksFile { hooks: merged, unknown_points: Vec::new() }.into_specs());
(!hook.is_empty()).then_some(hook)
}
/// Assemble the permission engine from config + CLI intent.
///
/// Layers, trusted-first: built-in defaults + the mode overlay + the global
/// `~/.config/luxe/permissions.json`; then the project-local `.luxe/permissions.json` as a
/// **tighten-only** overlay (it can raise strictness but not weaken the baseline) unless
/// `--trust-project`, which merges it freely. Mode precedence: CLI override > global file >
/// (project file only when trusted) > `Default`. A missing/malformed file is skipped.
pub(crate) fn load_permission_engine(
repo_root: &std::path::Path,
mode_override: Option<luxe_core::permission::PermissionMode>,
trust_project: bool,
) -> luxe_core::permission::PermissionEngine {
use luxe_core::permission::PermissionEngine;
let (global, project) = permission_files(repo_root);
let mode = resolve_mode(mode_override, &global, &project, trust_project);
PermissionEngine::assemble(mode, global.ruleset(), project.ruleset(), trust_project)
}
/// The permission mode this run is in, by the same precedence [`load_permission_engine`] uses.
///
/// For a decision the permission engine does not make itself: `--rpc` refusing GitHub writes in a
/// read-only session, which has to see a `"mode": "read-only"` in the global file exactly as the
/// engine does.
pub(crate) fn effective_permission_mode(
repo_root: &std::path::Path,
mode_override: Option<luxe_core::permission::PermissionMode>,
trust_project: bool,
) -> luxe_core::permission::PermissionMode {
let (global, project) = permission_files(repo_root);
resolve_mode(mode_override, &global, &project, trust_project)
}
/// The global and project permissions files, each empty when missing or malformed.
fn permission_files(
repo_root: &std::path::Path,
) -> (luxe_core::permission::PermissionsFile, luxe_core::permission::PermissionsFile) {
use luxe_core::permission::PermissionsFile;
let read_file = |path: std::path::PathBuf| -> PermissionsFile {
match std::fs::read_to_string(&path) {
Ok(text) => PermissionsFile::from_json(&text).unwrap_or_else(|e| {
tracing::warn!(path = %path.display(), error = %e, "ignoring malformed permissions.json");
PermissionsFile::default()
}),
Err(_) => PermissionsFile::default(),
}
};
(
read_file(global_permissions_path()),
read_file(repo_root.join(".luxe").join("permissions.json")),
)
}
/// CLI override, then the global file, then the project file when trusted, then `Default`.
fn resolve_mode(
mode_override: Option<luxe_core::permission::PermissionMode>,
global: &luxe_core::permission::PermissionsFile,
project: &luxe_core::permission::PermissionsFile,
trust_project: bool,
) -> luxe_core::permission::PermissionMode {
mode_override
.or_else(|| global.mode())
.or_else(|| trust_project.then(|| project.mode()).flatten())
.unwrap_or_default()
}
/// Parse a JSON config file into [`ModelsConfig`], returning `None` when absent/invalid.
pub(crate) fn read_json_config(path: &std::path::Path) -> Option<ModelsConfig> {
if !path.exists() {
return None;
}
match luxe_providers::config::load_models_config(path) {
Ok(c) => Some(c),
Err(e) => {
tracing::warn!(path = %path.display(), error = %e, "ignoring malformed config");
None
}
}
}
/// The global permissions file (`~/.config/luxe/permissions.json`).
///
/// The only file a "remember this" approval may be written to: a project-local ruleset is
/// tighten-only, so an approval stored there would never take effect.
pub(crate) fn global_permissions_path() -> PathBuf {
luxe_config_dir().join("permissions.json")
}
/// Luxe's own config directory. See [`luxe_core::user_dirs::luxe_config_dir`], the one owner.
pub(crate) fn luxe_config_dir() -> PathBuf {
luxe_core::user_dirs::luxe_config_dir()
}
/// Whether an env var is explicitly set to a falsy value (`0`/`false`/`no`/`off`). Used for
/// default-on features that can be turned off.
pub(crate) fn env_disabled(key: &str) -> bool {
std::env::var(key)
.map(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "0" | "false" | "no" | "off"))
.unwrap_or(false)
}
/// A short, stable hash of the repo path for session directory naming.
pub(crate) fn project_hash(path: &std::path::Path) -> String {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
path.hash(&mut hasher);
format!("{:016x}", hasher.finish())
}
#[cfg(test)]
mod tests {
use super::*;
/// Every file the guide's table says lives in the config directory resolves under
/// `LUXE_CONFIG_DIR`, through the code that actually reads it. A new row has to join the map,
/// so a file added to the guide cannot be left behind by the override.
///
/// The break this catches: three resolvers, and core's ignored the variable, so `auth.json`
/// and `models.json` moved while `config.json`, `themes/`, `skills/` and the rest stayed put.
#[test]
fn the_override_moves_every_file_in_the_config_directory() {
let _env =
crate::engine_setup::test_env::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let previous = std::env::var_os("LUXE_CONFIG_DIR");
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path().join("profile");
std::fs::create_dir_all(&root).expect("profile dir");
std::env::set_var("LUXE_CONFIG_DIR", &root);
let cwd = PathBuf::from("/tmp/luxe-config-all-project");
let contains = |paths: Vec<PathBuf>, name: &str| paths.contains(&root.join(name));
let resolved = |name: &str| -> bool {
match name {
"config.json" => luxe_core::config::Config::global_path() == root.join(name),
"keybindings.json" => luxe_core::keymap::keybindings_path() == root.join(name),
"models.json" => {
luxe_providers::auth::config_file::ConfigFile::default_path().path()
== root.join(name)
}
"auth.json" => {
luxe_providers::auth::AuthStore::default_path().path() == root.join(name)
}
"permissions.json" => global_permissions_path() == root.join(name),
"hooks.json" => {
let hooks = r#"{ "BeforeToolUse": [ { "command": ["true"] } ] }"#;
std::fs::write(root.join(name), hooks).expect("hooks.json");
let read = load_command_hooks(&cwd, false).is_some();
// and only that file: gone, there is nothing, whatever the machine's own says
std::fs::remove_file(root.join(name)).expect("hooks.json removed");
read && load_command_hooks(&cwd, false).is_none()
}
"mcp.json" => contains(luxe_core::mcp_config::McpConfigStore::sources(&cwd), name),
"lsp-servers.json" => {
luxe_core::config::Config::lsp_servers_path() == root.join(name)
}
"debug-adapters.json" => {
luxe_core::config::Config::debug_adapters_path() == root.join(name)
}
"agents.md" => luxe_core::instructions::global_context_file() == root.join(name),
"themes/" => luxe_core::theme::user_themes_dir() == root.join("themes"),
"skills/" => contains(luxe_core::skills::skill_dirs(&cwd), "skills"),
other => panic!("the guide lists `{other}`; add how it resolves to this map"),
}
};
let guide = include_str!("../guide.md");
let table = guide.split("| File | Holds | In a project |").nth(1).expect("the files table");
let names: Vec<&str> = table
.lines()
.skip(2)
.take_while(|line| line.starts_with('|'))
.filter_map(|line| line.split('`').nth(1))
.collect();
assert!(names.len() >= 12, "the table parsed: {names:?}");
let left_behind: Vec<&str> = names.iter().copied().filter(|name| !resolved(name)).collect();
let shown = luxe_core::user_dirs::config_path_display("x.json");
assert_eq!(shown, luxe_core::paths::home_relative(&root.join("x.json")));
match previous {
Some(value) => std::env::set_var("LUXE_CONFIG_DIR", value),
None => std::env::remove_var("LUXE_CONFIG_DIR"),
}
assert!(left_behind.is_empty(), "these stayed behind: {left_behind:?}");
}
/// `LUXE_STATE_DIR` moves the state record and the MCP tokens together, not just the record.
#[test]
fn the_state_override_moves_every_state_file() {
let _env =
crate::engine_setup::test_env::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let previous = std::env::var_os("LUXE_STATE_DIR");
let root = PathBuf::from("/tmp/luxe-state-all");
std::env::set_var("LUXE_STATE_DIR", &root);
let record = luxe_core::runtime_state::RuntimeState::path();
let tokens = luxe_mcp::token_store::TokenStore::default_path().path().to_path_buf();
match previous {
Some(value) => std::env::set_var("LUXE_STATE_DIR", value),
None => std::env::remove_var("LUXE_STATE_DIR"),
}
assert_eq!(record, root.join("state.json"));
assert_eq!(tokens, root.join("mcp-auth.json"));
}
}

View File

@@ -0,0 +1,176 @@
//! The reviewer, assembled from configuration — for the loop's phase gate and for `/review`.
//!
//! Two stages gate a claimed phase, both opt-in: the acceptance commands from `gate.commands`, and a
//! reviewer when `gate.review` says so (on by default once `reviewer.model` is named). With neither
//! configured a claim is taken at its word, which is what a loop that has not been told how to check
//! itself deserves. `/review` asks the same reviewer on demand, in any session.
//!
//! Either way the reviewer is an engine of its own, in a fresh session, so it judges the change
//! without the reasoning that produced it. It runs on `reviewer.model` when one is named and on the
//! session's model otherwise: the fresh context is most of what a review is worth, and a second
//! vendor's blind spots are a bonus for whoever has one.
use std::sync::Arc;
use luxe_core::phase_gate::PhaseReviewContext;
use luxe_core::phase_review::{PhaseReviewOutcome, PhaseReviewRequest, PhaseReviewer};
use super::AgentSettings;
#[cfg(test)]
mod tests;
pub(crate) fn phase_gate_config(settings: &AgentSettings) -> luxe_core::config::Config {
luxe_core::config::Config::load_trusted(&settings.state_root, settings.trust_project)
}
/// The gate a claimed phase has to clear, assembled from config.
pub(crate) async fn build_phase_gate(
settings: &AgentSettings,
controller: Arc<luxe_core::loop_controller::LoopController>,
) -> Arc<luxe_core::phase_gate::PhaseGate> {
let config = phase_gate_config(settings);
let mut gate = luxe_core::phase_gate::PhaseGate::new();
let commands = config.gate.commands();
if commands.is_empty() {
tracing::info!("no acceptance commands configured for the phase gate");
} else {
tracing::info!(count = commands.len(), "acceptance commands configured");
gate = gate.with_commands(Arc::new(
luxe_core::hooks::review_gate::ReviewGateHook::with_commands(commands)
.with_timeout(config.gate.timeout()),
));
}
if config.gate.reviews(&config.reviewer) {
if let Some((reviewer, context)) = build_reviewer(settings, &config, controller).await {
gate = gate.with_reviewer(reviewer, context);
}
} else {
tracing::info!("no reviewer for the phase gate (gate.review)");
}
Arc::new(gate)
}
/// The reviewer `/review` asks, started the first time it is asked.
pub(crate) fn on_demand_review(
settings: &AgentSettings,
config: &luxe_core::config::Config,
) -> luxe_core::engine::OnDemandReview {
let review_settings = reviewer_settings(settings, config);
luxe_core::engine::OnDemandReview {
label: review_settings.launch_model().r#ref.to_string(),
reviewer: Arc::new(LazyReviewer {
settings: review_settings,
agent: tokio::sync::OnceCell::new(),
}),
context: Arc::new(
crate::phase_review_context::WorktreeReviewContext::new(settings.work_root.clone())
.whole_plan(),
),
}
}
/// The settings a review engine is built from: the session's, on the reviewer's model.
///
/// The reviewer's model brings its provider's own credential, base URL and compat flags with it
/// (`for_model`); without one named, the review runs on the session's model, provider and all.
fn reviewer_settings(
settings: &AgentSettings,
config: &luxe_core::config::Config,
) -> AgentSettings {
let reviewer = &config.reviewer;
let mut review_settings = match (reviewer.model.as_deref(), reviewer.model_ref()) {
(Some(_), Some((provider, id))) => {
let catalog = super::load_luxe_config();
settings.for_model(crate::model_catalog::resolve_model(&catalog, provider, id).0)
}
(Some(raw), None) => {
tracing::warn!(model = %raw, "ignoring a reviewer.model that is not `provider/id`");
settings.clone()
}
(None, _) => settings.clone(),
};
if reviewer.thinking.is_some() {
review_settings.initial_thinking = reviewer.thinking;
}
// A review is not a loop iteration and not a session anyone resumes: no `loop_control`, a
// fresh session each time, and the reviewer's own read-only mode and tools
review_settings.loop_driven = false;
review_settings.resume = super::ResumeMode::New;
review_settings.review_engine = true;
review_settings.initial_mode = None;
review_settings.carryover = None;
// The issue's brief and the startup notices are the session's, not the reviewer's
review_settings.issue = None;
review_settings.pull_request = None;
review_settings.startup_notices.clear();
review_settings
}
/// The reviewer half of the phase gate.
async fn build_reviewer(
settings: &AgentSettings,
config: &luxe_core::config::Config,
controller: Arc<luxe_core::loop_controller::LoopController>,
) -> Option<(Arc<dyn PhaseReviewer>, Arc<dyn PhaseReviewContext>)> {
let review_settings = reviewer_settings(settings, config);
let model = review_settings.launch_model().r#ref.to_string();
if review_settings.launch_model().r#ref == settings.launch_model().r#ref {
tracing::info!(%model, "the reviewer runs on the loop's own model, in a fresh context");
}
match crate::review_agent::ReviewAgent::spawn(review_settings).await {
Ok(agent) => {
tracing::info!(%model, "the phase gate has a reviewer");
Some((
Arc::new(agent),
Arc::new(
crate::phase_review_context::WorktreeReviewContext::new(
settings.work_root.clone(),
)
.anchored_to(controller),
),
))
}
Err(error) => {
// A gate with no reviewer is the documented, safe state: the acceptance commands still
// run and a claim is judged on them.
tracing::warn!(%error, "could not start the reviewer; the gate is its commands only");
None
}
}
}
/// A reviewer whose engine is started the first time a review is asked for.
///
/// Most sessions never ask, and a review engine is a session file and a provider adapter that
/// would otherwise be made for every one of them.
struct LazyReviewer {
settings: AgentSettings,
agent: tokio::sync::OnceCell<Result<crate::review_agent::ReviewAgent, String>>,
}
impl std::fmt::Debug for LazyReviewer {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.debug_struct("LazyReviewer").finish_non_exhaustive()
}
}
#[async_trait::async_trait]
impl PhaseReviewer for LazyReviewer {
async fn review(&self, request: PhaseReviewRequest) -> PhaseReviewOutcome {
let started = self
.agent
.get_or_init(|| async {
crate::review_agent::ReviewAgent::spawn(self.settings.clone())
.await
.map_err(|error| format!("the reviewer could not start: {error}"))
})
.await;
match started {
Ok(agent) => agent.review(request).await,
Err(reason) => PhaseReviewOutcome::Unavailable(reason.clone()),
}
}
}

View File

@@ -0,0 +1,55 @@
use super::*;
use luxe_core::phase_gate::GateOutcome;
fn project_with_gate_command() -> (tempfile::TempDir, tempfile::TempDir, std::path::PathBuf) {
let home = tempfile::tempdir().unwrap();
std::env::set_var("XDG_CONFIG_HOME", home.path());
std::fs::create_dir_all(home.path().join("luxe")).unwrap();
std::fs::write(home.path().join("luxe/config.json"), "{}").unwrap();
let project = tempfile::tempdir().unwrap();
std::fs::create_dir_all(project.path().join(".luxe")).unwrap();
let marker = project.path().join("gate-ran");
std::env::set_var("LUXE_GATE_TEST_MARKER", &marker);
let command = vec![
luxe_core::paths::display(&std::env::current_exe().unwrap()),
"--exact".into(),
"engine_setup::phase_reviewer::tests::gate_marker_child".into(),
"--ignored".into(),
];
let config = serde_json::json!({"gate": {"commands": [command], "review": false}});
std::fs::write(project.path().join(".luxe/config.json"), config.to_string()).unwrap();
(home, project, marker)
}
#[test]
#[ignore = "subprocess fixture for the project gate trust test"]
fn gate_marker_child() {
let marker =
std::env::var_os("LUXE_GATE_TEST_MARKER").expect("parent supplies the marker path");
std::fs::write(marker, "trusted").unwrap();
}
/// The actual phase gate must not execute a project's command until the CLI grants trust.
#[tokio::test]
async fn a_project_gate_command_runs_only_with_explicit_trust() {
std::env::remove_var(luxe_core::hooks::review_gate::RECURSION_GUARD_ENV);
let (_home, project, marker) = project_with_gate_command();
let mut settings = AgentSettings::resolve(project.path().to_path_buf(), Default::default());
let controller = Arc::new(luxe_core::loop_controller::LoopController::new(
project.path().join("loop_state.json"),
project.path().join("STOP"),
));
let gate = build_phase_gate(&settings, controller.clone()).await;
let outcome = gate.run(0, "test", &|_| {}).await;
assert!(matches!(outcome, GateOutcome::Passed), "{outcome:?}");
assert!(!marker.exists(), "an untrusted project command must never execute");
assert!(phase_gate_config(&settings).gate.commands().is_empty());
settings.trust_project = true;
let gate = build_phase_gate(&settings, controller).await;
let outcome = gate.run(0, "test", &|_| {}).await;
assert!(matches!(outcome, GateOutcome::Passed), "{outcome:?}");
assert!(marker.exists(), "explicit trust must enable the project command");
assert_eq!(phase_gate_config(&settings).gate.commands().len(), 1);
std::env::remove_var("XDG_CONFIG_HOME");
std::env::remove_var("LUXE_GATE_TEST_MARKER");
}

View File

@@ -0,0 +1,198 @@
//! Provider adapter construction — the active adapter plus a registry of every provider Luxe can
//! route to, so an in-session model switch or a mid-session `/login` reaches the right backend.
use std::collections::HashMap;
use std::sync::Arc;
use luxe_core::auth::ApiKind;
use luxe_core::provider::{ModelInfo, Provider};
use luxe_providers::auth::{provider_descriptor, AuthSource, AuthStore, StoreAuth};
use luxe_providers::config::{
resolve_api, resolve_key_style, resolve_value, CompatFlags, ProviderConfig,
};
use super::config::{load_luxe_config, provider_key_env};
use super::AgentSettings;
/// The compat flags a provider runs with.
///
/// One line, because the answer belongs where a model's own keys are merged over it — the adapter
/// and the model metadata have to agree about what the provider's flags are.
pub(crate) fn resolve_compat(provider_name: &str, config: Option<&ProviderConfig>) -> CompatFlags {
luxe_providers::config::resolve_provider_compat(provider_name, config)
}
/// The base URL a provider runs against: the user's config, else the catalog's default, else the
/// adapter's own.
pub(crate) fn resolve_base_url(
provider_name: &str,
config: Option<&ProviderConfig>,
) -> Option<String> {
config
.and_then(|config| config.base_url.clone())
.map(|url| resolve_value(&url))
.filter(|url| !url.trim().is_empty())
.or_else(|| {
provider_descriptor(provider_name)
.and_then(|descriptor| descriptor.base_url)
.map(str::to_string)
})
}
/// Build one provider adapter.
///
/// The representative `model` only matters for Anthropic's build-time `max_tokens` fallback; every
/// adapter honors the per-request model, so an in-session `SetModel` swap changes the id without a
/// rebuild. Auth is resolved *per request* from `auth`, so a token can refresh and a fresh `/login`
/// takes effect without rebuilding anything either.
/// `LUXE_WIRE_LOG` wraps every adapter here, so the recorder sees the default provider, the
/// per-provider registry, and any mid-session switch — one seam instead of one per call site.
pub(crate) fn build_provider_adapter(
api: ApiKind,
model: ModelInfo,
auth: Arc<dyn AuthSource>,
base_url: Option<String>,
compat: CompatFlags,
) -> Arc<dyn Provider + Send + Sync> {
luxe_providers::wire::RecordingProvider::wrap(luxe_providers::config::build_adapter(
api, model, auth, base_url, compat,
))
}
/// The active provider's adapter, with the key named for this run, if any, over the store.
pub(crate) fn build_active_adapter(settings: &AgentSettings) -> Arc<dyn Provider + Send + Sync> {
let config = load_luxe_config();
let provider_config = config.providers.get(&settings.provider);
let api = resolve_api(&settings.provider, provider_config);
build_provider_adapter(
api,
settings.launch_model(),
active_auth(settings, provider_config),
settings.base_url.clone().or_else(|| resolve_base_url(&settings.provider, provider_config)),
settings.compat.clone(),
)
}
/// The active provider's auth source: the key named for this run, if any, over the same chain
/// every other provider uses.
pub(super) fn active_auth(
settings: &AgentSettings,
provider_config: Option<&ProviderConfig>,
) -> Arc<dyn AuthSource> {
provider_auth(AuthStore::default_path(), &settings.provider, provider_config)
.with_override(settings.api_key.clone())
.into_arc()
}
/// How a provider finds its key when none was named for this run: what you signed in with, then
/// the provider's own variable, then the key its block names.
///
/// One chain for the provider a session starts on and every one it can switch to, so the key that
/// goes out never depends on how the session got there. A provider Luxe does not know has no
/// variable of its own, only the `OPENAI_API_KEY` fallback, so its configured key comes first: an
/// OpenAI key must not go to someone else's endpoint in place of the key written for it. Keys stay
/// as written; the source expands them per request.
fn provider_auth(store: AuthStore, name: &str, config: Option<&ProviderConfig>) -> StoreAuth {
let configured = config
.and_then(|config| config.api_key.clone())
.filter(|key| !key.expose().trim().is_empty());
let auth = StoreAuth::new(store, name, resolve_api(name, config))
.with_key_style(Some(resolve_key_style(name, config)));
match (provider_descriptor(name), configured) {
(None, None) => {
auth.with_env(provider_key_env(name).iter().map(|v| v.to_string()).collect())
}
(_, configured) => auth.with_fallback(configured),
}
}
/// Assemble the provider registry the engine routes through on an in-session model switch.
///
/// Every provider Luxe knows about is registered: the built-in catalog plus anything declared in
/// `~/.config/luxe/{auth,models}.json`. That is what makes `/login` take effect mid-session — the
/// adapter is already there, and its store-backed auth source finds the new credential on the next
/// turn. A provider with no credential registers too, and answers with an actionable auth error
/// rather than a 401.
pub(crate) fn build_provider_registry(
settings: &AgentSettings,
active: &Arc<dyn Provider + Send + Sync>,
) -> HashMap<String, Arc<dyn Provider + Send + Sync>> {
let mut registry: HashMap<String, Arc<dyn Provider + Send + Sync>> = HashMap::new();
registry.insert(settings.provider.clone(), active.clone());
let config = load_luxe_config();
let store = AuthStore::default_path();
let catalog_ids = luxe_providers::auth::provider_descriptors()
.iter()
.filter(|descriptor| descriptor.id != "custom")
.map(|descriptor| descriptor.id.to_string());
let configured_ids = config.providers.keys().cloned();
for name in catalog_ids.chain(configured_ids) {
if registry.contains_key(&name) {
continue;
}
let provider_config = config.providers.get(&name);
let api = resolve_api(&name, provider_config);
// No override here: the CLI's `--api-key` was meant for the active provider, not for every
// provider the registry can reach.
let auth = provider_auth(store.clone(), &name, provider_config);
// A placeholder model: every adapter honors the per-request model, so this only supplies
// Anthropic's build-time `max_tokens` fallback.
let (model, _) = crate::model_catalog::resolve_model(&config, &name, "");
let adapter = build_provider_adapter(
api,
model,
auth.into_arc(),
resolve_base_url(&name, provider_config),
resolve_compat(&name, provider_config),
);
registry.insert(name, adapter);
}
registry
}
/// A `--model` that names its provider, `anthropic/claude-opus-5-5`, split into the two.
///
/// Only when the prefix is a provider Luxe knows, built in or configured, and no other provider
/// was named: under `--provider openrouter`, `anthropic/claude-x` is OpenRouter's own id, slash and
/// all. Without the split the whole string went to the default provider as an id, which is the
/// form the "no model selected" error tells you to type.
pub(super) fn split_model_ref(
model: &str,
named_provider: Option<&str>,
config: &luxe_providers::config::ModelsConfig,
) -> (Option<String>, String) {
let Some((prefix, id)) = model.split_once('/') else { return (None, model.to_string()) };
let known = luxe_providers::auth::provider_descriptor(prefix).is_some()
|| config.providers.contains_key(prefix);
let canonical = luxe_providers::auth::canonical_id;
let agrees = named_provider.is_none_or(|named| canonical(named) == canonical(prefix));
if known && agrees && !id.is_empty() {
let provider = named_provider.map_or_else(|| prefix.to_string(), str::to_string);
(Some(provider), id.to_string())
} else {
(None, model.to_string())
}
}
/// Whether `provider` can serve `model`, as far as anything knows before a request is made.
///
/// Deliberately permissive: it only rejects a pairing the provider catalog *names* as unserved (a
/// subscription backend with a fixed model list), or a model configured for a different provider
/// entirely. An unknown provider or an unlisted model is allowed through — the endpoint is the real
/// authority, and refusing a valid model would be worse than passing an invalid one to it.
pub(super) fn provider_serves(provider: &str, model: &str, configured_for: Option<&str>) -> bool {
if let Some(configured_for) = configured_for {
if !luxe_providers::auth::canonical_id(configured_for)
.eq(&luxe_providers::auth::canonical_id(provider))
{
return false;
}
}
luxe_providers::auth::provider_descriptor(provider)
.is_none_or(|descriptor| descriptor.served_models.serves(model))
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,360 @@
use super::*;
use luxe_providers::config::ApiKey;
#[test]
fn the_catalog_decides_which_adapter_a_known_provider_uses() {
assert_eq!(resolve_api("anthropic", None), ApiKind::AnthropicMessages);
assert_eq!(resolve_api("openai", None), ApiKind::OpenaiResponses);
assert_eq!(resolve_api("openai-codex", None), ApiKind::OpenaiCodex);
assert_eq!(resolve_api("groq", None), ApiKind::OpenaiCompletions);
// Luxe's historical default provider name is an alias of `openai`.
assert_eq!(resolve_api("openai_compat", None), ApiKind::OpenaiResponses);
// An unknown provider is assumed to speak the most common dialect.
assert_eq!(resolve_api("some-proxy", None), ApiKind::OpenaiCompletions);
}
#[test]
fn an_explicit_api_in_config_wins_over_the_catalog() {
let pinned = ProviderConfig { api: Some("openai-completions".into()), ..Default::default() };
assert_eq!(resolve_api("openai", Some(&pinned)), ApiKind::OpenaiCompletions);
// An unparseable value falls through rather than failing the launch.
let nonsense = ProviderConfig { api: Some("carrier-pigeon".into()), ..Default::default() };
assert_eq!(resolve_api("openai", Some(&nonsense)), ApiKind::OpenaiResponses);
}
/// The pre-catalog way of asking for `/responses` has to keep working for a user who set it.
#[test]
fn the_legacy_compat_flag_still_selects_the_responses_api() {
let legacy = ProviderConfig {
compat: CompatFlags { use_responses_api: true, ..Default::default() },
..Default::default()
};
assert_eq!(resolve_api("my-proxy", Some(&legacy)), ApiKind::OpenaiResponses);
}
#[test]
fn base_urls_and_compat_fall_back_to_the_catalog() {
assert_eq!(
resolve_base_url("anthropic", None).as_deref(),
Some("https://api.anthropic.com/v1")
);
assert!(resolve_compat("anthropic", None).cache_control_format.is_some());
// A user's own values win.
let mine = ProviderConfig {
base_url: Some("https://proxy.local/v1".into()),
compat: CompatFlags::default(),
..Default::default()
};
assert_eq!(
resolve_base_url("anthropic", Some(&mine)).as_deref(),
Some("https://proxy.local/v1")
);
assert!(resolve_compat("anthropic", Some(&mine)).cache_control_format.is_none());
// An unknown provider with no config has no base URL; the adapter's own default applies.
assert!(resolve_base_url("mystery", None).is_none());
}
/// One header's value out of a raw request head, by exact name.
fn header_value(request: &str, name: &str) -> Option<String> {
request.lines().skip(1).take_while(|line| !line.trim().is_empty()).find_map(|line| {
let (header, value) = line.split_once(':')?;
header.trim().eq_ignore_ascii_case(name).then(|| value.trim().to_string())
})
}
/// Accepts one request, hands back its head, and answers with `body`.
fn serve_once(body: &'static str) -> (u16, std::sync::mpsc::Receiver<String>) {
serve(body, 1)
}
/// Accepts `count` requests in turn, handing back each head and answering each with `body`.
fn serve(body: &'static str, count: usize) -> (u16, std::sync::mpsc::Receiver<String>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
let port = listener.local_addr().expect("addr").port();
let (send, receive) = std::sync::mpsc::channel();
std::thread::spawn(move || {
for _ in 0..count {
answer(&listener, body, &send);
}
});
(port, receive)
}
/// Accepts one request on `listener`, sends its head to `heads`, and answers with `body`.
fn answer(listener: &std::net::TcpListener, body: &str, heads: &std::sync::mpsc::Sender<String>) {
use std::io::{Read, Write};
let (mut socket, _) = listener.accept().expect("accept");
let mut seen = Vec::new();
let mut chunk = [0u8; 4096];
// Read until the blank line that ends the head; the body follows on the same read.
while !seen.windows(4).any(|window| window == b"\r\n\r\n") {
match socket.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(read) => seen.extend_from_slice(&chunk[..read]),
}
}
let _ = heads.send(String::from_utf8_lossy(&seen).to_string());
let head = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n";
let _ = socket.write_all(head.as_bytes());
let _ = socket.write_all(body.as_bytes());
let _ = socket.flush();
}
/// Drive one turn through `provider` and return the request it put on the wire.
async fn wire_request(
provider: &std::sync::Arc<dyn Provider + Send + Sync>,
model_id: &str,
head: std::sync::mpsc::Receiver<String>,
) -> String {
use futures::StreamExt;
let request = luxe_core::provider::CompletionRequest {
model: ModelInfo {
r#ref: luxe_core::provider::ModelRef::new("foundry", model_id),
max_tokens: 1024,
..ModelInfo::default()
},
messages: vec![luxe_core::message::Message::user("ping")],
system: Some("be brief".into()),
tools: Vec::new(),
thinking: luxe_core::provider::ThinkingLevel::Off,
max_tokens: Some(1024),
..Default::default()
};
let (_tx, cancel) = tokio::sync::watch::channel(false);
if let Ok(mut stream) = provider.stream(request, cancel).await {
while stream.next().await.is_some() {}
}
head.recv_timeout(std::time::Duration::from_secs(5)).expect("the adapter sent a request")
}
/// The header `name` that `provider` sends, or `None` when it sent no request at all (a
/// provider with no credential fails before reaching the wire).
fn sent_header(
runtime: &tokio::runtime::Runtime,
provider: &std::sync::Arc<dyn Provider + Send + Sync>,
heads: &std::sync::mpsc::Receiver<String>,
name: &str,
) -> Option<String> {
let request = luxe_core::provider::CompletionRequest {
model: ModelInfo { max_tokens: 1024, ..ModelInfo::default() },
messages: vec![luxe_core::message::Message::user("ping")],
max_tokens: Some(1024),
..Default::default()
};
let (_tx, cancel) = tokio::sync::watch::channel(false);
runtime.block_on(async {
use futures::StreamExt;
if let Ok(mut stream) = provider.stream(request, cancel).await {
while stream.next().await.is_some() {}
}
});
let head = heads.recv_timeout(std::time::Duration::from_millis(500)).ok()?;
header_value(&head, name)
}
/// The three endpoints a Foundry resource publishes, composed by the code that actually builds
/// the adapters. The paths are the ones on a deployment's Details tab; two of them share
/// `/openai/v1` and differ only in the adapter's own endpoint, and the Anthropic one
/// authenticates the Azure way while still speaking Anthropic's protocol — the exact pairing
/// that makes Foundry three providers instead of one.
#[tokio::test]
async fn each_foundry_surface_reaches_its_own_documented_endpoint() {
for (id, model, expected_line, body) in [
(
"foundry-anthropic",
"claude-sonnet-5",
"POST /anthropic/v1/messages HTTP/1.1",
"event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n",
),
(
"foundry-openai",
"gpt-5.6-sol",
"POST /openai/v1/responses HTTP/1.1",
"event: response.completed\ndata: {\"type\":\"response.completed\"}\n\n",
),
(
"foundry-completions",
"deepseek-v4-pro",
"POST /openai/v1/chat/completions HTTP/1.1",
"data: {\"choices\":[{\"finish_reason\":\"stop\",\"delta\":{}}]}\n\ndata: [DONE]\n\n",
),
] {
let descriptor = provider_descriptor(id).expect("in catalog");
let (port, head) = serve_once(body);
let base_url = descriptor.endpoint_for(&format!("http://127.0.0.1:{port}"));
let auth = luxe_providers::auth::StaticAuth::for_style(
resolve_key_style(id, None),
Some(ApiKey::new("fk-live")),
)
.into_arc();
let adapter = build_provider_adapter(
resolve_api(id, None),
ModelInfo::default(),
auth,
Some(base_url),
resolve_compat(id, None),
);
let sent = wire_request(&adapter, model, head).await;
assert!(sent.starts_with(expected_line), "{id} sent:\n{sent}");
assert!(sent.contains(model), "{id} must send the deployment name:\n{sent}");
// Header *names* are parsed rather than matched as substrings: `x-api-key` contains
// `api-key`, so a substring check passes whether or not the second header was sent.
let sent_header = |name: &str| header_value(&sent, name);
match id {
"foundry-anthropic" => {
assert_eq!(sent_header("x-api-key").as_deref(), Some("fk-live"), "{sent}");
assert_eq!(sent_header("api-key").as_deref(), Some("fk-live"), "{sent}");
assert_eq!(sent_header("authorization"), None, "a bearer 401s here:\n{sent}");
assert_eq!(
sent_header("anthropic-version").as_deref(),
Some("2023-06-01"),
"{sent}"
);
}
_ => {
assert_eq!(
sent_header("authorization").as_deref(),
Some("Bearer fk-live"),
"{sent}"
);
assert_eq!(sent_header("x-api-key"), None, "{sent}");
assert_eq!(sent_header("api-key"), None, "{sent}");
}
}
}
}
/// The launch provider's `!command` key runs for each request, not once at startup, so a
/// short-lived token (Entra, `az account get-access-token`) is fresh for every turn of a long
/// session. `cat` stands in for the token command: the file changes between two requests.
#[cfg(unix)]
#[tokio::test]
async fn the_launch_providers_command_key_runs_for_each_request() {
let (_dir, token, auth) = {
let _guard = super::super::test_env::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = super::super::test_env::isolated_env();
let token = dir.path().join("token");
std::fs::write(&token, "token-one").expect("token");
std::fs::create_dir_all(dir.path().join("luxe")).expect("config dir");
let models = serde_json::json!({
"providers": { "anthropic": { "api_key": format!("!cat {}", token.display()) } }
});
std::fs::write(dir.path().join("luxe").join("models.json"), models.to_string())
.expect("models.json");
let overrides =
super::super::CliOverrides { provider: Some("anthropic".into()), ..Default::default() };
let settings = AgentSettings::resolve(dir.path().to_path_buf(), overrides);
let config = load_luxe_config();
let auth = active_auth(&settings, config.providers.get("anthropic"));
(dir, token, auth)
};
let key = |auth: luxe_providers::auth::RequestAuth| {
auth.headers.into_iter().find(|(name, _)| name == "x-api-key").map(|(_, key)| key)
};
let first = key(auth.request_auth().await.expect("first request"));
std::fs::write(&token, "token-two").expect("token");
let second = key(auth.request_auth().await.expect("second request"));
assert_eq!(first.as_ref().map(ApiKey::expose), Some("token-one"));
assert_eq!(second.as_ref().map(ApiKey::expose), Some("token-two"), "run again, not cached");
}
/// Launch and a `/model` switch find a provider's key by one chain: a sign-in first, then the
/// provider's own variable, then the key its block names, and for a provider Luxe does not know,
/// its block before `OPENAI_API_KEY`. So a configured key always beats a key meant for another
/// provider, and which one goes out never depends on how the session reached the provider.
#[test]
fn launch_and_a_model_switch_send_the_same_key() {
let _guard = super::super::test_env::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let home = super::super::test_env::isolated_env();
let runtime =
tokio::runtime::Builder::new_current_thread().enable_all().build().expect("runtime");
let completions =
"data: {\"choices\":[{\"finish_reason\":\"stop\",\"delta\":{}}]}\n\ndata: [DONE]\n\n";
let messages = "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n";
let (gateway_port, gateway_heads) = serve(completions, 2);
let (keyed_port, keyed_heads) = serve(completions, 2);
let (anthropic_port, anthropic_heads) = serve(messages, 2);
std::fs::create_dir_all(home.path().join("luxe")).expect("config dir");
let models = serde_json::json!({ "providers": {
"gateway": { "base_url": format!("http://127.0.0.1:{gateway_port}/v1") },
"keyed": { "base_url": format!("http://127.0.0.1:{keyed_port}/v1"), "api_key": "keyed-key" },
"anthropic": { "base_url": format!("http://127.0.0.1:{anthropic_port}/v1") },
}});
std::fs::write(home.path().join("luxe").join("models.json"), models.to_string())
.expect("models.json");
AuthStore::default_path()
.put("anthropic", &luxe_providers::auth::Credential::api_key("sk-ant-signed-in"))
.expect("sign in");
std::env::set_var("OPENAI_API_KEY", "sk-openai");
std::env::set_var("ANTHROPIC_API_KEY", "sk-ant-env");
let launched_on = |provider: &str| {
let overrides =
super::super::CliOverrides { provider: Some(provider.into()), ..Default::default() };
AgentSettings::resolve(home.path().to_path_buf(), overrides)
};
let elsewhere = launched_on("lmstudio");
let registry = build_provider_registry(&elsewhere, &build_active_adapter(&elsewhere));
let mut sent = Vec::new();
for (provider, heads, header) in [
("gateway", &gateway_heads, "authorization"),
("keyed", &keyed_heads, "authorization"),
("anthropic", &anthropic_heads, "x-api-key"),
] {
let at_launch = build_active_adapter(&launched_on(provider));
let launch = sent_header(&runtime, &at_launch, heads, header);
let switched = sent_header(&runtime, &registry[provider], heads, header);
sent.push((provider, launch, switched));
}
std::env::remove_var("OPENAI_API_KEY");
std::env::remove_var("ANTHROPIC_API_KEY");
let both = |key: &str| (Some(key.to_string()), Some(key.to_string()));
let sent: Vec<_> =
sent.into_iter().map(|(name, launch, switch)| (name, (launch, switch))).collect();
assert_eq!(
sent,
[
("gateway", both("Bearer sk-openai")),
("keyed", both("Bearer keyed-key")),
("anthropic", both("sk-ant-signed-in")),
]
);
}
/// Which key each kind of provider settles on with nothing stored: a provider Luxe does not know
/// takes the key written for it before the `OPENAI_API_KEY` fallback, and one it knows takes its
/// own variable first.
#[test]
fn a_configured_key_beats_the_openai_fallback_for_an_unknown_provider() {
let _guard = super::super::test_env::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let home = super::super::test_env::isolated_env();
let runtime =
tokio::runtime::Builder::new_current_thread().enable_all().build().expect("runtime");
let store = AuthStore::new(home.path().join("auth.json"));
let key = |provider: &str, config: Option<&ProviderConfig>| {
let auth = provider_auth(store.clone(), provider, config);
let resolved = runtime.block_on(auth.request_auth()).ok()?;
resolved.headers.into_iter().next().map(|(_, key)| key.expose().to_string())
};
std::env::set_var("OPENAI_API_KEY", "sk-openai-fallback");
let written = ProviderConfig { api_key: Some(ApiKey::new("gw-key")), ..Default::default() };
let gateway = key("gateway", Some(&written));
let unwritten = key("gateway", None);
let openai = key("openai", Some(&written));
std::env::remove_var("OPENAI_API_KEY");
assert_eq!(gateway.as_deref(), Some("Bearer gw-key"), "the configured key");
assert_eq!(unwritten.as_deref(), Some("Bearer sk-openai-fallback"), "nothing configured");
assert_eq!(
openai.as_deref(),
Some("Bearer sk-openai-fallback"),
"a known provider's own variable"
);
}

View File

@@ -0,0 +1,299 @@
//! Warm, process-wide service singletons — the LSP client, code graph, DAP debugger, and
//! diagnostics cache — plus the per-project session store.
//!
//! Luxe runs one project per process, so each service is a `OnceLock` singleton reused across
//! every tool call and hook instead of being spawned per request.
use std::sync::Arc;
use luxe_core::session::JsonlSessionStore;
use super::config::project_hash;
/// Open the project's session store (session dir + project hash) without creating a session.
///
/// Shared by `build_engine` and the `sessions`/resume paths so they agree on where
/// sessions live and how the project is hashed.
pub(crate) fn open_session_store(repo_root: &std::path::Path) -> JsonlSessionStore {
let session_dir = repo_root.join(".luxe").join("sessions");
let mut store = JsonlSessionStore::new(&session_dir);
store.set_project_hash(&project_hash(repo_root));
store
}
/// A warm, per-workspace LSP service shared by the diagnostics/navigation tools and the
/// diagnostics-on-edit hook. One long-lived instance reuses language servers across every call
/// (no spawn-per-call).
pub(crate) type SharedLspService = Arc<luxe_lsp::WorkspaceLspClient>;
/// Whether this run may launch a language server the project installed for itself.
///
/// A `OnceLock` rather than a parameter because [`build_lsp_service`] is reached from three places
/// that do not all hold the settings — startup, the workspace collector, and shutdown — and only
/// the first of them knows the answer. Unset reads as refused, so an ordering mistake fails closed
/// rather than granting something nobody asked for.
static PROJECT_SERVERS: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
/// What every tool ended up doing, published once the registry is assembled.
///
/// Same shape and same reason as [`PROJECT_SERVERS`]: the answer is settled at startup by the code
/// that holds the registry, and read later by the workspace collector, which does not. Unset reads
/// as "nothing to report", so a front-end built without an engine simply shows no tool section.
static TOOL_STATUSES: std::sync::OnceLock<Vec<luxe_core::ToolStatus>> = std::sync::OnceLock::new();
/// Record what `/tools` should say. Called once, from registry assembly.
pub(crate) fn note_tool_statuses(statuses: Vec<luxe_core::ToolStatus>) {
let _ = TOOL_STATUSES.set(statuses);
}
/// What `/tools` should say, or empty before the registry has been built.
pub(crate) fn tool_statuses() -> Vec<luxe_core::ToolStatus> {
TOOL_STATUSES.get().cloned().unwrap_or_default()
}
/// Resolve whether this run may launch a server out of the project's `node_modules/.bin`.
///
/// Three inputs, and the judgement is here rather than in `luxe-lsp` so it can be read and tested
/// in one place: the user's preference, whether a front-end can prompt, and `--trust-project`.
///
/// `interactive` carries the whole argument for the default. Luxe is a coding agent someone sits
/// in front of; the loop is a feature, not the usual way it runs. With a person there, using the
/// server the project pinned is ordinary work — and `node_modules/.bin` exists only because
/// `npm install` already ran that project's install scripts, which is arbitrary code and a wider
/// door than one language server. Unattended there is nobody to notice, so that case wants the
/// explicit yes `--trust-project` already means everywhere else.
pub(crate) fn project_servers_allowed(
preference: luxe_core::config::ProjectServers,
interactive: bool,
trust_project: bool,
) -> bool {
use luxe_core::config::ProjectServers;
match preference {
ProjectServers::Never => false,
ProjectServers::Always => true,
ProjectServers::Auto => interactive || trust_project,
}
}
/// Record the resolved answer for the services built later in this run.
///
/// Called once, before anything builds the LSP service. Later calls are ignored, which is what
/// keeps the answer from changing under a service that has already been handed out.
pub(crate) fn note_project_servers(allowed: bool) {
let _ = PROJECT_SERVERS.set(allowed);
}
/// Whether this run may execute a binary the repository supplied.
///
/// The same answer [`build_lsp_service`] uses, read by format-on-save, because it is the same
/// question: a `.venv/bin/ruff` or a `node_modules/.bin/biome` got there from the repository. One
/// decision rather than two — a user who said "do not run this project's binaries" did not mean
/// only the language servers, and one who pinned a formatter version means the formatter too.
/// Unset reads as refused, the same fail-closed default.
pub(crate) fn project_tooling_allowed() -> bool {
PROJECT_SERVERS.get().copied().unwrap_or(false)
}
/// The process-wide warm LSP service. A singleton (like [`shared_diagnostics_store`]) so the tools,
/// the diagnostics-on-edit hook, and the workspace collector (which reads running-server state for
/// `/lsp`) all share one instance. Luxe runs one project per process; the collector scopes
/// running servers to the active root.
pub(crate) fn build_lsp_service() -> SharedLspService {
static SERVICE: std::sync::OnceLock<SharedLspService> = std::sync::OnceLock::new();
SERVICE
.get_or_init(|| {
Arc::new(
luxe_lsp::WorkspaceLspClient::with_servers(load_lsp_servers())
.with_project_servers(PROJECT_SERVERS.get().copied().unwrap_or(false)),
)
})
.clone()
}
/// The process-wide warm code graph service, shared by the `impact` / `module_report` tools and the
/// graph-invalidation hook. Singleton like the LSP/DAP services; rooted at the workspace on first
/// use (Luxe runs one project per process).
pub(crate) fn build_graph_service(
repo_root: &std::path::Path,
) -> Arc<luxe_lsp::graph::GraphService> {
static SERVICE: std::sync::OnceLock<Arc<luxe_lsp::graph::GraphService>> =
std::sync::OnceLock::new();
SERVICE.get_or_init(|| Arc::new(luxe_lsp::graph::GraphService::new(repo_root))).clone()
}
/// The process-wide warm symbol index, shared by `symbol_search` and the hook that forgets it when
/// a file changes. Singleton for the same reason as the graph service.
pub(super) fn shared_symbol_index() -> Arc<luxe_lsp::SymbolIndexCache> {
static INDEX: std::sync::OnceLock<Arc<luxe_lsp::SymbolIndexCache>> = std::sync::OnceLock::new();
INDEX.get_or_init(Arc::default).clone()
}
/// The process-wide warm DAP service, shared by the `debug` tool and the workspace collector (which
/// lists live debug sessions for `/debug`). Singleton for the same reason as the LSP service.
pub(crate) fn shared_dap_service() -> Arc<luxe_dap::DapService> {
static SERVICE: std::sync::OnceLock<Arc<luxe_dap::DapService>> = std::sync::OnceLock::new();
SERVICE
.get_or_init(|| Arc::new(luxe_dap::DapService::with_adapters(load_debug_adapters())))
.clone()
}
/// Loads user-configured language servers from `~/.config/luxe/lsp-servers.json`.
/// A missing file is no servers; an invalid one is logged and ignored (built-ins still work).
pub(crate) fn load_lsp_servers() -> std::collections::HashMap<String, luxe_lsp::ServerEntryPatch> {
read_lsp_servers().unwrap_or_else(|error| {
tracing::warn!(%error, "ignoring invalid lsp-servers.json");
std::collections::HashMap::new()
})
}
/// [`load_lsp_servers`], keeping the reason an invalid file was ignored — for `luxe doctor`,
/// which is where someone goes to find out why their server is not there.
pub(crate) fn read_lsp_servers(
) -> Result<std::collections::HashMap<String, luxe_lsp::ServerEntryPatch>, String> {
let path = luxe_core::config::Config::lsp_servers_path();
match read_config_text(&path)? {
Some(text) => serde_json::from_str(&text)
.map_err(|error| format!("{}: {error}", luxe_core::paths::display(&path))),
None => Ok(std::collections::HashMap::new()),
}
}
/// Whether the first word of `command` is a program this machine can run.
///
/// Delegates to [`luxe_core::program::is_available`], which is the one owner of "can I run this"
/// (`AGENTS.md`): it also tries the Windows executable suffixes, so a bare `rg` finds `rg.exe`
/// instead of reading as "ripgrep is not installed" on a machine where it plainly is. The split is
/// here because these entries are whole command lines (`python3 -m debugpy.adapter`), not names.
pub(crate) fn command_on_path(command: &str) -> bool {
let program = command.split_whitespace().next().unwrap_or(command);
!program.is_empty() && luxe_core::program::is_available(program)
}
/// Loads user-configured debug adapters from `~/.config/luxe/debug-adapters.json` (a JSON array).
/// A missing file is no adapters; an invalid one is logged and ignored (built-ins still work).
pub(crate) fn load_debug_adapters() -> Vec<luxe_dap::CustomAdapter> {
read_debug_adapters().unwrap_or_else(|error| {
tracing::warn!(%error, "ignoring invalid debug-adapters.json");
Vec::new()
})
}
/// [`load_debug_adapters`], keeping the reason an invalid file was ignored.
pub(crate) fn read_debug_adapters() -> Result<Vec<luxe_dap::CustomAdapter>, String> {
let path = luxe_core::config::Config::debug_adapters_path();
match read_config_text(&path)? {
Some(text) => serde_json::from_str(&text)
.map_err(|error| format!("{}: {error}", luxe_core::paths::display(&path))),
None => Ok(Vec::new()),
}
}
/// Every debug adapter a session can use: the built-ins a user entry does not shadow, then the
/// user's own. Args of each: `(adapter, from_config)`.
///
/// The one list, for the `/debug` view and `luxe doctor` alike, so an adapter added in config
/// appears in the checkup meant to confirm it.
pub(crate) fn merged_debug_adapters(
user: &[luxe_dap::CustomAdapter],
) -> Vec<(luxe_dap::adapter::ConfiguredAdapter, bool)> {
let user_ids: std::collections::HashSet<&str> =
user.iter().map(|adapter| adapter.id.as_str()).collect();
luxe_dap::builtin_adapters()
.into_iter()
.filter(|builtin| !user_ids.contains(builtin.spec.id.as_str()))
.map(|builtin| (builtin, false))
.chain(
user.iter()
.map(|custom| (luxe_dap::adapter::ConfiguredAdapter::from_custom(custom), true)),
)
.collect()
}
/// A config file's text, `None` when it does not exist; any other failure names the path.
fn read_config_text(path: &std::path::Path) -> Result<Option<String>, String> {
match std::fs::read_to_string(path) {
Ok(contents) => Ok(Some(contents)),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(format!("{}: {error}", luxe_core::paths::display(path))),
}
}
/// The process-wide diagnostics cache shared by the diagnostics-on-edit hook (writer) and the
/// workspace collector (reader).
///
/// A shared handle at the binary boundary: it lets the (core) hook publish per-file diagnostics
/// that the (core-agnostic) collector reads for the Context Dock without threading a channel
/// through every front-end. Luxe runs one project per process; the collector filters entries to the
/// active root, so a project switch never leaks another tree's diagnostics.
pub(crate) fn shared_diagnostics_store() -> luxe_core::lsp::DiagnosticsStore {
static STORE: std::sync::OnceLock<luxe_core::lsp::DiagnosticsStore> =
std::sync::OnceLock::new();
STORE.get_or_init(luxe_core::lsp::DiagnosticsStore::new).clone()
}
/// The process-wide record of work done outside the project, written by the external-work hook and
/// read by the workspace collector.
///
/// Shares the diagnostics cache's arrangement and its reason: one project per process, a hook that
/// writes and a collector that reads, and no channel threaded through every front-end to join them.
pub(crate) fn shared_external_work() -> luxe_core::external_work::ExternalWork {
static WORK: std::sync::OnceLock<luxe_core::external_work::ExternalWork> =
std::sync::OnceLock::new();
WORK.get_or_init(luxe_core::external_work::ExternalWork::new).clone()
}
#[cfg(test)]
mod tests {
use super::{merged_debug_adapters, project_servers_allowed};
use luxe_core::config::ProjectServers;
/// A configured adapter is in the list every surface reads, and one reusing a built-in id
/// replaces it rather than appearing twice.
///
/// `luxe doctor` listed the built-ins alone, so the adapter someone had just added never showed
/// up in the checkup they ran to confirm it.
#[test]
fn configured_adapters_join_the_built_ins() {
let user: Vec<luxe_dap::CustomAdapter> = serde_json::from_str(
r#"[
{ "id": "ruby", "command": ["rdbg"], "extensions": ["rb"], "dialect": "debugpy" },
{ "id": "gdb", "command": ["my-gdb"], "dialect": "debugpy" }
]"#,
)
.expect("valid adapters");
let merged = merged_debug_adapters(&user);
let find = |id: &str| merged.iter().filter(|(a, _)| a.spec.id == id).collect::<Vec<_>>();
assert!(matches!(find("ruby").as_slice(), [(_, true)]), "the configured adapter is listed");
let gdb = find("gdb");
assert_eq!(gdb.len(), 1, "a shadowed built-in appears once");
assert_eq!(gdb[0].0.spec.command, ["my-gdb"], "as the user's");
assert!(matches!(find("debugpy").as_slice(), [(_, false)]), "untouched built-ins stay");
}
/// The default answer turns on who is watching, and nothing else.
#[test]
fn auto_follows_whether_anyone_is_there_to_notice() {
assert!(project_servers_allowed(ProjectServers::Auto, true, false), "a TUI session");
assert!(!project_servers_allowed(ProjectServers::Auto, false, false), "headless or a loop");
assert!(
project_servers_allowed(ProjectServers::Auto, false, true),
"unattended, but the run said it trusts this project"
);
}
/// Both explicit settings mean it everywhere, including where the default would disagree.
#[test]
fn an_explicit_preference_wins_over_the_situation() {
for (interactive, trust) in [(true, true), (true, false), (false, true), (false, false)] {
assert!(project_servers_allowed(ProjectServers::Always, interactive, trust));
assert!(!project_servers_allowed(ProjectServers::Never, interactive, trust));
}
}
/// `never` outranks `--trust-project`: the flag is what a *repository* may do, not an
/// instruction to override a preference the user set for themselves.
#[test]
fn never_is_not_overridden_by_trusting_the_project() {
assert!(!project_servers_allowed(ProjectServers::Never, true, true));
}
}

View File

@@ -0,0 +1,232 @@
//! The session a run attaches to — which one, and what its log records about the run.
use std::path::PathBuf;
use luxe_core::session::{SessionId, SessionStore};
use super::AgentSettings;
/// How [`super::build_engine`] chooses the session to run.
#[derive(Debug, Clone, Default, PartialEq)]
pub(crate) enum ResumeMode {
/// Start a fresh session (the default).
#[default]
New,
/// Resume the most recently modified session for this project.
Latest,
/// Resume a specific session by id.
Session(String),
/// Resume the newest session that worked on this pull request.
PullRequest(u64),
}
/// The existing session a resume mode picks, or `None` when it starts a new one or finds none.
///
/// One answer for the two places that need it: the CLI, which has to know before the engine
/// starts whether that session works in a worktree, and `build_engine`, which opens it.
pub(crate) fn resumed_session(store: &impl SessionStore, mode: &ResumeMode) -> Option<SessionId> {
match mode {
ResumeMode::New => None,
ResumeMode::Latest => store.most_recent_session(),
ResumeMode::PullRequest(number) => {
let recent: Vec<SessionId> =
store.recent_sessions(usize::MAX).into_iter().map(|(id, _)| id).collect();
luxe_core::session::session_for_pull_request(store, &recent, *number)
}
ResumeMode::Session(id) => {
let sid = SessionId(id.clone());
store.list_sessions().contains(&sid).then_some(sid)
}
}
}
/// Appends `kind` to the session's log, unless the log already says it.
///
/// Appended at the current leaf and never made the leaf, like a usage record. `what` names the
/// record in the warning: a failed write costs the next resume a convenience, not this run.
fn record_once(
store: &mut luxe_core::session::JsonlSessionStore,
session: &SessionId,
already: impl FnOnce(&[luxe_core::session::Entry]) -> bool,
kind: luxe_core::session::EntryKind,
what: &str,
) {
let Ok(entries) = store.load(session) else {
return;
};
if already(&entries) {
return;
}
if let Err(error) = store.append(session, luxe_core::session::latest_leaf(&entries), kind) {
tracing::warn!(%error, record = what, "could not record it in the session's log");
}
}
/// Records in the session's own log that it works in `binding`, unless it already says so.
fn record_worktree(
store: &mut luxe_core::session::JsonlSessionStore,
session: &SessionId,
binding: &WorktreeBinding,
state_root: &std::path::Path,
) {
let path = binding.path.strip_prefix(state_root).unwrap_or(&binding.path);
let kind = luxe_core::session::EntryKind::Worktree {
branch: binding.branch.clone(),
path: luxe_core::paths::display(path),
};
let already = |entries: &[luxe_core::session::Entry]| {
luxe_core::session::session_worktree(entries).as_deref() == Some(binding.branch.as_str())
};
record_once(store, session, already, kind, "worktree");
}
/// The issue a session takes up as its brief.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct IssueBinding {
/// Number within its repository
pub(crate) number: u64,
/// Its web address
pub(crate) url: String,
/// What the session's first message carries
pub(crate) brief: String,
}
/// Records in the session's log the issue it took up, unless it already says so.
fn record_issue(
store: &mut luxe_core::session::JsonlSessionStore,
session: &SessionId,
issue: &IssueBinding,
) {
let kind =
luxe_core::session::EntryKind::IssueLink { number: issue.number, url: issue.url.clone() };
let already = |entries: &[luxe_core::session::Entry]| {
luxe_core::session::session_issue(entries) == Some(issue.number)
};
record_once(store, session, already, kind, "issue");
}
/// Records in the session's log that it works on pull request `number`, unless it already says so,
/// so `--from-pr` finds it again.
fn record_pull_request(
store: &mut luxe_core::session::JsonlSessionStore,
session: &SessionId,
number: u64,
url: &str,
) {
let kind = luxe_core::session::EntryKind::PullRequestLink { number, url: url.to_string() };
let already = |entries: &[luxe_core::session::Entry]| {
luxe_core::session::linked_pull_requests(entries).contains(&number)
};
record_once(store, session, already, kind, "pull request");
}
/// The worktree a session works in: its branch and where it is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct WorktreeBinding {
pub(crate) branch: String,
pub(crate) path: PathBuf,
}
/// The session to run: resumed or fresh, with the worktree, issue and pull request it is tied to
/// written into its log.
///
/// The engine's `current_leaf` lazily walks to the tail on the first turn, so an existing id
/// resumes.
pub(super) fn attach_session(
settings: &AgentSettings,
store: &mut luxe_core::session::JsonlSessionStore,
) -> anyhow::Result<SessionId> {
let session_id = match (&settings.resume, resumed_session(store, &settings.resume)) {
(ResumeMode::New, _) => store.create(&settings.state_root.to_string_lossy())?,
(_, Some(id)) => {
tracing::info!(session = %id, "resuming session");
id
}
(ResumeMode::Latest, None) => {
tracing::info!("no prior session to resume; starting fresh");
store.create(&settings.state_root.to_string_lossy())?
}
(ResumeMode::PullRequest(number), None) => anyhow::bail!(
"no session in this project worked on pull request #{number}; `luxe sessions list` \
shows the ones that exist"
),
(ResumeMode::Session(id), None) => {
anyhow::bail!("session '{id}' not found for this project")
}
};
// A session in a worktree says so in its own log, which is how resuming finds the worktree
if let Some(binding) = &settings.worktree {
record_worktree(store, &session_id, binding, &settings.state_root);
}
if let Some(issue) = &settings.issue {
record_issue(store, &session_id, issue);
}
if let Some((number, url)) = &settings.pull_request {
record_pull_request(store, &session_id, *number, url);
}
Ok(session_id)
}
#[cfg(test)]
mod tests {
use super::super::open_session_store;
use super::*;
/// A session records its worktree once, relative to the project, and each way of resuming
/// finds the session it names — which is how the CLI knows to re-enter the worktree first.
#[test]
fn a_session_records_its_worktree_once_and_resuming_finds_it() {
use luxe_core::session::{EntryKind, SessionStore};
let dir = tempfile::tempdir().unwrap();
let mut store = open_session_store(dir.path());
let id = store.create("/work").unwrap();
store
.append(&id, None, EntryKind::Message(luxe_core::message::Message::user("hi")))
.unwrap();
let binding = WorktreeBinding {
branch: "topic".into(),
path: dir.path().join(".luxe/worktrees/topic"),
};
record_worktree(&mut store, &id, &binding, dir.path());
record_worktree(&mut store, &id, &binding, dir.path());
let entries = store.load(&id).unwrap();
let recorded: Vec<_> = entries
.iter()
.filter_map(|entry| match &entry.kind {
EntryKind::Worktree { branch, path } => Some((branch.clone(), path.clone())),
_ => None,
})
.collect();
assert_eq!(recorded, [("topic".to_string(), ".luxe/worktrees/topic".to_string())]);
assert_eq!(luxe_core::session::session_worktree(&entries).as_deref(), Some("topic"));
let issue = IssueBinding {
number: 7,
url: "https://github.com/acme/app/issues/7".into(),
brief: String::new(),
};
record_issue(&mut store, &id, &issue);
record_issue(&mut store, &id, &issue);
let entries = store.load(&id).unwrap();
assert_eq!(luxe_core::session::session_issue(&entries), Some(7));
assert_eq!(
entries.iter().filter(|e| matches!(e.kind, EntryKind::IssueLink { .. })).count(),
1,
"once"
);
record_pull_request(&mut store, &id, 142, "https://github.com/acme/app/pull/142");
record_pull_request(&mut store, &id, 142, "https://github.com/acme/app/pull/142");
let entries = store.load(&id).unwrap();
assert_eq!(luxe_core::session::linked_pull_requests(&entries), [142], "once");
assert_eq!(resumed_session(&store, &ResumeMode::PullRequest(142)), Some(id.clone()));
assert_eq!(resumed_session(&store, &ResumeMode::New), None);
assert_eq!(resumed_session(&store, &ResumeMode::Latest), Some(id.clone()));
assert_eq!(resumed_session(&store, &ResumeMode::Session(id.0.clone())), Some(id.clone()));
assert_eq!(resumed_session(&store, &ResumeMode::Session("nope".into())), None);
assert_eq!(resumed_session(&store, &ResumeMode::PullRequest(9)), None);
}
}

View File

@@ -0,0 +1,364 @@
//! Settings — what a run resolved to before the engine exists: provider, model, key, endpoint.
use std::path::PathBuf;
use luxe_providers::config::{resolve_value, ApiKey, CompatFlags, ProviderConfig};
use super::config::{env_nonempty, load_luxe_config};
use super::provider::{provider_serves, resolve_base_url, resolve_compat, split_model_ref};
use super::{IssueBinding, ResumeMode, WorktreeBinding};
/// The active provider's endpoint: the CLI flag, then the environment, then the provider's own
/// config and the catalog's default.
fn active_base_url(
flag: Option<String>,
provider: &str,
config: Option<&ProviderConfig>,
) -> Option<String> {
flag.or_else(|| env_nonempty("LUXE_BASE_URL"))
.or_else(|| {
(provider == "openai_compat").then(|| env_nonempty("OPENAI_BASE_URL")).flatten()
})
.map(|url| resolve_value(&url))
.filter(|url| !url.trim().is_empty())
.or_else(|| resolve_base_url(provider, config))
}
/// CLI-supplied overrides. Any set value wins over env and the config files.
#[derive(Debug, Clone, Default)]
pub(crate) struct CliOverrides {
pub(crate) provider: Option<String>,
pub(crate) model: Option<String>,
pub(crate) api_key: Option<String>,
pub(crate) base_url: Option<String>,
}
/// Resolved runtime settings for the agent.
///
/// Precedence, highest first: CLI flag → environment variable → what the last session picked →
/// `~/.config/luxe/auth.json` (+ `models.json`). There is no layer under that one: nothing here
/// invents a model. Local endpoints that need no key still work; a missing key for a hosted
/// provider surfaces as an auth error at request time.
#[derive(Debug, Clone)]
pub(crate) struct AgentSettings {
/// The project: sessions, todos, reviews, logs and the rest of `.luxe/` live here, and its
/// config and permissions are read from here, whatever checkout the agent works in.
pub(crate) state_root: PathBuf,
/// Where the agent works: tools run here, reviews and diffs are taken here, and the language
/// servers and the code graph index it. The same path as `state_root` unless the session has a
/// worktree of its own.
pub(crate) work_root: PathBuf,
/// The session's own worktree, when it has one; `work_root` is its path
pub(crate) worktree: Option<WorktreeBinding>,
/// The issue taken up with `--issue`, and the brief its first message carries
pub(crate) issue: Option<IssueBinding>,
/// The pull request checked out with `--pr`, which the session records working on
pub(crate) pull_request: Option<(u64, String)>,
/// Where this engine's spend is reported on top of its own session ledger.
///
/// Carried in the settings rather than passed to `build_engine` so that an engine built from a
/// clone of them — the phase reviewer's — reports into the same run without being told to.
pub(crate) spend_sink: Option<std::sync::Arc<dyn luxe_core::usage::SpendSink>>,
/// Provider identifier (`openai_compat` or `anthropic`).
pub(crate) provider: String,
/// Fully resolved metadata for the chosen model, or `None` when nobody has chosen one.
///
/// The embedded models.dev snapshot and the refreshed cache layered under the user's config:
/// the wire id (`model.ref.id`), context window, output cap, reasoning levels, and pricing the
/// engine runs on.
///
/// `None` is a real state rather than a gap to be filled: falling back to whichever id the
/// provider catalog names first is a literal in the binary, and model ids age out faster than
/// releases do, so the guess goes stale and then gets sent. Use
/// [`Self::require_model`] where a model is needed to proceed and [`Self::launch_model`] where
/// an engine has to be built either way.
pub(crate) model: Option<luxe_core::provider::ModelInfo>,
/// Base URL override (must include the API version segment, e.g. `.../v1`).
pub(crate) base_url: Option<String>,
/// The key named for this run (`--api-key`, else `LUXE_API_KEY`), which outranks a sign-in.
///
/// Held as written, as a redacted secret; a `$ENV` or `!command` in it is expanded per request.
/// `None` leaves the provider's own chain in charge (see `provider::provider_auth`).
pub(crate) api_key: Option<ApiKey>,
/// The provider's compat flags (from config, else defaults).
pub(crate) compat: CompatFlags,
/// Which session to run (new / latest / specific).
pub(crate) resume: ResumeMode,
/// Permission-mode override from the CLI (`None` defers to config / built-in default).
pub(crate) permission_mode: Option<luxe_core::permission::PermissionMode>,
/// Whether the project's `.luxe/permissions.json` may loosen policy (`--trust-project`).
pub(crate) trust_project: bool,
/// Reasoning level to apply once at startup (`--thinking`, else what the last session chose).
///
/// `None` leaves the engine on the level the model itself declares (`models.json`'s
/// `thinking`), which is why a remembered level is dropped here rather than sent and
/// overridden: the send is what gets written back to the remembered level, so applying a
/// model's own default through it would make the default permanent the first time it fired.
pub(crate) initial_thinking: Option<luxe_core::provider::ThinkingLevel>,
/// Per-turn tool round-trip cap (`agent.max_tool_iterations`, overridable by
/// `LUXE_MAX_TOOL_ITERATIONS`). `None` — the default — means no cap.
pub(crate) max_tool_iterations: Option<usize>,
/// Whether the model was named on *this* command line (`--model`) or in `LUXE_MODEL`.
///
/// Distinct from `model` being `Some`, which is true for a remembered or configured model as
/// well. What this answers is narrower and is asked in exactly one kind of place: may plan
/// mode's configured model apply? A flag is a one-off and outranks configuration; anything a
/// config file decided does not.
pub(crate) model_forced: bool,
/// Whether `--thinking` set [`Self::initial_thinking`], which outranks `plan.thinking` the way
/// [`Self::model_forced`] outranks `plan.model`. A level remembered from the last session does
/// not.
pub(crate) thinking_forced: bool,
/// The mode this engine starts in (`--plan`, else `agent.default_mode`), when not `build`.
pub(crate) initial_mode: Option<String>,
/// Whether this engine is a reviewer's: one mode that changes nothing, the reviewer's tools and
/// no others, and no reviewer of its own to ask.
pub(crate) review_engine: bool,
/// Whether an autonomous loop is driving this engine (`luxe loop`).
///
/// Set by the loop subcommand and nowhere else. The loop's machinery is opt-in, so nothing it
/// owns may reach an ordinary session: its hooks are registered only by
/// `loop_hooks::build_default_hooks`, and this flag keeps `loop_control` — a tool with nothing
/// to control outside a loop — out of the tool catalog every other session's prompt carries.
pub(crate) loop_driven: bool,
/// Tools to leave unregistered for this run (`--no-tool`), on top of the config deny-list.
pub(crate) disable_tools: Vec<String>,
/// Tools to register despite the config deny-list, for this run (`--with-tool`).
pub(crate) enable_tools: Vec<String>,
/// What an `ask` resolves to where nobody can answer it (`--on-ask`, else `agent.on_ask`).
///
/// Read by the front-ends that cannot prompt — headless, the loop, a review agent — through
/// [`Self::unattended_ask`]. The TUI and RPC ignore it: there the answer is the reader's.
pub(crate) on_ask: luxe_core::config::OnAsk,
/// Whether an interactive session starts in walk-away mode (`--auto-approve`).
pub(crate) auto_approve: bool,
/// What the TUI's last engine was set to, for the next one to start from: a session left for
/// another keeps its mode, model and thinking level, as one loaded in place would. Overrides
/// [`Self::initial_mode`] and [`Self::initial_thinking`], which are for a launch.
pub(crate) carryover: Option<luxe_core::engine::Carryover>,
/// What startup found wrong before the engine existed, carried through to
/// [`luxe_core::engine::EngineConfig::startup_notices`] so every front-end reads it the same way.
pub(crate) startup_notices: Vec<String>,
/// The fraction of the usable window this engine compacts at, over `compaction.at`: the loop's
/// `--compact-percent`
pub(crate) compact_at: Option<f64>,
}
/// The mode `agent.default_mode` starts a session in, when it is not `build`, which needs no switch.
fn starting_mode(config: &luxe_core::config::Config) -> Option<String> {
config.agent.default_mode.clone().filter(|mode| mode.as_str() != luxe_core::mode::BUILD)
}
impl AgentSettings {
/// Resolve settings, letting `cli` overrides win over env and config.
pub(crate) fn resolve(repo_root: PathBuf, cli: CliOverrides) -> Self {
let config = load_luxe_config();
// What the last session picked, unless the user asked us not to remember. It sits *below*
// the CLI and the environment (a one-off `--model` must stay a one-off) and *above* the
// configured default, which is the point: the default is where you start, not where you are
// pinned.
let ui_config = luxe_core::config::Config::load(&repo_root);
let remembered = ui_config
.agent
.remember_model()
.then(luxe_core::runtime_state::RuntimeState::load)
.unwrap_or_default();
let named_provider = cli.provider.or_else(|| env_nonempty("LUXE_PROVIDER"));
let from_flag_or_env = cli.model.clone().or_else(|| env_nonempty("LUXE_MODEL"));
let (provider_in_model, from_flag_or_env) = match from_flag_or_env {
Some(model) => {
let (provider, id) = split_model_ref(&model, named_provider.as_deref(), &config);
(provider, Some(id))
}
None => (None, None),
};
let provider = named_provider
.or(provider_in_model)
.or_else(|| remembered.model.as_ref().map(|model| model.provider.clone()))
.or_else(|| config.default_provider.clone())
.unwrap_or_else(|| "openai_compat".to_string());
// A remembered model only applies to the provider it was chosen for: pairing last session's
// Anthropic model id with a locally forced provider would resolve to nothing.
let remembered_model = remembered
.model
.as_ref()
.filter(|model| model.provider == provider)
.map(|model| model.id.clone());
// A configured `default_model` belongs to the provider it was configured alongside. Pairing
// it with a provider forced on the command line produces combinations that don't exist —
// `claude-sonnet-5` on Codex — so it only applies when that provider can actually serve it.
let configured_model = config
.default_model
.clone()
.filter(|model| provider_serves(&provider, model, config.default_provider.as_deref()));
let model_from_flag_or_env = from_flag_or_env.is_some();
let chosen_model = from_flag_or_env.or(remembered_model).or(configured_model);
let provider_cfg = config.providers.get(&provider);
// Only the *explicit* sources land here. A sign-in, the provider's variable and its
// configured key resolve per request in the adapter's auth source, by the chain a
// `/model` switch uses too, so logging in mid-session takes effect without a relaunch.
let api_key = cli
.api_key
.or_else(|| env_nonempty("LUXE_API_KEY"))
.filter(|key| !key.trim().is_empty())
.map(ApiKey::new);
let base_url = active_base_url(cli.base_url, &provider, provider_cfg);
let model =
chosen_model.map(|id| crate::model_catalog::resolve_model(&config, &provider, &id).0);
let max_tool_iterations =
luxe_core::engine::max_tool_iterations_from_env(ui_config.agent.max_tool_iterations);
// A model that declares its own starting level is not overruled by the level some *other*
// model was last set to — that carry-over is the whole reason the field exists. `--thinking`
// still wins, at the call site.
let initial_thinking = match model.as_ref().and_then(|model| model.default_thinking) {
Some(_) => None,
None => remembered.thinking,
};
Self {
worktree: None,
issue: None,
pull_request: None,
work_root: repo_root.clone(),
state_root: repo_root,
spend_sink: None,
compat: resolve_compat(&provider, provider_cfg),
provider,
model,
// Only the two sources that belong to this invocation; a remembered or configured
// model is a default, and a mode may override a default.
model_forced: model_from_flag_or_env,
thinking_forced: false,
initial_mode: starting_mode(&ui_config),
review_engine: false,
base_url,
api_key,
resume: ResumeMode::New,
permission_mode: None,
trust_project: false,
initial_thinking,
max_tool_iterations,
// Opt-in, and only `luxe loop` opts in.
loop_driven: false,
// Per-run tool overrides; applied over the config deny-list at registry assembly.
disable_tools: Vec::new(),
enable_tools: Vec::new(),
on_ask: ui_config.agent.on_ask.unwrap_or_default(),
auto_approve: false,
carryover: None,
startup_notices: Vec::new(),
compact_at: None,
}
}
/// These settings pointed at `model`, with everything provider-specific re-resolved.
///
/// The reviewer or plan mode may name a model on a *different* provider than the session's — a
/// local model building with a hosted one reviewing is the configuration the loop exists for.
/// Swapping only the provider name and the id leaves the *session* provider's key, base URL and
/// compat flags attached to it: Anthropic requests at LM Studio's port with no credential, and
/// every phase advancing on an unavailable review. Everything that is not provider-specific —
/// repo root, permissions, spend sink, resume mode — carries over untouched.
///
/// The session's `--api-key` and `--base-url` deliberately do not: they were given for the
/// active provider, and handing one provider's key to another is worse than having none.
pub(super) fn for_model(&self, model: luxe_core::provider::ModelInfo) -> Self {
let provider = model.r#ref.provider.clone();
if provider == self.provider {
return Self { model: Some(model), ..self.clone() };
}
let config = load_luxe_config();
let provider_cfg = config.providers.get(&provider);
Self {
provider: provider.clone(),
model: Some(model),
// the provider's own chain finds its key, as it would on a `/model` switch
api_key: None,
base_url: resolve_base_url(&provider, provider_cfg),
compat: resolve_compat(&provider, provider_cfg),
..self.clone()
}
}
/// The chosen model, or the reason there is nothing to run.
///
/// For the entry points that cannot ask anybody: a headless run and a loop. An interactive
/// front-end does the opposite — it opens, and choosing is one of the things you do there.
/// Called *before* an engine is built, so a run with nothing chosen ends with a sentence the
/// reader can act on rather than a provider rejecting an empty model id.
pub(crate) fn require_model(&self) -> anyhow::Result<&luxe_core::provider::ModelInfo> {
self.model.as_ref().ok_or_else(|| {
// The config path is asked for rather than spelled: it is `~/.config` on one platform
// and nowhere near it on the others.
let models = luxe_core::user_dirs::config_path_display("models.json");
anyhow::anyhow!(
"no model selected — pass --model <provider/id>, set LUXE_MODEL, or add \
\"default_model\" to {models}. `luxe models list` shows what this machine can \
reach; in the TUI, `/model` picks one and remembers it."
)
})
}
/// How this run resolves an `ask`, for the front-ends that have nobody to ask.
///
/// Headless, `luxe loop` and a review agent call this instead of naming
/// [`luxe_core::permission::AskResolution::AutoAllow`] themselves, so the setting reaches every
/// unattended surface at once rather than three places agreeing by hand. A `deny` rule is
/// enforced either way; this only settles the middle answer.
pub(crate) fn unattended_ask(&self) -> luxe_core::permission::AskResolution {
self.on_ask.resolution()
}
/// The model an engine is built with: the chosen one, or an **unset** stand-in.
///
/// The stand-in exists for the TUI, which opens on a dashboard where choosing a model is one of
/// the things you do — so it needs an engine before there is an answer. It carries an empty id
/// ([`luxe_core::provider::ModelRef::is_unset`]) rather than a plausible one, which is the whole
/// point: the engine refuses the turn, and a gap in that refusal would fail at the provider
/// instead of billing a guess. Resolved through the same catalog layers as a real model, so the
/// window and output cap the engine does arithmetic with are sane numbers.
pub(crate) fn launch_model(&self) -> luxe_core::provider::ModelInfo {
self.model.clone().unwrap_or_else(|| {
crate::model_catalog::resolve_model(&load_luxe_config(), &self.provider, "").0
})
}
/// Name to show in the UI: the resolved display name, or nothing when no model is chosen.
pub(crate) fn display_model(&self) -> Option<String> {
self.model.as_ref().map(|model| model.display().to_string())
}
/// The reasoning level this session begins on, as the model would actually run it.
///
/// The same answer the engine reaches from [`Self::initial_thinking`] and the model's own
/// configured level, so a front-end can paint its first frame without waiting for the engine's
/// first `StateChanged` — and cannot disagree with it. With no model chosen there is nothing to
/// clamp against, so the requested level stands.
pub(crate) fn starting_thinking(&self) -> luxe_core::provider::ThinkingLevel {
let Some(model) = &self.model else {
return self.initial_thinking.unwrap_or_default();
};
let requested = self.initial_thinking.or(model.default_thinking).unwrap_or_default();
model.effective_thinking_level(requested)
}
}
#[cfg(test)]
impl AgentSettings {
/// The model these settings chose, for a test that set one up.
///
/// The panic is the assertion: every caller is checking *which* model was resolved, and "none"
/// is a different test.
pub(crate) fn chosen(&self) -> &luxe_core::provider::ModelInfo {
self.model.as_ref().expect("these settings chose a model")
}
}

View File

@@ -0,0 +1,31 @@
//! Run-scoped spend accounting — one figure for a loop, across every engine it uses.
//!
//! A session ledger is reset and rebuilt whenever a session is loaded, and a loop run loads several:
//! it starts fresh sessions as it goes, and every phase review runs in an engine and a session of its
//! own. So the run's total is kept beside the phase counter in `.luxe/loop_state.json`, and both
//! engines report into it through [`luxe_core::usage::SpendSink`].
use std::sync::Arc;
use luxe_core::loop_controller::LoopController;
use luxe_core::usage::{SpendSink, UsageSource, UsageTotals};
/// Adds every engine's provider calls to the loop run's total.
#[derive(Debug)]
pub(crate) struct LoopSpendSink {
controller: Arc<LoopController>,
}
impl LoopSpendSink {
/// A sink writing into `controller`'s state.
pub(crate) fn new(controller: Arc<LoopController>) -> Self {
Self { controller }
}
}
#[async_trait::async_trait]
impl SpendSink for LoopSpendSink {
async fn record(&self, model_id: &str, _source: UsageSource, totals: &UsageTotals) {
self.controller.record_spend(model_id, totals).await;
}
}

View File

@@ -0,0 +1,36 @@
//! Test environment — isolation for the two things config resolution reads that a process shares.
//!
//! One owner, because more than one module's tests need it and two locks do not serialize against
//! each other — which is the failure mode this exists to prevent.
/// Env + real config are process-global; serialize the tests that touch them. `cargo test`
/// runs tests as threads in one process, so a test that skips this lock does not only risk
/// itself — it corrupts the environment under whichever locked test is mid-flight. Recover
/// from poisoning rather than `unwrap`, or one genuine failure cascades into a screenful of
/// fictional ones.
pub(crate) static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// Point config discovery at an empty temp dir and clear the provider/model env so
/// resolution is deterministic and host-independent.
pub(crate) fn isolated_env() -> tempfile::TempDir {
let dir = tempfile::tempdir().expect("a temp dir");
std::env::set_var("XDG_CONFIG_HOME", dir.path());
// The *state* dir too: a remembered model outranks `default_model`, so a developer who has
// ever used `/model` would have their own choice resolved here instead of the fixture's,
// and the suite would pass or fail depending on whose machine ran it.
std::env::set_var("XDG_STATE_HOME", dir.path().join("state"));
for var in [
"LUXE_PROVIDER",
"LUXE_MODEL",
"LUXE_API_KEY",
"LUXE_BASE_URL",
"LUXE_CONFIG_DIR",
"LUXE_STATE_DIR",
"OPENAI_API_KEY",
"OPENAI_BASE_URL",
"ANTHROPIC_API_KEY",
] {
std::env::remove_var(var);
}
dir
}

View File

@@ -0,0 +1,728 @@
#[cfg(unix)]
use super::config::perms_are_loose;
use super::*;
/// A repository root for the tests that only need *a* path.
///
/// Nothing below touches the filesystem — `build_tool_registry` and `collect_tooling_summary`
/// only carry the root into what they build — so this has to be portable, not real, and a
/// literal `/tmp/…` is neither on Windows.
fn unused_repo_root() -> std::path::PathBuf {
std::env::temp_dir().join("luxe-registry-shape")
}
/// Closing waits for the engine's way out, which is where `SessionEnd` runs — and gives up at
/// the grace rather than holding an exit hostage.
///
/// Headless used to send `Close` and return from `main`, so the runtime dropped the engine
/// mid-hook and not one `SessionEnd` hook ever fired there.
#[tokio::test]
async fn closing_waits_for_the_engine_but_not_forever() {
let (actions, mut received) = mpsc::channel::<Action>(1);
let finished = Arc::new(std::sync::atomic::AtomicBool::new(false));
let flag = finished.clone();
let task = tokio::spawn(async move {
received.recv().await;
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
flag.store(true, std::sync::atomic::Ordering::SeqCst);
luxe_core::engine::Carryover::default()
});
EngineCloser { task, grace: std::time::Duration::from_secs(5) }.close(&actions).await;
assert!(finished.load(std::sync::atomic::Ordering::SeqCst), "the way out was waited for");
let (actions, _received) = mpsc::channel::<Action>(1);
let stuck = tokio::spawn(std::future::pending::<luxe_core::engine::Carryover>());
let started = std::time::Instant::now();
EngineCloser { task: stuck, grace: std::time::Duration::from_millis(100) }
.close(&actions)
.await;
assert!(started.elapsed() < std::time::Duration::from_secs(2), "bounded by the grace");
}
#[tokio::test]
async fn tooling_summary_has_builtins_and_paths() {
// The summary reads the global MCP config and, for an OAuth server, the token store: this
// machine's, unless both are pointed somewhere empty
let (config, state) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
std::env::set_var("XDG_CONFIG_HOME", config.path());
std::env::set_var("XDG_STATE_HOME", state.path());
let root = &unused_repo_root();
let summary = collect_tooling_summary(root, &build_lsp_service(), &shared_dap_service()).await;
// Built-ins are always present regardless of what's installed on the host.
let langs: Vec<&str> = summary.servers.iter().map(|s| s.language.as_str()).collect();
for lang in ["rust", "typescript", "python", "go", "cpp", "bash"] {
assert!(langs.contains(&lang), "summary missing built-in server {lang}: {langs:?}");
}
let adapters: Vec<&str> = summary.adapters.iter().map(|a| a.id.as_str()).collect();
for id in ["debugpy", "codelldb", "dlv"] {
assert!(adapters.contains(&id), "summary missing built-in adapter {id}: {adapters:?}");
}
// No server has been started for a root nothing has opened, so nothing is running yet.
assert!(summary.servers.iter().all(|s| !s.running));
assert!(summary.lsp_config_path.is_some());
assert!(summary.adapters_config_path.is_some());
}
/// Warm a real language server (clangd) and confirm `/lsp` reports it running. Gated behind
/// `LUXE_TEST_LSP_RUNNING=1` (needs clangd on PATH; starts a server process) so it stays out
/// of the default suite.
#[tokio::test]
async fn running_server_is_reported_after_warming() {
if std::env::var("LUXE_TEST_LSP_RUNNING").as_deref() != Ok("1") {
eprintln!("skipping: set LUXE_TEST_LSP_RUNNING=1 (needs clangd) to run");
return;
}
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
std::fs::write(root.join("compile_commands.json"), "[]").unwrap();
let source = root.join("main.c");
std::fs::write(&source, "int main(void){return 0;}\n").unwrap();
let lsp = build_lsp_service();
// Warming inserts the client into the service's map, which is what running-state reads.
let warmed = lsp.client_for_path(&source).await;
assert!(warmed.is_some(), "clangd should start for a .c file");
let summary = collect_tooling_summary(root, &lsp, &shared_dap_service()).await;
let cpp = summary.servers.iter().find(|s| s.language == "cpp").expect("cpp entry");
assert!(cpp.installed, "clangd is on PATH in this gated env");
assert!(cpp.running, "cpp should be reported running after warming: {summary:?}");
// Leaving the project shuts the server down, so it's no longer reported running.
lsp.shutdown_all().await;
let after = collect_tooling_summary(root, &lsp, &shared_dap_service()).await;
let cpp = after.servers.iter().find(|s| s.language == "cpp").expect("cpp entry");
assert!(!cpp.running, "cpp should stop running after shutdown_all: {after:?}");
}
#[test]
fn tool_registry_has_builtins_and_lsp() {
let reg =
build_tool_registry(&unused_repo_root(), &unused_repo_root(), build_lsp_service(), false);
let names = reg.names();
for expected in [
"read",
"write",
"edit",
"bash",
"read_symbol",
"module_report",
"symbol_search",
"grep",
"glob",
"git",
"todo",
"lsp_diagnostics",
"lsp_navigation",
"web_fetch",
] {
assert!(names.contains(&expected), "tool registry missing '{expected}': {names:?}");
}
// `debug` is deliberately conditional — it carries the largest schema in the set and is
// registered only where an adapter exists. Asserting it unconditionally was an assertion
// about the machine, and it failed on any host without a debugger installed.
assert_eq!(
names.contains(&"debug"),
shared_dap_service().has_adapter(),
"debug is registered exactly when this machine can debug: {names:?}"
);
}
/// The loop is opt-in, so nothing it owns may reach an ordinary session.
///
/// `loop_control` was registered unconditionally, and since it is not a core tool it landed in
/// the "available on demand" catalog of every prompt Luxe sent — offering a plain chat session a
/// tool for advancing phases of an autonomous run that was not happening.
#[test]
fn loop_control_is_absent_unless_a_loop_is_driving() {
let repo = &unused_repo_root();
let ordinary = build_tool_registry(repo, repo, build_lsp_service(), false);
assert!(
!ordinary.names().contains(&"loop_control"),
"an ordinary session was offered loop_control: {:?}",
ordinary.names()
);
let looped = build_tool_registry(repo, repo, build_lsp_service(), true);
assert!(
looped.names().contains(&"loop_control"),
"...and the loop still gets it: {:?}",
looped.names()
);
}
/// Resolved settings never opt into the loop; only the `loop` subcommand sets that.
#[test]
fn resolved_settings_are_not_loop_driven() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
let settings = AgentSettings::resolve(PathBuf::from("."), CliOverrides::default());
assert!(!settings.loop_driven);
}
use crate::engine_setup::test_env::{isolated_env, ENV_LOCK};
#[cfg(unix)]
/// File modes are a unix idea; Windows has no bits to be loose about.
#[test]
#[cfg(unix)]
fn loose_secret_perms_are_flagged() {
// 0600/0400 are fine; any group/other bit is loose.
assert!(!perms_are_loose(0o600));
assert!(!perms_are_loose(0o400));
assert!(perms_are_loose(0o640)); // group-readable
assert!(perms_are_loose(0o604)); // other-readable
assert!(perms_are_loose(0o644));
assert!(perms_are_loose(0o660));
}
/// Re-picking a model you already chose is a tax on the person who already decided.
#[test]
fn a_remembered_model_beats_the_configured_default_but_not_a_flag() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let home = tempfile::tempdir().expect("temp home");
let state = home.path().join("state");
std::fs::create_dir_all(&state).expect("state dir");
luxe_core::runtime_state::RuntimeState {
schema_version: luxe_core::runtime_state::RUNTIME_STATE_SCHEMA_VERSION,
model: Some(luxe_core::runtime_state::RememberedModel {
provider: "anthropic".into(),
id: "claude-opus-5".into(),
}),
thinking: Some(luxe_core::provider::ThinkingLevel::High),
recent_commands: Vec::new(),
panes: Default::default(),
}
.save_to(&state.join("state.json"))
.expect("write state");
// Scoped env: these tests share a process, so the guard restores what it found.
let _state_dir = EnvGuard::set("LUXE_STATE_DIR", state.to_str().expect("utf-8 path"));
let project = tempfile::tempdir().expect("temp project");
let remembered = AgentSettings::resolve(project.path().to_path_buf(), CliOverrides::default());
assert_eq!(remembered.provider, "anthropic");
assert_eq!(remembered.chosen().r#ref.id, "claude-opus-5");
assert_eq!(remembered.initial_thinking, Some(luxe_core::provider::ThinkingLevel::High));
// A one-off flag stays a one-off.
let overridden = AgentSettings::resolve(
project.path().to_path_buf(),
CliOverrides { model: Some("claude-sonnet-5".into()), ..CliOverrides::default() },
);
assert_eq!(overridden.chosen().r#ref.id, "claude-sonnet-5");
}
/// A remembered model must not be pasted onto a different provider.
#[test]
fn a_remembered_model_is_ignored_when_the_provider_is_forced_elsewhere() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let home = tempfile::tempdir().expect("temp home");
let state = home.path().join("state");
std::fs::create_dir_all(&state).expect("state dir");
luxe_core::runtime_state::RuntimeState {
schema_version: luxe_core::runtime_state::RUNTIME_STATE_SCHEMA_VERSION,
model: Some(luxe_core::runtime_state::RememberedModel {
provider: "anthropic".into(),
id: "claude-opus-5".into(),
}),
thinking: None,
recent_commands: Vec::new(),
panes: Default::default(),
}
.save_to(&state.join("state.json"))
.expect("write state");
let _state_dir = EnvGuard::set("LUXE_STATE_DIR", state.to_str().expect("utf-8 path"));
// A machine with a `default_model` of its own would otherwise answer for the remembered one
let config = home.path().join("config");
let _config_dir = EnvGuard::set("LUXE_CONFIG_DIR", config.to_str().expect("utf-8 path"));
let project = tempfile::tempdir().expect("temp project");
let settings = AgentSettings::resolve(
project.path().to_path_buf(),
CliOverrides { provider: Some("openai_compat".into()), ..CliOverrides::default() },
);
assert_eq!(settings.provider, "openai_compat");
// And nothing takes its place: the fallback that used to stand here was a literal.
assert_eq!(settings.model, None);
}
/// The key `settings`' provider would send in `header`, by the chain a request resolves it with.
fn sent_key(settings: &AgentSettings, header: &str) -> Option<String> {
let config = super::config::load_luxe_config();
let auth = super::provider::active_auth(settings, config.providers.get(&settings.provider));
let runtime =
tokio::runtime::Builder::new_current_thread().enable_all().build().expect("runtime");
let resolved = runtime.block_on(auth.request_auth()).ok()?;
resolved
.headers
.into_iter()
.find(|(name, _)| name == header)
.map(|(_, key)| key.expose().into())
}
/// A reviewer's model on another provider brings that provider's credential and endpoint.
///
/// The break this catches, measured on a real run: the loop's reviewer took the session's
/// settings with only `provider` and `model` swapped, so a Claude reviewer behind a local
/// developer inherited LM Studio's (absent) key and its `127.0.0.1:1234` base URL. Every review
/// failed with "no credential for 'anthropic'", every failure counted as *unavailable* rather
/// than a refusal, and four phases advanced in three minutes with nothing reviewed at all.
#[test]
fn a_role_model_on_another_provider_is_pointed_at_that_provider() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let home = isolated_env();
std::fs::create_dir_all(home.path().join("luxe")).expect("config dir");
std::fs::write(
home.path().join("luxe").join("models.json"),
r#"{
"providers": {
"lmstudio": { "base_url": "http://127.0.0.1:1234/v1" },
"anthropic": { "api_key": "sk-ant-fixture" }
}
}"#,
)
.expect("write models.json");
let local = AgentSettings::resolve(
PathBuf::from("."),
CliOverrides { provider: Some("lmstudio".into()), ..Default::default() },
);
assert_eq!(local.base_url.as_deref(), Some("http://127.0.0.1:1234/v1"));
assert_eq!(sent_key(&local, "authorization"), None, "a local endpoint needs no key");
let reviewer = local.for_model(luxe_core::provider::ModelInfo {
r#ref: luxe_core::provider::ModelRef::new("anthropic", "claude-sonnet-5"),
..Default::default()
});
assert_eq!(reviewer.provider, "anthropic");
assert_eq!(reviewer.chosen().r#ref.id, "claude-sonnet-5");
assert_eq!(
sent_key(&reviewer, "x-api-key").as_deref(),
Some("sk-ant-fixture"),
"the reviewer must carry anthropic's own credential"
);
assert_ne!(
reviewer.base_url.as_deref(),
Some("http://127.0.0.1:1234/v1"),
"a hosted reviewer must not be sent to the local developer's port"
);
assert_eq!(reviewer.state_root, local.state_root, "the project carries over");
assert_eq!(reviewer.work_root, local.work_root, "and so does the checkout it works in");
}
/// Staying on one provider changes the model and nothing else.
#[test]
fn a_role_model_on_the_same_provider_keeps_the_session_s_endpoint() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let _home = isolated_env();
let local = AgentSettings::resolve(
PathBuf::from("."),
CliOverrides {
provider: Some("lmstudio".into()),
base_url: Some("http://127.0.0.1:1234/v1".into()),
..Default::default()
},
);
let switched = local.for_model(luxe_core::provider::ModelInfo {
r#ref: luxe_core::provider::ModelRef::new("lmstudio", "another-local-model"),
..Default::default()
});
assert_eq!(switched.chosen().r#ref.id, "another-local-model");
assert_eq!(switched.base_url, local.base_url, "same provider, same endpoint");
}
/// Restores an environment variable to whatever it was, so sibling tests are unaffected.
struct EnvGuard {
key: &'static str,
previous: Option<String>,
}
impl EnvGuard {
fn set(key: &'static str, value: &str) -> Self {
let previous = std::env::var(key).ok();
std::env::set_var(key, value);
Self { key, previous }
}
}
impl Drop for EnvGuard {
fn drop(&mut self) {
match self.previous.take() {
Some(value) => std::env::set_var(self.key, value),
None => std::env::remove_var(self.key),
}
}
}
/// Nothing configured means nothing chosen. Luxe used to reach for whichever id the provider
/// catalog named first, which is a literal in the binary: it goes stale as models turn over,
/// and the first thing a fresh install did with it was send it.
#[test]
fn nothing_configured_chooses_no_model() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let _tmp = isolated_env();
let s = AgentSettings::resolve(PathBuf::from("."), CliOverrides::default());
assert_eq!(s.provider, "openai_compat");
assert_eq!(s.model, None);
assert!(s.display_model().is_none());
assert!(s.require_model().is_err(), "a run with nothing chosen must not start");
assert_eq!(sent_key(&s, "authorization"), None, "and no key to send");
// And what an engine is built with instead names no model at all, so the turn is refused
// rather than sent somewhere plausible.
assert!(s.launch_model().r#ref.is_unset());
assert_eq!(s.launch_model().r#ref.provider, "openai_compat");
}
/// Forcing a provider does not conjure one of its models either.
#[test]
fn forcing_a_provider_chooses_no_model() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let _tmp = isolated_env();
let cli = CliOverrides { provider: Some("anthropic".into()), ..Default::default() };
let s = AgentSettings::resolve(PathBuf::from("."), cli);
assert_eq!(s.provider, "anthropic");
assert_eq!(s.model, None);
// The stand-in still resolves through the catalog layers, so the Anthropic API's own floors
// apply and the engine is doing arithmetic with real numbers.
assert!(s.launch_model().reasoning);
assert!(s.launch_model().max_tokens > 0);
}
/// `--model provider/id` picks the provider too, the form the "no model selected" error asks
/// for; an id that merely contains a slash, or a prefix another provider was named over, stays
/// whole.
#[test]
fn a_model_can_name_its_provider() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let _tmp = isolated_env();
let flags = |provider: Option<&str>, model: &str| CliOverrides {
provider: provider.map(str::to_string),
model: Some(model.to_string()),
..Default::default()
};
let s = AgentSettings::resolve(PathBuf::from("."), flags(None, "openai-codex/gpt-5.4"));
assert_eq!((s.provider.as_str(), s.chosen().r#ref.id.as_str()), ("openai-codex", "gpt-5.4"));
let s =
AgentSettings::resolve(PathBuf::from("."), flags(Some("openrouter"), "anthropic/claude-x"));
assert_eq!(s.provider, "openrouter");
assert_eq!(s.chosen().r#ref.id, "anthropic/claude-x", "openrouter's own id");
let s = AgentSettings::resolve(PathBuf::from("."), flags(None, "deepseek-ai/r1"));
assert_eq!(s.chosen().r#ref.id, "deepseek-ai/r1", "not a provider, so not split");
std::env::set_var("LUXE_MODEL", "anthropic/claude-opus-5-5");
let s = AgentSettings::resolve(PathBuf::from("."), CliOverrides::default());
std::env::remove_var("LUXE_MODEL");
assert_eq!(
(s.provider.as_str(), s.chosen().r#ref.id.as_str()),
("anthropic", "claude-opus-5-5")
);
}
#[test]
fn cli_overrides_win_over_env() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let _tmp = isolated_env();
std::env::set_var("LUXE_PROVIDER", "openai_compat");
std::env::set_var("LUXE_MODEL", "gpt-4o");
std::env::set_var("LUXE_API_KEY", "env-key");
let cli = CliOverrides {
provider: Some("anthropic".into()),
model: Some("claude-x".into()),
api_key: Some("cli-key".into()),
base_url: Some("https://proxy/v1".into()),
};
let s = AgentSettings::resolve(PathBuf::from("."), cli);
assert_eq!(s.provider, "anthropic");
assert_eq!(s.chosen().r#ref.id, "claude-x");
assert_eq!(s.api_key.as_ref().map(|k| k.expose()), Some("cli-key"));
assert_eq!(s.base_url.as_deref(), Some("https://proxy/v1"));
std::env::remove_var("LUXE_PROVIDER");
std::env::remove_var("LUXE_MODEL");
std::env::remove_var("LUXE_API_KEY");
}
#[test]
fn nested_auth_json_is_read() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let tmp = isolated_env();
let luxe_dir = tmp.path().join("luxe");
std::fs::create_dir_all(&luxe_dir).unwrap();
std::fs::write(
luxe_dir.join("auth.json"),
r#"{
"providers": {
"anthropic": { "api_key": "sk-ant-from-file" }
},
"default_provider": "anthropic",
"default_model": "claude-3-5-haiku-latest"
}"#,
)
.unwrap();
let s = AgentSettings::resolve(PathBuf::from("."), CliOverrides::default());
assert_eq!(s.provider, "anthropic");
assert_eq!(s.chosen().r#ref.id, "claude-3-5-haiku-latest");
assert_eq!(sent_key(&s, "x-api-key").as_deref(), Some("sk-ant-from-file"));
}
#[test]
fn model_thinking_map_reaches_runtime_settings() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let tmp = isolated_env();
let luxe_dir = tmp.path().join("luxe");
std::fs::create_dir_all(&luxe_dir).unwrap();
std::fs::write(
luxe_dir.join("models.json"),
r#"{
"default_provider": "openai_compat",
"default_model": "gpt-5.6-sol",
"models": {
"openai_compat/gpt-5.6-sol": {
"reasoning": true,
"thinking_level_map": {
"minimal": "low",
"xhigh": "xhigh",
"max": "max"
}
}
}
}"#,
)
.unwrap();
let settings = AgentSettings::resolve(PathBuf::from("."), CliOverrides::default());
assert!(settings.chosen().reasoning);
let map = &settings.chosen().thinking_level_map;
assert_eq!(map.get("minimal").and_then(|value| value.as_deref()), Some("low"));
assert_eq!(map.get("max").and_then(|value| value.as_deref()), Some("max"));
}
/// A model that declares where it starts is not handed the level another model was left on.
///
/// The startup half of the same rule the engine enforces on a switch, and the reason the
/// remembered level is *dropped* rather than applied and overridden: applying it is what writes
/// it back, so a model's own default would become permanently remembered the first time it
/// fired — for every other model too.
#[test]
fn a_models_own_thinking_level_outranks_the_remembered_one() {
use luxe_core::provider::ThinkingLevel;
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let tmp = isolated_env();
let luxe_dir = tmp.path().join("luxe");
std::fs::create_dir_all(&luxe_dir).unwrap();
std::fs::write(
luxe_dir.join("models.json"),
r#"{
"default_provider": "lmstudio",
"default_model": "qwen3.8-27b",
"models": {
"lmstudio/qwen3.8-27b": {
"reasoning": true,
"thinking": "medium",
"thinking_level_map": {
"off": "none", "low": "low", "medium": "medium",
"high": "high", "xhigh": "xhigh"
}
},
"lmstudio/some-other-build": { "reasoning": true }
}
}"#,
)
.unwrap();
let state = tmp.path().join("state");
std::fs::create_dir_all(&state).unwrap();
luxe_core::runtime_state::RuntimeState {
schema_version: luxe_core::runtime_state::RUNTIME_STATE_SCHEMA_VERSION,
model: None,
thinking: Some(ThinkingLevel::XHigh),
recent_commands: Vec::new(),
panes: Default::default(),
}
.save_to(&state.join("state.json"))
.unwrap();
let _state_dir = EnvGuard::set("LUXE_STATE_DIR", state.to_str().unwrap());
let declared = AgentSettings::resolve(PathBuf::from("."), CliOverrides::default());
assert_eq!(declared.chosen().default_thinking, Some(ThinkingLevel::Medium));
assert_eq!(declared.initial_thinking, None, "the remembered level is not sent over it");
assert_eq!(declared.starting_thinking(), ThinkingLevel::Medium);
// An explicit flag still wins — it is set on top of the resolved settings, as `run` does.
let mut flagged = declared.clone();
flagged.initial_thinking = Some(ThinkingLevel::XHigh);
assert_eq!(flagged.starting_thinking(), ThinkingLevel::XHigh);
// A sibling on the same server that declares nothing still gets the remembered level.
let undeclared = AgentSettings::resolve(
PathBuf::from("."),
CliOverrides { model: Some("some-other-build".into()), ..CliOverrides::default() },
);
assert_eq!(undeclared.chosen().default_thinking, None);
assert_eq!(undeclared.initial_thinking, Some(ThinkingLevel::XHigh));
// Clamped for display, because that build advertises no thinking map and `xhigh` is opt-in
// — the level a request would really carry, which is the point of reporting it here.
assert_eq!(undeclared.starting_thinking(), ThinkingLevel::High);
}
#[test]
fn permission_config_loads_global_and_project_tighten_only() {
use luxe_core::permission::{build_request, PermissionAction};
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let tmp = isolated_env();
// Global config: bash asks.
let global_dir = tmp.path().join("luxe");
std::fs::create_dir_all(&global_dir).unwrap();
std::fs::write(global_dir.join("permissions.json"), r#"{ "permission": { "bash": "ask" } }"#)
.unwrap();
// Project config tries to LOOSEN bash to allow and TIGHTEN edit to deny.
let repo = tempfile::tempdir().unwrap();
std::fs::create_dir_all(repo.path().join(".luxe")).unwrap();
std::fs::write(
repo.path().join(".luxe").join("permissions.json"),
r#"{ "permission": { "bash": "allow", "edit": "deny" } }"#,
)
.unwrap();
let bash = build_request("bash", &serde_json::json!({"command": "ls"}), repo.path());
let edit = build_request("edit", &serde_json::json!({"path": "src/x.rs"}), repo.path());
// Untrusted: project can tighten (edit->deny) but not loosen (bash stays ask).
let untrusted = load_permission_engine(repo.path(), None, false);
assert_eq!(untrusted.decide(&bash), PermissionAction::Ask, "project can't loosen bash");
assert_eq!(untrusted.decide(&edit), PermissionAction::Deny, "project tightened edit");
// Trusted: project may loosen (bash->allow).
let trusted = load_permission_engine(repo.path(), None, true);
assert_eq!(trusted.decide(&bash), PermissionAction::Allow, "trust lets project loosen");
}
#[test]
fn permission_mode_override_beats_config() {
use luxe_core::permission::{build_request, PermissionAction, PermissionMode};
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let _tmp = isolated_env();
let repo = tempfile::tempdir().unwrap();
// No config files: read-only override should deny a mutating tool.
let engine = load_permission_engine(repo.path(), Some(PermissionMode::ReadOnly), false);
let edit = build_request("edit", &serde_json::json!({"path": "src/x.rs"}), repo.path());
assert_eq!(engine.decide(&edit), PermissionAction::Deny);
}
/// A loop's `--compact-percent` is the threshold its engine compacts at, over the project's own,
/// and eliding moves with it; without one the project's stands.
#[test]
fn the_loop_s_mark_is_the_engine_s_compaction_threshold() {
let config = luxe_core::config::CompactionConfig { at: Some(0.25), ..Default::default() };
let looped = super::compaction_settings(Some(0.4), &config);
assert_eq!(looped.compact_at_fraction, 0.4);
assert!((looped.prune_at_fraction - 0.3).abs() < 1e-9, "{}", looped.prune_at_fraction);
assert_eq!(super::compaction_settings(None, &config).compact_at_fraction, 0.25);
}
/// A model named in `compaction.summarizer` comes with the catalog's rates and window, so `/cost`
/// prices the summary call like any other instead of showing its spend as unpriced.
#[test]
fn a_named_summarizer_is_priced_like_any_other_model() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let tmp = isolated_env();
// the embedded catalog only, not this machine's refreshed copy
let no_cache = tmp.path().join("no-cache.json");
let _catalog = EnvGuard::set("LUXE_MODELS_DEV_PATH", &no_cache.to_string_lossy());
let config = luxe_core::config::CompactionConfig {
summarizer: Some("anthropic/claude-haiku-4-5".into()),
..Default::default()
};
let settings = super::compaction_settings(None, &config);
let active = luxe_core::provider::ModelInfo {
r#ref: luxe_core::provider::ModelRef::new("openai", "gpt-5.6-sol"),
..Default::default()
};
let summarizer = luxe_core::compaction::summarizer_model(settings.summarizer.as_ref(), &active);
assert_eq!(summarizer.r#ref.id, "claude-haiku-4-5");
assert!(summarizer.cost.input > 0.0 && summarizer.cost.output > 0.0, "{:?}", summarizer.cost);
assert_ne!(
summarizer.context_window,
luxe_core::provider::ModelInfo::default().context_window,
"and its own window, for the summary's cap"
);
}
/// `"herdr": false` turns the engine's Herdr reports off too, not only the interface's.
#[test]
fn herdr_reports_follow_the_config_switch() {
let _guard = test_env::ENV_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
std::env::set_var("HERDR_ENV", "1");
std::env::set_var("HERDR_PANE_ID", "w1:p1");
std::env::remove_var("LUXE_HERDR");
let on = herdr_hook(&luxe_core::config::Config::default()).is_some();
let off: luxe_core::config::Config =
serde_json::from_str(r#"{ "herdr": false }"#).expect("a config");
let off = herdr_hook(&off).is_some();
std::env::remove_var("HERDR_ENV");
std::env::remove_var("HERDR_PANE_ID");
assert!(on, "inside Herdr, on by default");
assert!(!off, "switched off in config");
}
/// `plan.thinking` holds over a level remembered from the last session; only `--thinking` beats it.
#[test]
fn plan_thinking_wins_over_a_remembered_level() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let _env = test_env::isolated_env();
let config: luxe_core::config::Config =
serde_json::from_str(r#"{ "plan": { "thinking": "high" } }"#).expect("a config");
let mut settings = AgentSettings::resolve(PathBuf::from("."), CliOverrides::default());
settings.initial_thinking = Some(luxe_core::provider::ThinkingLevel::Low);
let plan = |settings: &AgentSettings| {
build_modes(settings, &config).get(luxe_core::mode::PLAN).and_then(|mode| mode.thinking)
};
assert_eq!(plan(&settings), Some(luxe_core::provider::ThinkingLevel::High), "remembered");
settings.thinking_forced = true;
assert_eq!(plan(&settings), None, "--thinking on the command line");
}
/// An engine that is still running when the grace runs out is stopped, not left behind.
///
/// The break this catches: the closer gave up waiting and dropped the task's handle, which detaches
/// it, so the TUI started the next session's engine while the last one still ran, possibly in a
/// checkout the process had just left.
#[tokio::test]
async fn an_engine_that_outlives_its_grace_is_stopped() {
struct Dropped(std::sync::Arc<std::sync::atomic::AtomicBool>);
impl Drop for Dropped {
fn drop(&mut self) {
self.0.store(true, std::sync::atomic::Ordering::SeqCst);
}
}
let stopped = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let flag = Dropped(stopped.clone());
let task = tokio::spawn(async move {
let _flag = flag;
std::future::pending::<luxe_core::engine::Carryover>().await
});
let (actions, _rx) = tokio::sync::mpsc::channel(4);
let closer = EngineCloser { task, grace: std::time::Duration::from_millis(20) };
let carryover = closer.close(&actions).await;
assert!(stopped.load(std::sync::atomic::Ordering::SeqCst), "the engine's task was stopped");
assert!(carryover.is_none(), "and a stopped engine hands nothing over");
}
/// An engine that closes in time hands over what the reader set it to, for the next one.
#[tokio::test]
async fn an_engine_that_closes_hands_over_its_carryover() {
let task = tokio::spawn(async { luxe_core::engine::Carryover::default() });
let (actions, _rx) = tokio::sync::mpsc::channel(4);
let closer = EngineCloser { task, grace: std::time::Duration::from_secs(5) };
assert!(closer.close(&actions).await.is_some());
}

View File

@@ -0,0 +1,250 @@
//! Tooling status collection for the `/lsp`, `/debug`, and `/mcp` views — built-in defaults
//! merged with user config, a live PATH check, warm-server state, and active debug sessions.
use super::services::{command_on_path, load_debug_adapters, load_lsp_servers, SharedLspService};
/// Assemble the merged LSP-server + debug-adapter status for the `/lsp` and `/debug` views: built-in
/// defaults plus the user's config files, a live PATH installed-check, the warm servers running
/// under `root`, and any active debug sessions. Rebuilt by the collector each snapshot so the views
/// stay fresh (config edits, mid-session installs, live sessions) without a restart.
pub(crate) async fn collect_tooling_summary(
root: &std::path::Path,
lsp_service: &SharedLspService,
dap_service: &luxe_dap::DapService,
) -> luxe_core::ToolingSummary {
use luxe_core::{DebugAdapterStatus, DebugSessionStatus, LanguageServerStatus, ToolingSummary};
// Warm servers under the active project root → the set of "running" languages.
let running_langs: std::collections::HashSet<String> = lsp_service
.running_servers()
.into_iter()
.filter(|(_, server_root)| server_root.starts_with(root) || root.starts_with(server_root))
.map(|(lang, _)| lang)
.collect();
// LSP catalog: built-ins merged with lsp-servers.json (a config id overrides a built-in).
let user_servers = load_lsp_servers();
let mut registry = luxe_lsp::ServerRegistry::new();
registry.merge_patches(user_servers.clone());
let mut servers: Vec<LanguageServerStatus> = registry
.iter()
.map(|(language, entry)| LanguageServerStatus {
language: language.clone(),
command: entry.command.clone(),
extensions: entry.extensions.clone(),
from_config: user_servers.contains_key(language),
install_hint: entry.install_hint.clone(),
installed: command_on_path(&entry.command),
running: running_langs.contains(language),
})
.collect();
servers.sort_by(|a, b| a.language.cmp(&b.language));
// Debug adapters: built-ins, minus any shadowed by a user id, plus the user's own.
let adapters: Vec<DebugAdapterStatus> =
super::services::merged_debug_adapters(&load_debug_adapters())
.into_iter()
.map(|(adapter, from_config)| DebugAdapterStatus {
installed: command_on_path(adapter.spec.command.first().map_or("", String::as_str)),
id: adapter.spec.id.clone(),
command: adapter.spec.command.join(" "),
extensions: adapter.extensions,
from_config,
})
.collect();
let debug_sessions = dap_service
.list()
.await
.into_iter()
.map(|s| DebugSessionStatus {
id: s.id,
adapter: s.adapter,
program: s.program,
terminated: s.terminated,
stopped: s.stopped,
stop_reason: s.stop_reason,
})
.collect();
ToolingSummary {
servers,
adapters,
debug_sessions,
mcp_servers: collect_mcp_servers(root),
tools: super::services::tool_statuses(),
lsp_config_path: Some(luxe_core::config::Config::lsp_servers_path()),
adapters_config_path: Some(luxe_core::config::Config::debug_adapters_path()),
}
}
/// MCP servers, their cached tools and whether each is signed in, for `/mcp` and the `@` picker.
///
/// Reads the servers this run may start, the persisted metadata cache (`.luxe/mcp-metadata.json`)
/// and — only when a server signs in with OAuth — the names in the token store. Nothing is
/// connected and nothing is written, since this runs on every snapshot.
pub(crate) fn collect_mcp_servers(root: &std::path::Path) -> Vec<luxe_core::McpServerStatus> {
use luxe_core::mcp_client::McpAuth;
// What this run would start, not every file on disk: a refused project server listed as
// configured is the "why doesn't it work" hunt all over again
let servers = super::tools::mcp_servers_for_run(root).0;
let signed_in = match servers.iter().any(|s| matches!(s.auth, Some(McpAuth::OAuth(_)))) {
true => luxe_mcp::token_store::TokenStore::default_path().signed_in_ids(),
false => Default::default(),
};
mcp_statuses(servers, &read_metadata_cache(root), &signed_in)
}
/// The metadata cache as JSON, or `Null` when there is none yet.
fn read_metadata_cache(root: &std::path::Path) -> serde_json::Value {
std::fs::read_to_string(root.join(".luxe").join("mcp-metadata.json"))
.ok()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or(serde_json::Value::Null)
}
/// One status row per server, from what is already on disk.
///
/// Args: `(servers, metadata cache, ids with a stored token)`.
fn mcp_statuses(
servers: Vec<luxe_core::mcp_client::McpServerConfig>,
cache: &serde_json::Value,
signed_in: &std::collections::HashSet<String>,
) -> Vec<luxe_core::McpServerStatus> {
use luxe_core::mcp_client::{McpAuth, McpTransport};
servers
.into_iter()
.map(|server| {
let cached = cache
.get(&server.id)
.and_then(|entry| entry.get("tools"))
.and_then(|tools| tools.as_array());
// `tool_count` keeps counting what the server lists; `tools` is what `mcp` will call,
// the same exclusions the registry applies
let tools = cached
.into_iter()
.flatten()
.filter_map(|tool| tool.get("name")?.as_str())
.filter(|name| !server.exclude_tools.iter().any(|excluded| excluded == name))
.map(str::to_owned)
.collect();
luxe_core::McpServerStatus {
transport: match server.transport {
McpTransport::Stdio { .. } => "stdio".into(),
McpTransport::HttpSse { .. } => "http".into(),
},
auth: match server.auth {
None => "none",
Some(McpAuth::Bearer { .. }) => "bearer",
Some(McpAuth::OAuth(_)) => "oauth",
}
.into(),
signed_in: matches!(server.auth, Some(McpAuth::OAuth(_)))
.then(|| signed_in.contains(&server.id)),
tool_count: cached.map(Vec::len),
tools,
enabled: server.enabled,
id: server.id,
}
})
.collect()
}
#[cfg(test)]
mod tests {
use luxe_core::mcp_client::{McpAuth, McpServerConfig, McpTransport, OAuthConfig};
fn server(id: &str, auth: Option<McpAuth>, exclude: &[&str]) -> McpServerConfig {
McpServerConfig {
id: id.into(),
transport: McpTransport::HttpSse { url: "https://example.com/mcp".into() },
auth,
exclude_tools: exclude.iter().map(|name| (*name).to_string()).collect(),
enabled: true,
..Default::default()
}
}
/// Through the real paths: the global config names the servers, the project's cache their
/// tools, and the token store — in the state directory, both redirected here — who is signed in.
#[test]
fn the_status_rows_come_from_the_config_the_cache_and_the_token_store() {
let (config, state, project) = (
tempfile::tempdir().unwrap(),
tempfile::tempdir().unwrap(),
tempfile::tempdir().unwrap(),
);
std::env::set_var("XDG_CONFIG_HOME", config.path());
std::env::set_var("XDG_STATE_HOME", state.path());
std::fs::create_dir_all(config.path().join("luxe")).unwrap();
std::fs::write(
config.path().join("luxe").join("mcp.json"),
r#"{ "mcpServers": {
"asana": { "url": "https://mcp.asana.com/v2/mcp", "auth": { "kind": "oauth" } },
"linear": { "url": "https://mcp.linear.app/mcp", "auth": { "kind": "oauth" } }
} }"#,
)
.unwrap();
std::fs::create_dir_all(state.path().join("luxe")).unwrap();
std::fs::write(
state.path().join("luxe").join("mcp-auth.json"),
r#"{ "asana": { "access_token": "t" } }"#,
)
.unwrap();
std::fs::create_dir_all(project.path().join(".luxe")).unwrap();
std::fs::write(
project.path().join(".luxe").join("mcp-metadata.json"),
r#"{ "asana": { "config_hash": 0, "tools": [{"name": "get_tasks"}] } }"#,
)
.unwrap();
let mut rows = super::collect_mcp_servers(project.path());
rows.sort_by(|a, b| a.id.cmp(&b.id));
let shape: Vec<_> =
rows.iter().map(|row| (row.id.as_str(), row.tools.clone(), row.signed_in)).collect();
assert_eq!(
shape,
vec![
("asana", vec!["get_tasks".to_string()], Some(true)),
("linear", Vec::new(), Some(false)),
]
);
std::env::remove_var("XDG_CONFIG_HOME");
std::env::remove_var("XDG_STATE_HOME");
}
/// A row carries what `mcp` will call — the cache less the exclusions — and says signed in only
/// for an OAuth server, from the ids with a token.
#[test]
fn a_status_row_carries_the_callable_tools_and_the_sign_in() {
let cache = serde_json::json!({
"asana": { "config_hash": 1, "tools": [{"name": "get_tasks"}, {"name": "delete_task"}, {"description": "nameless"}] },
"docs": { "config_hash": 2, "tools": [] },
});
let signed_in = ["asana".to_string()].into_iter().collect();
let oauth = || Some(McpAuth::OAuth(OAuthConfig::default()));
let rows = super::mcp_statuses(
vec![
server("asana", oauth(), &["delete_task"]),
server("linear", oauth(), &[]),
server("docs", None, &[]),
],
&cache,
&signed_in,
);
let shape: Vec<_> = rows
.iter()
.map(|row| (row.id.as_str(), row.tool_count, row.tools.clone(), row.signed_in))
.collect();
assert_eq!(
shape,
vec![
("asana", Some(3), vec!["get_tasks".to_string()], Some(true)),
("linear", None, Vec::new(), Some(false)),
("docs", Some(0), Vec::new(), None),
]
);
}
}

View File

@@ -0,0 +1,441 @@
//! Tool registry assembly — built-ins, the LSP discovery funnel, the DAP debugger, opt-in MCP,
//! the config deny-list, and optional lazy-tool tiering.
use std::sync::Arc;
use luxe_core::ToolRegistry;
use super::config::env_disabled;
use super::services::{build_graph_service, shared_dap_service, SharedLspService};
/// Where a deny-list entry came from — and so what the reader has to edit to change it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DenySource {
/// `--no-tool <name>` on this command line
Flag,
/// `tools.disabled` in a config file
Config,
}
impl DenySource {
/// How `/tools` names this source in the status list.
fn label(self) -> &'static str {
match self {
Self::Flag => "--no-tool",
Self::Config => "config",
}
}
/// How a notice quotes the instruction, so the reader can find it and fix it.
fn quoted(self, name: &str) -> String {
match self {
Self::Flag => format!("--no-tool {name}"),
Self::Config => format!("tools.disabled \"{name}\""),
}
}
}
/// What the deny-list actually did with one name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DeniedTool {
/// The name as written
name: String,
/// Where it was written
source: DenySource,
}
/// What the deny-list did, in the four outcomes worth telling apart.
///
/// A list of removals cannot explain an absence: `--no-tool websearch` and `--no-tool screenshot`
/// on a machine with no browser both removed nothing, and only one of them is a typo.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct ToolDenyReport {
/// Unregistered, with what asked for it — what `/tools` reports as `disabled`
removed: Vec<DeniedTool>,
/// Essential, so the request was refused
refused: Vec<DeniedTool>,
/// A tool Luxe knows, not registered on this machine
unavailable: Vec<DeniedTool>,
/// No tool of that name anywhere, with the nearest one when there is a near miss
unknown: Vec<(DeniedTool, Option<&'static str>)>,
}
impl ToolDenyReport {
/// The removals, in the shape [`collect_tool_statuses`] takes.
pub(super) fn removals(&self) -> Vec<(String, String)> {
self.removed
.iter()
.map(|denied| (denied.name.clone(), denied.source.label().to_string()))
.collect()
}
/// What to say at startup, or nothing when the deny-list did exactly what it was asked.
///
/// A removal is silent — it worked, and `/tools` lists it. The other three are the reader
/// believing something happened that did not.
pub(super) fn notices(&self) -> Vec<String> {
let mut notices = Vec::new();
for denied in &self.refused {
notices.push(format!(
"{}: refused — the agent cannot work without read, write, edit and bash.",
denied.source.quoted(&denied.name)
));
}
for (denied, nearest) in &self.unknown {
let suggestion = match nearest {
Some(nearest) => format!(" Did you mean {nearest}?"),
None => String::new(),
};
notices.push(format!(
"{}: no tool by that name, so nothing was disabled.{suggestion}",
denied.source.quoted(&denied.name)
));
}
for denied in &self.unavailable {
notices.push(format!(
"{}: nothing to disable — {} is not registered in this run.",
denied.source.quoted(&denied.name),
denied.name
));
}
notices
}
}
/// Register the built-in tool set plus the LSP tools, wiring both LSP tools to the shared warm
/// service so they reuse running servers instead of spawning one per call.
///
/// `todo` is rooted at `<repo>/.luxe/todos` so a session's checklist persists.
/// Unregisters every tool the layered config disables, with `--no-tool`/`--with-tool` layered over
/// it (essential tools are never removed). Runs after built-ins + MCP register so a user can trim
/// any optional tool, including `mcp`.
///
/// Returns a [`ToolDenyReport`] rather than a list of names: `/tools` has to explain an absence,
/// and the reader has to be told when an instruction of theirs did nothing.
pub(crate) fn apply_tool_deny_list(
registry: &mut ToolRegistry,
repo_root: &std::path::Path,
disable: &[String],
enable: &[String],
) -> ToolDenyReport {
let config = luxe_core::config::Config::load(repo_root).tools;
let from_flag = |name: &String| disable.iter().any(|flag| flag == name);
let mut report = ToolDenyReport::default();
for name in config.effective_disabled(disable, enable) {
let source = if from_flag(&name) { DenySource::Flag } else { DenySource::Config };
let denied = DeniedTool { name, source };
let name = denied.name.as_str();
if luxe_core::config::ESSENTIAL_TOOLS.contains(&name) {
// Refused rather than honored: an agent without these cannot do anything, so the
// request is a misunderstanding of what the knob is for. Say so instead of
// half-obeying.
tracing::warn!(
tool = %name,
source = source.label(),
"refusing to disable an essential tool (read/write/edit/bash)"
);
report.refused.push(denied);
} else if registry.unregister(name) {
tracing::info!(tool = %name, source = source.label(), "tool disabled");
report.removed.push(denied);
} else if is_known_tool(name) {
// `debug`, `screenshot` and `ast_grep` register only where their program is installed,
// and `mcp` only where a server is configured, so disabling one here is a no-op.
tracing::debug!(
tool = %name,
source = source.label(),
"nothing to disable: that tool is not registered on this machine"
);
report.unavailable.push(denied);
} else {
let nearest = nearest_tool(name);
tracing::warn!(
tool = %name,
source = source.label(),
nearest,
"nothing to disable: no tool by that name"
);
report.unknown.push((denied, nearest));
}
}
report
}
/// Every tool Luxe can register, whatever this machine happens to have installed.
///
/// The set that makes "no such tool" tellable from "not here": four tools register only where
/// their program exists (`debug`, `screenshot`, `ast_grep`) or where something is configured
/// (`mcp`), so a registry read on a bare CI box cannot answer the question a typo asks. The list
/// itself is [`luxe_core::tool_catalog`]; `the_catalog_covers_the_registry` keeps it honest.
fn is_known_tool(name: &str) -> bool {
luxe_core::tool_catalog::get(name).is_some()
}
/// The tool `name` was probably meant to be, or `None` when it is nothing like any of them.
///
/// Punctuation and case are ignored first, because that is what the near misses look like:
/// `websearch`, `web-search` and `webSearch` are all one keystroke's worth of `web_search`.
/// A shared prefix catches the rest, the way an unrecognized hook point already does.
fn nearest_tool(name: &str) -> Option<&'static str> {
let squash = |value: &str| {
value
.chars()
.filter(|c| c.is_alphanumeric())
.flat_map(char::to_lowercase)
.collect::<String>()
};
let wanted = squash(name);
if let Some(exact) = luxe_core::tool_catalog::names().find(|tool| squash(tool) == wanted) {
return Some(exact);
}
let shared = |candidate: &str| {
wanted.chars().zip(squash(candidate).chars()).take_while(|(a, b)| a == b).count()
};
luxe_core::tool_catalog::names()
.filter(|candidate| shared(candidate) >= 3)
.max_by_key(|candidate| shared(candidate))
}
/// What every tool is doing right now, for `/tools`.
///
/// Assembled after tiering so the three states are distinguishable from the outside: shipped in
/// every request, deferred behind `activate_tools`, or gone and by whose instruction.
pub(crate) fn collect_tool_statuses(
registry: &ToolRegistry,
removed: Vec<(String, String)>,
) -> Vec<luxe_core::ToolStatus> {
use luxe_core::{ToolAvailability, ToolStatus};
let core: std::collections::HashSet<&str> = registry.prompt_names().into_iter().collect();
let registered: std::collections::HashSet<String> =
registry.names().into_iter().map(str::to_string).collect();
let mut statuses: Vec<ToolStatus> = registry
.names()
.into_iter()
.map(|name| ToolStatus {
availability: if !registry.is_tiered() || core.contains(name) {
ToolAvailability::Active
} else {
ToolAvailability::Deferred
},
name: name.to_string(),
})
.collect();
// A name cannot be both present and removed, and letting one be would list it twice and count
// it in two totals. The registry is the authority; the removal list is a record of intent.
statuses.extend(removed.into_iter().filter(|(name, _)| !registered.contains(name)).map(
|(name, source)| ToolStatus { name, availability: ToolAvailability::Disabled { source } },
));
statuses.sort_by(|a, b| a.name.cmp(&b.name));
statuses
}
/// Build the callable tool set.
///
/// `loop_driven` is whether an autonomous loop is driving this engine. It gates `loop_control`,
/// which has nothing to control in an ordinary session — the same capability gate `ast_grep` and
/// `screenshot` use, since a tool that cannot work here should not be advertised here.
/// The checklist is state, kept with the project (`state_root`); the code graph indexes the files
/// the agent works on (`work_root`). They are one path unless the session has a worktree.
pub(super) fn build_tool_registry(
state_root: &std::path::Path,
work_root: &std::path::Path,
lsp_service: SharedLspService,
loop_driven: bool,
) -> ToolRegistry {
let mut registry = ToolRegistry::new();
let todo_root = state_root.join(".luxe").join("todos");
// The shared read tracker also gates the LSP funnel reads below, so
// `read_symbol`/`module_report` count toward the read-before-edit guard.
let web = luxe_tools::web::WebConfig {
clone_repositories: luxe_core::config::Config::load(state_root).tools.clone_repositories(),
..luxe_tools::web::WebConfig::from_env()
};
let read_tracker = luxe_tools::register_builtins(&mut registry, Some(todo_root), web);
if loop_driven {
registry.register(Arc::new(luxe_tools::loop_control::LoopControlTool::new()));
}
// Warm code graph shared by the impact tool and module_report's `blastRadius`.
let graph_service = build_graph_service(work_root);
registry.register(Arc::new(luxe_lsp::LspDiagnosticsTool::new(lsp_service.clone())));
registry.register(Arc::new(
luxe_lsp::LspNavigationTool::new(lsp_service.clone()).with_tracker(read_tracker.clone()),
));
// Discovery funnel (symbol_search → module_report → read_symbol), LSP-backed. The two that
// return file content share the read tracker so a subsequent edit isn't falsely blocked.
registry.register(Arc::new(
luxe_lsp::SymbolSearchTool::new(lsp_service.clone())
.with_graph(graph_service.clone())
.with_index(super::services::shared_symbol_index()),
));
registry.register(Arc::new(
luxe_lsp::ModuleReportTool::new(lsp_service.clone())
.with_tracker(read_tracker.clone())
.with_graph(graph_service.clone()),
));
registry.register(Arc::new(
luxe_lsp::ReadSymbolTool::new(lsp_service.clone()).with_tracker(read_tracker),
));
// "What does changing X affect?" over the offline structural graph, with optional LSP-verified
// callers (`verify: true`).
registry.register(Arc::new(luxe_lsp::ImpactTool::new(graph_service).with_lsp(lsp_service)));
// Native DAP debugger, backed by a warm per-workspace session service. Custom adapters from
// ~/.config/luxe/debug-adapters.json extend the built-in language coverage.
//
// Registered only where a debug adapter is actually installed: it carries the largest schema in
// the set (~780 tokens on every request), and with no adapter present every call it could make
// would answer "no debug adapter found". This hides no capability — there is none to hide.
let dap = shared_dap_service();
if dap.has_adapter() {
registry.register(Arc::new(luxe_dap::DebugTool::new(dap)));
} else {
tracing::debug!(
"debug tool not registered: no DAP adapter installed (codelldb, lldb-dap, gdb, \
debugpy, or dlv)"
);
}
registry
}
/// Register the single `mcp` proxy tool over the servers this run may start.
///
/// Instead of eagerly connecting every server and registering every tool (thousands of context
/// tokens, whether used or not), we register one ~200-token proxy backed by a lazy
/// [`luxe_mcp::ServerRegistry`]: servers connect on first call, tool metadata is cached to
/// `.luxe/mcp-metadata.json` so discovery works cold, and idle servers disconnect. MCP servers
/// stay untrusted — calls are permission-gated and results are surfaced as data, not instructions.
pub(crate) async fn register_mcp_tools(registry: &mut ToolRegistry, repo_root: &std::path::Path) {
use luxe_mcp::{McpProxyTool, ServerRegistry};
let (servers, refused) = mcp_servers_for_run(repo_root);
if !refused.is_empty() {
tracing::warn!(
servers = ?refused,
"mcp: not starting servers this project declares; --trust-project, or \
lsp.project_servers in the global config, allows them"
);
}
let unlisted: Vec<&str> = servers
.iter()
.map(|server| server.id.as_str())
.filter(|id| !luxe_core::mcp_client::is_plain_name(id))
.collect();
if !unlisted.is_empty() {
tracing::warn!(
servers = ?unlisted,
"mcp: not listing these servers in the @ picker; an id there is letters, digits, \
dots, dashes and underscores, at most 64"
);
}
let cache_path = repo_root.join(".luxe").join("mcp-metadata.json");
let manager = Arc::new(ServerRegistry::new(servers, Some(cache_path)));
if !manager.has_servers() {
return;
}
manager.start().await;
tracing::info!(servers = ?manager.server_ids(), "mcp: registered proxy tool (lazy)");
registry.register(Arc::new(McpProxyTool::new(manager)));
}
/// The MCP servers this run may start, and the ids of any the project declared that it may not.
///
/// A stdio server in `.mcp.json` is a command the repository chose, and an `eager` one must not
/// start the moment Luxe opens a cloned tree, headless included. It answers to the gate project
/// language servers and formatters already use, not a second one.
pub(crate) fn mcp_servers_for_run(
repo_root: &std::path::Path,
) -> (Vec<luxe_core::mcp_client::McpServerConfig>, Vec<String>) {
luxe_core::mcp_config::McpConfigStore::for_run(
repo_root,
super::services::project_tooling_allowed(),
)
}
/// Default core tool set: every tool with demonstrated use, kept in every request. The rest are
/// deferred and listed in the prompt as available on demand. Override with `LUXE_CORE_TOOLS`
/// (comma-separated).
///
/// The split is drawn from measurement, not taste. A tool earns core by being called; one that is
/// rarely called and heavy in schema (`debug`, `lsp_navigation`, `screenshot`, `ast_grep`,
/// `impact`, `module_report`, `read_symbol`, `symbol_search`) is deferred. The sweeps found the
/// model rarely or never reached for these, and deferring them did not change what it answered;
/// `read_symbol` and `symbol_search` joined only once an adapter that loads a tool in place could
/// activate one without rewriting the cached prefix (where one cannot, see
/// [`default_core_tools`]). Deferred rather than removed: some models do reach for them now and
/// then, and a catalog line costs a fraction of a schema. `test` stays because deferring it
/// changed which tools the model reached for, which is the one thing this must not do.
///
/// `question` earns its place despite being rare: the communication contract asks the model to put
/// decisions through it, and deferring it means an activation round-trip at exactly the moment the
/// user is already waiting to be asked something.
///
/// `skill` is the one entry that is not in this list and is sometimes core anyway — see
/// [`apply_lazy_tools`].
const DEFAULT_CORE_TOOLS: &[&str] =
&["read", "write", "edit", "bash", "grep", "glob", "todo", "git", "question", "test"];
/// Tier the registry: only the core set (plus the `activate_tools` meta-tool) ships in every
/// request, and the rest are deferred behind a one-line catalog in the prompt.
///
/// On by default — it cuts the per-request floor 29% (33,827 → 23,952 characters) and total turn
/// cost by about the same, with tool choice and task completion unchanged against the full set.
/// Set `LUXE_LAZY_TOOLS=0` to ship every schema every time.
pub(crate) fn apply_lazy_tools(registry: &mut ToolRegistry, repo_root: &std::path::Path) {
if env_disabled("LUXE_LAZY_TOOLS") {
return;
}
let core: std::collections::HashSet<String> = std::env::var("LUXE_CORE_TOOLS")
.ok()
.filter(|value| !value.trim().is_empty())
.map(|value| {
value.split(',').map(|t| t.trim().to_string()).filter(|t| !t.is_empty()).collect()
})
.unwrap_or_else(|| default_core_tools(repo_root, registry));
// Deferred = every currently-registered tool not in core (computed before adding the
// meta-tool).
let deferred: Vec<String> =
registry.names().iter().filter(|n| !core.contains(**n)).map(|s| s.to_string()).collect();
let count = deferred.len();
registry.register(Arc::new(luxe_tools::activate::ActivateToolsTool::new(deferred)));
registry.set_tiers(core);
tracing::info!(deferred = count, "lazy tools enabled");
}
/// [`DEFAULT_CORE_TOOLS`], plus `skill` for anyone who has skills and `mcp` for anyone with a
/// server this run may reach.
///
/// The two tools whose tier depends on the machine rather than on measurement, and it is the same
/// cache arithmetic that says so. A deferred tool costs an `activate_tools` round-trip on first
/// use, and on a provider that can't load it in place (chat completions) that round-trip *changes
/// the tool list* — which invalidates the cached prompt prefix and re-bills everything in front of
/// it. Meanwhile the skill index is already in the prompt of anyone who has skills installed, so
/// the tool that index points at is not optional for them.
///
/// Decided at wiring time, at the same moment the index enters the prompt, so the two cannot
/// disagree within a session. An explicit `LUXE_CORE_TOOLS` is explicit and overrides both.
///
/// `mcp` follows the same arithmetic. It is 203 tokens, about 20 a request once cached, while
/// activating it mid-session where it has to be listed rewrites the whole cached prompt — 34,500
/// tokens' worth for a session 30,000 in — so the schema has to be carried for some 1,700 requests
/// to cost what one activation does. "Registered" is the definite test: [`register_mcp_tools`] adds
/// the tool only when the trust gate leaves a server, and the deny list has already had its say, so
/// a `--no-tool mcp` run never sees it here. A server whose login has expired still counts;
/// dropping it would change the tool list mid-session, the break this exists to avoid.
fn default_core_tools(
repo_root: &std::path::Path,
registry: &ToolRegistry,
) -> std::collections::HashSet<String> {
let mut core: std::collections::HashSet<String> =
DEFAULT_CORE_TOOLS.iter().map(|name| (*name).to_string()).collect();
if !luxe_core::skills::discover(repo_root).is_empty() {
core.insert("skill".to_string());
}
if registry.names().contains(&"mcp") {
core.insert("mcp".to_string());
}
core
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,456 @@
use super::{is_known_tool, DeniedTool, DenySource, ToolDenyReport, DEFAULT_CORE_TOOLS};
use luxe_core::ToolAvailability;
/// The catalog is the only thing that can tell a typo from a tool this machine cannot run, and
/// the list every settings surface offers, so it has to cover what the registry actually
/// produces — including the four that register conditionally and are therefore absent from a
/// CI box's registry.
#[test]
fn the_catalog_covers_the_registry() {
let lsp = super::super::services::build_lsp_service();
let mut registry =
super::build_tool_registry(std::path::Path::new("."), std::path::Path::new("."), lsp, true);
super::apply_lazy_tools(&mut registry, std::path::Path::new("."));
for name in registry.names() {
assert!(is_known_tool(name), "{name} is registered but not in the tool catalog");
}
for conditional in ["debug", "screenshot", "ast_grep", "mcp"] {
assert!(
is_known_tool(conditional),
"{conditional} registers only sometimes, which is exactly why it must be listed"
);
}
}
/// The near miss this exists for: `--no-tool websearch` disabled nothing and said nothing.
#[test]
fn a_near_miss_is_pointed_at_the_tool_it_meant() {
assert_eq!(super::nearest_tool("websearch"), Some("web_search"));
assert_eq!(super::nearest_tool("web-search"), Some("web_search"));
assert_eq!(super::nearest_tool("webSearch"), Some("web_search"));
assert_eq!(super::nearest_tool("lsp_diagnostic"), Some("lsp_diagnostics"));
assert_eq!(super::nearest_tool("xyzzy"), None, "a guess at nothing helps nobody");
}
/// The four outcomes, each with the line a reader gets — and a removal, which is silent
/// because it worked and `/tools` lists it.
#[test]
fn the_deny_report_tells_the_four_outcomes_apart() {
let denied = |name: &str, source| DeniedTool { name: name.to_string(), source };
let report = ToolDenyReport {
removed: vec![denied("web_fetch", DenySource::Flag)],
refused: vec![denied("bash", DenySource::Flag)],
unavailable: vec![denied("screenshot", DenySource::Config)],
unknown: vec![
(denied("websearch", DenySource::Flag), Some("web_search")),
(denied("xyzzy", DenySource::Config), None),
],
};
assert_eq!(
report.removals(),
vec![("web_fetch".to_string(), "--no-tool".to_string())],
"what /tools renders is unchanged"
);
let notices = report.notices();
assert_eq!(notices.len(), 4, "a removal that worked is not news: {notices:?}");
assert!(notices[0].starts_with("--no-tool bash: refused"), "{}", notices[0]);
assert!(notices[1].contains("Did you mean web_search?"), "{}", notices[1]);
assert!(
notices[2].starts_with("tools.disabled \"xyzzy\":") && !notices[2].contains("mean"),
"a config typo names the config key, and invents no suggestion: {}",
notices[2]
);
assert!(
notices[3].contains("not registered in this run"),
"a tool that is known but absent is not a typo: {}",
notices[3]
);
}
/// The switch reaches the tool the model is offered, not just the config: with cloning off,
/// `web_fetch`'s description stops promising a path it will not produce.
#[test]
fn turning_cloning_off_in_config_reaches_web_fetch() {
let project = tempfile::tempdir().expect("temp project");
std::fs::create_dir_all(project.path().join(".luxe")).unwrap();
std::fs::write(
project.path().join(".luxe").join("config.json"),
r#"{ "tools": { "clone_repositories": false } }"#,
)
.unwrap();
let lsp = super::super::services::build_lsp_service();
let registry = super::build_tool_registry(project.path(), project.path(), lsp, false);
let description = registry.get("web_fetch").expect("web_fetch").schema().description;
assert!(!description.contains("gh-cache"), "{description}");
}
/// And the whole path: a run that disables an essential tool, a real one, a conditional one
/// and a typo gets one report that separates them.
#[test]
fn the_deny_list_classifies_what_a_real_run_asks_for() {
let lsp = super::super::services::build_lsp_service();
let mut registry = super::build_tool_registry(
std::path::Path::new("."),
std::path::Path::new("."),
lsp,
false,
);
let project = tempfile::tempdir().expect("temp project");
let disable: Vec<String> =
["bash", "web_fetch", "mcp", "websearch"].iter().map(|s| s.to_string()).collect();
let report = super::apply_tool_deny_list(&mut registry, project.path(), &disable, &[]);
assert_eq!(report.refused.iter().map(|d| d.name.as_str()).collect::<Vec<_>>(), ["bash"]);
assert_eq!(report.removed.iter().map(|d| d.name.as_str()).collect::<Vec<_>>(), ["web_fetch"]);
assert_eq!(
report.unavailable.iter().map(|d| d.name.as_str()).collect::<Vec<_>>(),
["mcp"],
"a tool Luxe knows that this run never registered is not a typo"
);
assert_eq!(report.unknown.len(), 1);
assert_eq!(report.unknown[0].0.name, "websearch");
assert_eq!(report.unknown[0].1, Some("web_search"));
assert!(registry.names().contains(&"bash"), "and bash is still there");
}
/// The status list is what `/tools` renders, so it has to be built from the *tiered* registry.
/// Reading it earlier would report every tool as active and hide the distinction the view
/// exists to draw.
#[test]
fn tool_statuses_separate_core_from_deferred_and_carry_the_disabled() {
let lsp = super::super::services::build_lsp_service();
let mut registry = super::build_tool_registry(
std::path::Path::new("."),
std::path::Path::new("."),
lsp,
false,
);
// As production does it: the tool is really gone before its absence is described.
assert!(registry.unregister("web_search"), "web_search is a built-in");
super::apply_lazy_tools(&mut registry, std::path::Path::new("."));
let statuses = super::collect_tool_statuses(
&registry,
vec![("web_search".to_string(), "--no-tool".to_string())],
);
assert_eq!(
statuses.iter().filter(|s| s.name == "web_search").count(),
1,
"a tool appears once, whatever state it is in"
);
let state =
|name: &str| statuses.iter().find(|s| s.name == name).map(|s| s.availability.clone());
assert_eq!(state("read"), Some(ToolAvailability::Active), "a core tool ships every time");
assert_eq!(
state("lsp_navigation"),
Some(ToolAvailability::Deferred),
"an expensive, rarely-used tool is deferred rather than absent"
);
assert_eq!(
state("web_search"),
Some(ToolAvailability::Disabled { source: "--no-tool".to_string() }),
"an unregistered tool is still reported, with what removed it"
);
assert!(
statuses.windows(2).all(|pair| pair[0].name <= pair[1].name),
"sorted, so the view does not reorder between snapshots"
);
}
/// Untiered (`LUXE_LAZY_TOOLS=0`) there is no deferred tier, so nothing may be reported as
/// deferred — it would send the reader to `activate_tools` for a tool that is already loaded.
#[test]
fn nothing_is_deferred_when_tiering_is_off() {
let lsp = super::super::services::build_lsp_service();
let registry = super::build_tool_registry(
std::path::Path::new("."),
std::path::Path::new("."),
lsp,
false,
);
let statuses = super::collect_tool_statuses(&registry, Vec::new());
assert!(!statuses.is_empty());
assert!(statuses.iter().all(|s| s.availability == ToolAvailability::Active));
}
/// The split is an evidence claim, so it gets a test. Deferring these four changed nothing
/// about which tools the model reached for; deferring `test` did. The symbol tools were kept
/// for a while on gpt-6.1-sol's use, then measured as earning nothing by being in the request.
#[test]
fn the_expensive_unused_tools_are_deferred_and_the_used_ones_are_not() {
for deferred in ["debug", "lsp_navigation", "screenshot", "ast_grep"] {
assert!(
!DEFAULT_CORE_TOOLS.contains(&deferred),
"{deferred} is 31% of the tool block between them and fired once in 58 runs"
);
}
for core in ["read", "write", "edit", "bash", "grep", "test"] {
assert!(DEFAULT_CORE_TOOLS.contains(&core), "{core} has demonstrated use");
}
for deferred in ["impact", "module_report"] {
assert!(!DEFAULT_CORE_TOOLS.contains(&deferred), "{deferred}: no call in 248 runs");
}
for deferred in ["symbol_search", "read_symbol"] {
assert!(
!DEFAULT_CORE_TOOLS.contains(&deferred),
"{deferred}: every arm of the sweep was as right without it"
);
}
}
/// Deferring `question` would cost an activation round-trip at the exact moment the user is
/// already waiting to be asked something.
#[test]
fn question_stays_core_for_the_users_sake() {
assert!(DEFAULT_CORE_TOOLS.contains(&"question"));
}
/// `skill` is core exactly where there are skills, and deferred where there are none.
///
/// The break this catches is invisible from inside a session and costs real money: a deferred
/// tool's first use goes through `activate_tools`, which on a provider that has to list it
/// *changes the tool list*, which invalidates the cached prompt prefix and re-bills everything
/// in front of it — measured on the wire as `#4 → #5: tools CHANGED`. The skill index is already in the prompt of anyone
/// who has skills, so the tool it points at is not optional for them; for everyone else the
/// schema is dead weight and stays deferred.
///
/// Both halves are asserted against the same fixture, because the interesting failure is
/// promoting it unconditionally — which no test of the skills case alone can see.
#[test]
fn skill_is_core_when_there_are_skills_and_deferred_when_there_are_not() {
// The real global skills directories would otherwise decide this test's answer on a machine
// that has skills installed — including this developer's. Home as well as config, since
// `~/.agents/skills` hangs off home, and Windows reads `USERPROFILE` for that.
let home = tempfile::tempdir().expect("temp home");
std::env::set_var("XDG_CONFIG_HOME", home.path());
std::env::set_var("HOME", home.path());
std::env::set_var("USERPROFILE", home.path());
let project = tempfile::tempdir().expect("temp project");
let tier_of_skill = |root: &std::path::Path| {
let lsp = super::super::services::build_lsp_service();
let mut registry = super::build_tool_registry(root, root, lsp, false);
super::apply_lazy_tools(&mut registry, root);
let statuses = super::collect_tool_statuses(&registry, Vec::new());
statuses
.into_iter()
.find(|status| status.name == "skill")
.map(|status| status.availability)
.expect("skill is a built-in")
};
assert_eq!(
tier_of_skill(project.path()),
ToolAvailability::Deferred,
"with no skills the schema is dead weight"
);
let skill = project.path().join(".luxe").join("skills").join("canary");
std::fs::create_dir_all(&skill).expect("skill dir");
std::fs::write(
skill.join("SKILL.md"),
"---\nname: canary\ndescription: a skill that exists\n---\n\nBody.\n",
)
.expect("SKILL.md");
assert_eq!(
tier_of_skill(project.path()),
ToolAvailability::Active,
"the index is in the prompt, so the tool it points at ships with it"
);
// An explicit list is explicit, and outranks both answers.
std::env::set_var("LUXE_CORE_TOOLS", "read,write");
assert_eq!(tier_of_skill(project.path()), ToolAvailability::Deferred);
std::env::remove_var("LUXE_CORE_TOOLS");
std::env::remove_var("XDG_CONFIG_HOME");
}
/// `mcp` ships in every request when this run has a server, and not at all when it has none —
/// through the real sequence, registration and then tiering, since tiering first would defer it
/// again without a word.
#[tokio::test]
async fn mcp_is_core_when_a_server_is_registered_and_absent_when_none_is() {
let home = tempfile::tempdir().expect("temp home");
std::env::set_var("XDG_CONFIG_HOME", home.path());
let project = tempfile::tempdir().expect("temp project");
let tier_of_mcp = |root: std::path::PathBuf| async move {
let lsp = super::super::services::build_lsp_service();
let mut registry = super::build_tool_registry(&root, &root, lsp, false);
super::register_mcp_tools(&mut registry, &root).await;
super::apply_lazy_tools(&mut registry, &root);
let statuses = super::collect_tool_statuses(&registry, Vec::new());
let catalog: Vec<String> =
registry.deferred_catalog().into_iter().map(|(name, _)| name).collect();
let tier = statuses.into_iter().find(|s| s.name == "mcp").map(|status| status.availability);
(tier, catalog.contains(&"mcp".to_string()))
};
assert_eq!(
tier_of_mcp(project.path().to_path_buf()).await,
(None, false),
"no server: no tool, and no catalog line either"
);
// A global server, lazy, so nothing is started to answer this
let config = home.path().join("luxe");
std::fs::create_dir_all(&config).expect("config dir");
std::fs::write(
config.join("mcp.json"),
r#"{ "mcpServers": { "canary": { "command": "true", "lifecycle": "lazy" } } }"#,
)
.expect("mcp.json");
assert_eq!(
tier_of_mcp(project.path().to_path_buf()).await,
(Some(ToolAvailability::Active), false),
"a server this run may reach puts the gateway in every request"
);
std::env::set_var("LUXE_CORE_TOOLS", "read,write");
assert_eq!(
tier_of_mcp(project.path().to_path_buf()).await.0,
Some(ToolAvailability::Deferred),
"an explicit list still outranks it"
);
std::env::remove_var("LUXE_CORE_TOOLS");
std::env::remove_var("XDG_CONFIG_HOME");
}
/// One word for a file across the whole surface.
///
/// The registry is the only place that sees every schema at once, which is exactly why the
/// surface drifted: `read`/`write`/`edit` said `path` while the discovery funnel said `file`,
/// so the funnel's own next step was where a model arrived holding the other word. The tools
/// still *accept* the old spelling; what must not come back is a second one being advertised.
/// The whole surface, with the capability-gated tools forced in.
///
/// `screenshot`, `ast_grep` and `debug` register only where their program is installed, so a
/// sweep over the plain registry silently stops covering them on a machine without chromium
/// — which is most CI runners, and one of those three is exactly where a stale argument name
/// last hid.
fn every_schema() -> Vec<luxe_core::provider::ToolSchema> {
use luxe_core::Tool;
let lsp = super::super::services::build_lsp_service();
let registry =
super::build_tool_registry(std::path::Path::new("."), std::path::Path::new("."), lsp, true);
let mut schemas = registry.schemas();
for gated in ["screenshot", "ast_grep"] {
if !schemas.iter().any(|s| s.name == gated) {
schemas.push(match gated {
"screenshot" => luxe_tools::screenshot::ScreenshotTool::new().schema(),
_ => luxe_tools::astgrep::AstGrepTool::new().schema(),
});
}
}
if !schemas.iter().any(|s| s.name == "debug") {
schemas
.push(luxe_dap::DebugTool::new(super::super::services::shared_dap_service()).schema());
}
schemas
}
/// Every property name in the surface, `tool.a.b` style, including nested `items` schemas.
fn advertised_names(schema: &luxe_core::provider::ToolSchema) -> Vec<String> {
fn walk(node: &serde_json::Value, trail: &str, out: &mut Vec<String>) {
if let Some(properties) = node.get("properties").and_then(|p| p.as_object()) {
for (name, child) in properties {
let path = if trail.is_empty() { name.clone() } else { format!("{trail}.{name}") };
out.push(path.clone());
walk(child, &path, out);
}
}
if let Some(items) = node.get("items") {
walk(items, trail, out);
}
}
let mut out = Vec::new();
walk(&schema.parameters, "", &mut out);
out
}
/// No advertised argument carries an underscore, at any depth.
///
/// Grounded in measurement rather than taste: `edit`'s `old_text`/`new_text` corrupted two in
/// five calls, because the model emitted the separator after a key ending in `_text` as `">`
/// and the provider's JSON repair then stringified the whole array. Only that suffix is known to
/// be dangerous, but the underscore buys nothing anywhere — a name is a name — and one convention
/// across the surface keeps the next `wait_ms` from being written without a second thought.
/// Retired spellings stay *accepted* via `luxe_core::tool::arg`; what this refuses is
/// advertising one.
#[test]
fn no_tool_advertises_an_argument_with_an_underscore_in_its_name() {
let schemas = every_schema();
assert!(schemas.len() > 15, "the sweep found almost no tools: {}", schemas.len());
let mut offenders = Vec::new();
for schema in &schemas {
for name in advertised_names(schema) {
let leaf = name.rsplit('.').next().unwrap_or(&name);
if leaf.contains('_') {
offenders.push(format!("{}.{name}", schema.name));
}
}
}
assert!(
offenders.is_empty(),
"advertise these camelCase and accept the old spelling via `luxe_core::tool::arg`: \
{offenders:?}"
);
}
/// The same concept spelled two ways is the drift this convention exists to stop.
///
/// `screenshot` took `wait_ms` while `lsp_diagnostics` took `waitMs` — the same argument, the
/// same units, two names, and nothing that would ever have failed.
#[test]
fn a_shared_argument_is_spelled_the_same_way_by_every_tool_that_takes_it() {
let mut spellings: std::collections::BTreeMap<String, Vec<String>> = Default::default();
for schema in every_schema() {
for name in advertised_names(&schema) {
let leaf = name.rsplit('.').next().unwrap_or(&name).to_string();
spellings
.entry(leaf.to_lowercase().replace('_', ""))
.or_default()
.push(format!("{}.{leaf}", schema.name));
}
}
for (canonical, uses) in spellings {
let distinct: std::collections::BTreeSet<&str> =
uses.iter().filter_map(|use_| use_.split('.').nth(1)).collect();
assert!(distinct.len() <= 1, "`{canonical}` is advertised under {distinct:?} by {uses:?}");
}
}
#[test]
fn every_tool_advertises_one_file_path_under_the_same_name() {
let lsp = super::super::services::build_lsp_service();
let registry = super::build_tool_registry(
std::path::Path::new("."),
std::path::Path::new("."),
lsp,
false,
);
// `target` is deliberately not a path: it takes a symbol name, a qualified name, or a file.
const NOT_A_PATH_ARGUMENT: [&str; 1] = ["impact"];
for schema in registry.schemas() {
if NOT_A_PATH_ARGUMENT.contains(&schema.name.as_str()) {
continue;
}
let Some(properties) = schema.parameters.get("properties").and_then(|p| p.as_object())
else {
continue;
};
for spelling in ["file", "file_path", "filePath"] {
assert!(
!properties.contains_key(spelling),
"{} advertises `{spelling}`; a single file path is spelled `path`",
schema.name
);
}
}
}