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 @@
//! Anthropic Messages API adapter.
//!
//! Implements the `Provider` trait for Anthropic's API, supporting:
//! - Streaming text, thinking blocks, and tool calls
//! - Extended thinking with signature round-trip
//! - Prompt caching with cache_control markers
//! - Fine-grained tool input streaming
use futures::stream::BoxStream;
use luxe_core::message::Message;
use luxe_core::provider::{
CompletionRequest, ModelInfo, Provider, ProviderError, ProviderEvent, StopReason,
ThinkingLevel, Usage,
};
use reqwest::Client;
use serde::Deserialize;
use crate::learned::Learned;
/// Anthropic API base URL.
const ANTHROPIC_API_BASE: &str = "https://api.anthropic.com/v1";
/// Anthropic provider adapter.
pub struct AnthropicProvider {
client: Client,
/// Where this call's auth comes from, resolved per request.
auth: std::sync::Arc<dyn crate::auth::AuthSource>,
model_info: ModelInfo,
compat: AnthropicCompat,
/// API base (defaults to [`ANTHROPIC_API_BASE`]; overridable for proxies).
base_url: String,
/// Thinking encodings learned from a rejection, keyed by model id.
///
/// A 400 teaches us which mode a model really accepts; remembering it keeps the correction to
/// one wasted round trip per model per session instead of one per turn.
learned_thinking: Learned<ThinkingPlan>,
/// Output caps learned from a rejection, keyed by model id.
///
/// A model no catalog knows goes out with the current generation's ceiling; an older one that
/// refuses it names its real limit, and remembering that keeps the retry to once per session.
learned_max_tokens: Learned<u32>,
/// Models whose endpoint refused in-place tool loading, so their deferred tools go back to the
/// list for the rest of the session.
listed_tools: Learned<()>,
}
impl AnthropicProvider {
/// Build an adapter from an API key, optional base URL, model info, and compat flags.
pub fn new(
api_key: crate::config::ApiKey,
base_url: Option<String>,
model_info: ModelInfo,
compat: AnthropicCompat,
) -> Self {
Self {
client: crate::http::shared_client(),
auth: crate::auth::StaticAuth::anthropic(Some(api_key)).into_arc(),
model_info,
compat,
base_url: base_url.unwrap_or_else(|| ANTHROPIC_API_BASE.to_string()),
learned_thinking: Learned::default(),
learned_max_tokens: Learned::default(),
listed_tools: Learned::default(),
}
}
/// Resolve auth from a credential store instead of the fixed key.
pub fn with_auth(mut self, auth: std::sync::Arc<dyn crate::auth::AuthSource>) -> Self {
self.auth = auth;
self
}
/// POST one Messages request, encoding thinking per `plan` and deferred tools per `loading`.
async fn post_messages(
&self,
req: &CompletionRequest,
model_info: &ModelInfo,
compat: &AnthropicCompat,
plan: ThinkingPlan,
loading: ToolLoading,
) -> Result<reqwest::Response, ProviderError> {
// Streaming is requested via `stream: true` in the body — Anthropic has a single
// `POST /v1/messages` endpoint, there is no `/messages/stream`.
let mut body = build_anthropic_request(req, model_info, compat, plan, loading);
body["stream"] = serde_json::Value::Bool(true);
// Anthropic authenticates with the `x-api-key` header (not `Authorization: Bearer`); the
// auth source supplies it. `anthropic-version` is protocol, not auth, so it stays here.
let auth = self.auth.request_auth().await?;
let base = auth.base_url.clone().unwrap_or_else(|| self.base_url.clone());
let url = format!("{}/messages", base.trim_end_matches('/'));
let mut headers: Vec<(&str, &str)> =
vec![("anthropic-version", "2023-06-01"), ("Content-Type", "application/json")];
if compat.copilot_headers {
headers.extend(crate::copilot::turn_headers(req));
}
let request = crate::http::json_request(self.client.post(&url), &headers, &body);
crate::wire::record_request(self.name(), &url, &headers, &body);
crate::http::send(auth.apply(request)).await
}
/// The flags this model's requests are shaped by: its own when it resolved any, else the
/// provider's.
///
/// Owned rather than borrowed because the projection is two fields and the decoder wants a copy
/// of its own — borrowing would put a lifetime on the adapter for the sake of a bool.
fn compat_for(&self, model_info: &ModelInfo) -> AnthropicCompat {
model_info.compat.as_ref().map_or_else(|| self.compat.clone(), AnthropicCompat::from)
}
/// The thinking encoding to open with: whatever a rejection already taught us about this
/// model, else what its declared controls imply.
fn thinking_plan(&self, model_info: &ModelInfo, compat: &AnthropicCompat) -> ThinkingPlan {
self.learned_thinking
.get(&model_info.r#ref.id)
.unwrap_or_else(|| ThinkingPlan::for_model(model_info, compat))
}
fn remember_thinking_plan(&self, model_info: &ModelInfo, plan: ThinkingPlan) {
self.learned_thinking.remember(&model_info.r#ref.id, plan);
}
/// The output cap a rejection already taught us for this model, if any.
fn learned_max_tokens(&self, model_info: &ModelInfo) -> Option<u32> {
self.learned_max_tokens.get(&model_info.r#ref.id)
}
fn remember_max_tokens(&self, model_info: &ModelInfo, limit: u32) {
self.learned_max_tokens.remember(&model_info.r#ref.id, limit);
}
/// How this model's deferred tools load: in place unless the flags or a refusal said not to.
fn tool_loading(&self, model_info: &ModelInfo, compat: &AnthropicCompat) -> ToolLoading {
let refused = self.listed_tools.knows(&model_info.r#ref.id);
if compat.defer_tool_loading && !refused {
ToolLoading::InPlace
} else {
ToolLoading::Listed
}
}
fn remember_listed_tools(&self, model_info: &ModelInfo) {
self.listed_tools.remember(&model_info.r#ref.id, ());
}
}
/// The output cap Anthropic names when it refuses `max_tokens`, or `None` when the 400 is about
/// something else.
///
/// The wording has held since 2024: `max_tokens: 128000 > 64000, which is the maximum allowed
/// number of output tokens for claude-opus-4-5-20251101`.
fn max_tokens_limit(body: &str) -> Option<u32> {
if !body.contains("maximum allowed number of output tokens") {
return None;
}
let (_, rest) = body.split_once("max_tokens: ")?;
let (_, rest) = rest.split_once(" > ")?;
let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
digits.parse().ok().filter(|limit| *limit > 0)
}
/// Anthropic-specific compatibility flags.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnthropicCompat {
/// Force adaptive thinking mode (default false).
pub force_adaptive_thinking: bool,
/// Use cache_control markers (default true).
pub cache_control: bool,
/// Keep cache entries for an hour rather than the default five minutes.
pub long_cache_retention: bool,
/// Ask for a tool call's arguments as the model writes them rather than in one lump at the end.
pub stream_tool_arguments: bool,
/// Send GitHub Copilot's per-request headers, for Claude reached through Copilot.
pub copilot_headers: bool,
/// Load deferred tools with `defer_loading` and `tool_reference` (default true).
pub defer_tool_loading: bool,
}
impl Default for AnthropicCompat {
fn default() -> Self {
Self {
force_adaptive_thinking: false,
cache_control: true,
long_cache_retention: false,
stream_tool_arguments: true,
copilot_headers: false,
defer_tool_loading: true,
}
}
}
impl From<&luxe_core::provider::CompatFlags> for AnthropicCompat {
/// The flags this API has an opinion about, projected out of the shared set.
///
/// `cache_control_format` doubles as the on switch: naming a format is how caching is asked
/// for, and `null` is how it is refused.
fn from(flags: &luxe_core::provider::CompatFlags) -> Self {
Self {
force_adaptive_thinking: flags.force_adaptive_thinking,
cache_control: flags.cache_control_format.is_some(),
long_cache_retention: flags.supports_long_cache_retention,
stream_tool_arguments: flags.stream_tool_arguments,
copilot_headers: flags.copilot_headers,
defer_tool_loading: flags.defer_tool_loading,
}
}
}
#[async_trait::async_trait]
impl Provider for AnthropicProvider {
fn name(&self) -> &str {
"anthropic"
}
async fn stream(
&self,
mut req: CompletionRequest,
cancel: tokio::sync::watch::Receiver<bool>,
) -> Result<BoxStream<'static, ProviderEvent>, ProviderError> {
// Honor the *per-request* model so a runtime model switch (`Action::SetModel`) actually
// changes the id/thinking sent to Anthropic. Fall back to the adapter's build-time model
// only when the request carries the placeholder default (`unknown`).
let model_info =
if req.model.r#ref.id == "unknown" { &self.model_info } else { &req.model };
// Per request for the same reason: one adapter serves every Claude generation, and how
// thinking is asked for differs between them.
let compat = self.compat_for(model_info);
let mut plan = self.thinking_plan(model_info, &compat);
let mut loading = self.tool_loading(model_info, &compat);
if let Some(limit) = self.learned_max_tokens(model_info) {
req.max_tokens = req.max_tokens.map(|max| max.min(limit));
}
let mut response = self.post_messages(&req, model_info, &compat, plan, loading).await?;
// Three 400s are recoverable rather than fatal, each at most once: an output cap the model
// can't honor, which Anthropic answers with the real limit; a thinking encoding from the
// wrong generation, which a model our catalog hasn't caught up with resolves to; and an
// endpoint that doesn't know in-place tool loading. Fix the request, retry, and remember
// what worked.
let (mut cap_revised, mut plan_revised) = (false, false);
while response.status() == reqwest::StatusCode::BAD_REQUEST {
let rejection = response.text().await.unwrap_or_default();
if let Some(limit) = max_tokens_limit(&rejection).filter(|_| !cap_revised) {
tracing::warn!(
model = %model_info.r#ref.id,
requested = ?req.max_tokens,
limit,
"anthropic refused the output cap; retrying at the model's limit"
);
req.max_tokens = req.max_tokens.map(|max| max.min(limit));
self.remember_max_tokens(model_info, limit);
cap_revised = true;
} else if let Some(revised) = plan.revised(&rejection).filter(|_| !plan_revised) {
tracing::warn!(
model = %model_info.r#ref.id,
?plan,
?revised,
"anthropic rejected the thinking configuration; retrying with the other encoding"
);
plan = revised;
plan_revised = true;
} else if loading == ToolLoading::InPlace && refuses_in_place_loading(&rejection) {
tracing::warn!(
model = %model_info.r#ref.id,
%rejection,
"the endpoint refused in-place tool loading; listing deferred tools instead"
);
loading = ToolLoading::Listed;
self.remember_listed_tools(model_info);
} else {
return Err(crate::http::status_error(reqwest::StatusCode::BAD_REQUEST, rejection));
}
response = self.post_messages(&req, model_info, &compat, plan, loading).await?;
if response.status().is_success() && plan_revised {
self.remember_thinking_plan(model_info, plan);
}
}
if !response.status().is_success() {
let status = response.status();
let text = response.text().await.unwrap_or_default();
return Err(crate::http::status_error(status, text));
}
// Decode the SSE body as it arrives: reasoning and text have to reach the UI while the
// model is still producing them, and a cancel has to be able to drop the connection.
Ok(crate::sse::decode(response.bytes_stream(), cancel, AnthropicDecoder::default()))
}
/// Five minutes, or an hour on the long tier — unless the request would cache differently when
/// replayed with a one-token cap.
///
/// That is budget-based thinking: the budget is derived from `max_tokens`, Anthropic keys the
/// message cache on it, and a replayed request would also be allowed to think for thousands of
/// tokens. Adaptive thinking, and thinking switched off, replay byte-for-byte apart from the cap.
fn prompt_cache_ttl(&self, req: &CompletionRequest) -> Option<std::time::Duration> {
let model_info =
if req.model.r#ref.id == "unknown" { &self.model_info } else { &req.model };
let compat = self.compat_for(model_info);
if !compat.cache_control || !req.reuse.worth_caching() {
return None;
}
let budgeted = self.thinking_plan(model_info, &compat).mode == ThinkingMode::Extended
&& thinking_is_on(model_info, req.thinking, &compat);
if budgeted {
return None;
}
let minutes = if compat.long_cache_retention { 60 } else { 5 };
Some(std::time::Duration::from_secs(minutes * 60))
}
/// Replays `req` through [`Provider::stream`] at one output token and reads the usage off the
/// end of it, so the body is the one the turn sent — same breakpoints, same learned thinking
/// encoding — and only `max_tokens` differs, which is not part of the cache key.
///
/// One token rather than the documented `max_tokens: 0`, which Anthropic refuses on a streamed
/// request and on any request with budget-based thinking.
async fn warm_cache(&self, mut req: CompletionRequest) -> Result<Usage, ProviderError> {
use futures::StreamExt;
req.max_tokens = Some(1);
// Nobody cancels a refresh by flag; the warmer drops this future instead
let (_never, cancel) = tokio::sync::watch::channel(false);
let mut events = self.stream(req, cancel).await?;
let mut usage = None;
while let Some(event) = events.next().await {
match event {
ProviderEvent::Usage(measured) => usage = Some(measured),
ProviderEvent::Error { message, .. } => return Err(ProviderError::Other(message)),
ProviderEvent::Done { .. } => break,
_ => {}
}
}
usage.ok_or_else(|| ProviderError::Other("the refresh reported no usage".to_string()))
}
}
mod request;
mod sse;
use request::*;
use sse::*;
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,306 @@
//! Anthropic Messages request building — core messages → Anthropic wire JSON.
use super::*;
use std::collections::HashSet;
mod cache;
mod messages;
pub(crate) use cache::add_cache_control_markers;
use cache::cache_marker;
pub(crate) use messages::{find_system_message, serialize_messages_loading};
#[cfg(test)]
pub(crate) use messages::{serialize_content_blocks, serialize_messages};
/// How a request expresses a non-off thinking level on the wire.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ThinkingMode {
/// `thinking: {type: "adaptive"}` + `output_config.effort` — Claude 4.7 and later.
Adaptive,
/// `thinking: {type: "enabled", budget_tokens: N}` — Claude 4.5 and earlier.
Extended,
}
/// The thinking encoding one request uses: how a level is expressed, and whether thinking may be
/// switched off at all.
///
/// Derived from the model's declared controls, and revised when Anthropic rejects it (see
/// [`ThinkingPlan::revised`]) so a model the catalog doesn't know yet still lands on a working
/// request after one retry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ThinkingPlan {
/// Encoding for a level above `off`
pub(crate) mode: ThinkingMode,
/// Whether `thinking: {type: "disabled"}` is accepted; the newest models are always-on
pub(crate) can_disable: bool,
/// Whether "off" is `thinking: {type: "between_tools"}`: the newest models think unless told
/// not to, refuse `disabled`, and name this as the way to stop
pub(crate) between_tools: bool,
}
impl ThinkingPlan {
/// The encoding a model's declared reasoning controls call for.
///
/// Effort-only models (the adaptive-only generation) reject extended thinking outright;
/// anything that still advertises a token budget keeps it, because that's the only mode the
/// older models accept and the catalog can't tell an extended-only model that happens to
/// support effort from one that also took adaptive.
pub(crate) fn for_model(model: &ModelInfo, compat: &AnthropicCompat) -> Self {
let adaptive = compat.force_adaptive_thinking || model.thinking_controls.effort_only();
let mode = if adaptive { ThinkingMode::Adaptive } else { ThinkingMode::Extended };
Self { mode, can_disable: true, between_tools: false }
}
/// The plan to retry with when `body` is Anthropic rejecting this one, or `None` when the 400
/// is about something else and there is nothing to learn.
pub(crate) fn revised(self, body: &str) -> Option<Self> {
// "To turn thinking off on this model, send {type: between_tools} instead of {type:
// disabled}": the remedy is named, and omitting the block would leave the model thinking
if self.can_disable && body.contains("between_tools") && body.contains("disabled") {
return Some(Self { can_disable: false, between_tools: true, ..self });
}
if self.can_disable && rejects(body, "disabled") {
return Some(Self { can_disable: false, ..self });
}
match self.mode {
ThinkingMode::Extended if rejects(body, "enabled") => {
Some(Self { mode: ThinkingMode::Adaptive, ..self })
}
ThinkingMode::Adaptive if rejects(body, "adaptive") => {
Some(Self { mode: ThinkingMode::Extended, ..self })
}
_ => None,
}
}
}
/// Whether `body` is Anthropic naming `thinking.type.<what>` as the value it rejected.
///
/// The complaint follows the rejected value and the *suggested* replacement follows the complaint
/// ("thinking.type.enabled is not supported … Use thinking.type.adaptive …"), so the match has to
/// stay local to each mention — scanning the whole body would read the remedy as a second rejection
/// and flip the encoding straight back.
fn rejects(body: &str, what: &str) -> bool {
const COMPLAINT_WINDOW: usize = 40;
let needle = format!("thinking.type.{what}");
body.match_indices(&needle).any(|(at, _)| {
body[at + needle.len()..]
.chars()
.take(COMPLAINT_WINDOW)
.collect::<String>()
.contains("not supported")
})
}
/// How a deferred tool reaches the model once `activate_tools` asks for it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ToolLoading {
/// In `tools`, which the engine has already grown by the activated ones
Listed,
/// Sent with `defer_loading` and expanded where the activation happened, by `tool_reference`
InPlace,
}
/// Whether `body` is a 400 about in-place tool loading itself, so listing the tools instead would
/// get the request through.
///
/// The phrases are the ones Anthropic uses (`defer_loading`, "Tool reference 'x' not found",
/// "Tool definitions … cannot be mixed with other content") plus the block's own type name, which
/// is what a proxy that doesn't know it tends to quote back.
pub(crate) fn refuses_in_place_loading(body: &str) -> bool {
["defer_loading", "tool_reference", "Tool reference", "Tool definitions"]
.iter()
.any(|phrase| body.contains(phrase))
}
/// The deferred tools one request loads in place, by name; empty when it lists them instead.
///
/// In place only when there's something to load and something left in the list: Anthropic
/// requires at least one tool that isn't deferred, and a pass that withholds tools sends no
/// deferred ones either, which also keeps a `tool_reference` from pointing at nothing.
fn in_place_names(req: &CompletionRequest, loading: ToolLoading) -> HashSet<&str> {
if loading != ToolLoading::InPlace {
return HashSet::new();
}
let deferred: HashSet<&str> = req.deferred_tools.iter().map(|t| t.name.as_str()).collect();
let listed_any = req.tools.iter().any(|tool| !deferred.contains(tool.name.as_str()));
if listed_any {
deferred
} else {
HashSet::new()
}
}
/// Build an Anthropic Messages API request body.
pub(crate) fn build_anthropic_request(
req: &CompletionRequest,
model_info: &ModelInfo,
compat: &AnthropicCompat,
plan: ThinkingPlan,
loading: ToolLoading,
) -> serde_json::Value {
let in_place = in_place_names(req, loading);
let mut body = serde_json::json!({
"model": model_info.r#ref.id.clone(),
"max_tokens": req.max_tokens.unwrap_or(4096),
"messages": serialize_messages_loading(
&req.messages,
req.model.input.contains(&luxe_core::provider::Modality::Image),
&in_place,
),
});
// The engine puts the system prompt in `CompletionRequest.system`; a `System`-role *message*
// is only how an embedder might hand one over. Reading the message alone silently shipped
// every Anthropic request with no system prompt at all.
if let Some(system) =
req.system.clone().or_else(|| find_system_message(&req.messages)).filter(|s| !s.is_empty())
{
body["system"] = serde_json::Value::String(system);
}
if !req.tools.is_empty() {
let tool_json = |t: &luxe_core::provider::ToolSchema| {
let mut tool = serde_json::json!({
"name": t.name,
"description": t.description,
"input_schema": t.parameters,
});
// Per tool, not request-wide: unvalidated streaming garbles `edit`
if compat.stream_tool_arguments && luxe_core::activity::streams_arguments(&t.name) {
tool["eager_input_streaming"] = serde_json::Value::Bool(true);
}
tool
};
// The listed tools first and the deferred ones after, all in the order the engine sorted
// them. A deferred definition is outside the cached prefix, so the list is the same bytes
// before and after an activation and the prefix holds.
let listed =
req.tools.iter().filter(|t| !in_place.contains(t.name.as_str())).map(tool_json);
let deferred =
req.deferred_tools.iter().filter(|_| !in_place.is_empty()).map(tool_json).map(
|mut tool| {
tool["defer_loading"] = serde_json::Value::Bool(true);
tool
},
);
body["tools"] = serde_json::json!(listed.chain(deferred).collect::<Vec<_>>());
}
let (level, effort) = resolve_anthropic_thinking(model_info, req.thinking, compat);
match (level, plan.mode) {
// Off carries no `output_config`, which also keeps us clear of the newer rule that rejects
// a disabled block combined with xhigh/max effort.
(ThinkingLevel::Off, _) if plan.can_disable => {
body["thinking"] = serde_json::json!({"type": "disabled"});
}
// The newest models stop thinking only when told `between_tools`
(ThinkingLevel::Off, _) if plan.between_tools => {
body["thinking"] = serde_json::json!({"type": "between_tools"});
}
// Always-on models reject `disabled`; omitting the parameter is Anthropic's own remedy.
(ThinkingLevel::Off, _) => {}
(_, ThinkingMode::Adaptive) => {
// `display: "summarized"` because the newest models omit thinking text by default and
// Luxe shows reasoning in the transcript.
body["thinking"] = serde_json::json!({"type": "adaptive", "display": "summarized"});
body["output_config"] = serde_json::json!({"effort": effort});
}
(_, ThinkingMode::Extended) => {
body["thinking"] = serde_json::json!({
"type": "enabled",
"budget_tokens": manual_thinking_budget(level, req.max_tokens.unwrap_or(4096)),
});
}
}
// A one-off prompt is never read back, so a breakpoint on it only buys the write premium.
if compat.cache_control && req.reuse.worth_caching() {
add_cache_control_markers(&mut body, cache_marker(compat), req.shared_system_len);
}
body
}
/// Whether a request at `requested` goes out with thinking on, once the model's own limits apply.
pub(crate) fn thinking_is_on(
model: &ModelInfo,
requested: ThinkingLevel,
compat: &AnthropicCompat,
) -> bool {
resolve_anthropic_thinking(model, requested, compat).0 != ThinkingLevel::Off
}
/// The level this model will actually honor, plus the effort value that names it.
///
/// Anthropic models always reason, so a missing `reasoning` flag never silences thinking here.
fn resolve_anthropic_thinking(
model: &ModelInfo,
requested: ThinkingLevel,
compat: &AnthropicCompat,
) -> (ThinkingLevel, String) {
let mut capabilities = model.clone();
capabilities.reasoning = true;
// Forcing adaptive by hand is how an endpoint the catalog knows nothing about says "this is a
// current model", so grant it the top level the mode implies.
if compat.force_adaptive_thinking
&& !capabilities.thinking_level_map.contains_key("ultra")
&& !capabilities.thinking_level_map.contains_key("max")
{
capabilities.thinking_level_map.insert("ultra".to_string(), Some("max".to_string()));
}
let level = capabilities.effective_thinking_level(requested);
let value = capabilities
.thinking_level_value(level)
.unwrap_or(match level {
// Anthropic has no `minimal` effort; the floor is `low`.
ThinkingLevel::Off | ThinkingLevel::Minimal | ThinkingLevel::Low => "low",
ThinkingLevel::Medium => "medium",
ThinkingLevel::High => "high",
ThinkingLevel::XHigh => "xhigh",
ThinkingLevel::Ultra => "max",
})
.to_string();
(level, value)
}
/// The token budget a level asks for, reduced to fit under `max_tokens` when the cap is too small
/// to honor it.
///
/// A reduced budget leaves the reply a real share of the cap — half of it, up to 16k — because
/// thinking and answer draw on the same `max_tokens`. Shrinking only to the 1,024-token floor gave
/// XHigh on a 32k cap a 30,720 budget and the answer about 1,200 tokens, so a model that used its
/// budget was cut off mid-reply or mid-tool-call, and the error told the user to raise a cap that
/// was already the model's maximum.
///
/// The reduction is snapped to a coarse step for a reason that has nothing to do with thinking:
/// Anthropic invalidates the cached *messages* prefix whenever `budget_tokens` changes, and
/// `max_tokens` is itself clamped against a prompt that grows every turn. A budget read straight
/// off it would therefore drift by a few hundred tokens per call and re-bill the whole
/// conversation as a cache write each time.
fn manual_thinking_budget(level: ThinkingLevel, max_tokens: u32) -> u32 {
/// Anthropic's own floor for a thinking budget, and the granularity the reduction moves in.
const FLOOR: u32 = 1_024;
/// The most a squeezed budget holds back for the answer.
const ANSWER_RESERVE: u32 = 16_384;
let requested = match level {
ThinkingLevel::Off => 0,
ThinkingLevel::Minimal => FLOOR,
ThinkingLevel::Low => 2_048,
ThinkingLevel::Medium => 8_192,
ThinkingLevel::High => 16_384,
ThinkingLevel::XHigh => 32_768,
ThinkingLevel::Ultra => 65_536,
};
let reserve = (max_tokens / 2).clamp(FLOOR, ANSWER_RESERVE);
let room = max_tokens.saturating_sub(reserve).max(1);
if requested <= room {
return requested;
}
(room / FLOOR * FLOOR).clamp(1, room)
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,116 @@
//! Anthropic cache markers — where the request asks for its prefix to be kept.
use super::super::*;
/// Add `cache_control` breakpoints so Anthropic serves the stable prefix (and the conversation so
/// far) from cache instead of re-reading it every turn.
///
/// Anthropic caches the whole prompt prefix up to and including each marked block, in the canonical
/// order tools → system → messages, and allows four markers. Luxe spends them on:
///
/// 1. the system prompt, at the end of its shared part,
/// 2. the last listed tool definition — with (1), the ~static floor. A deferred one can't
/// carry a marker (it's outside the prefix, and Anthropic 400s on the pair),
/// 3. the end of the *previous* turn, and
/// 4. the end of this one, so the next request reads everything up to here at ~0.1x and writes
/// only its own delta.
///
/// (3) is the one that is easy to leave out and expensive to leave out. A lookup walks back at most
/// twenty content blocks from a marker looking for an entry to read, and a single agentic turn
/// appends more than that whenever the model calls tools in parallel — a reasoning block, a
/// `tool_use` per call, and a `tool_result` per call. Marking where the last request stopped puts
/// an exact entry at that position, so the read never depends on the lookback at all.
///
/// `shared` is how much of the system prompt every session shares; the breakpoint goes at its end
/// rather than the prompt's, so a session in another directory reads that much from cache instead
/// of writing the whole prompt again. The rest rides to the next breakpoint, on the conversation,
/// which keeps the count at Anthropic's four.
pub(crate) fn add_cache_control_markers(
body: &mut serde_json::Value,
marker: serde_json::Value,
shared: usize,
) {
if let Some(system) = body.get_mut("system") {
if let Some(text) = system.as_str() {
*system = match text.split_at_checked(shared) {
Some((head, tail)) if !head.is_empty() && !tail.trim().is_empty() => {
serde_json::json!([
{"type": "text", "text": head, "cache_control": marker.clone()},
{"type": "text", "text": tail},
])
}
_ => serde_json::json!([{
"type": "text", "text": text, "cache_control": marker.clone(),
}]),
};
}
}
if let Some(tools) = body.get_mut("tools").and_then(|t| t.as_array_mut()) {
if let Some(last) = tools.iter_mut().rev().find(|tool| tool.get("defer_loading").is_none())
{
last["cache_control"] = marker.clone();
}
}
if let Some(messages) = body.get_mut("messages").and_then(|m| m.as_array_mut()) {
for at in rolling_breakpoints(messages) {
mark_message_content_cached(&mut messages[at], marker.clone());
}
}
}
/// The `cache_control` value every breakpoint in this request carries.
///
/// The hour-long tier is opt-in: it doubles the write premium on each turn's delta — pennies — to
/// stop a six-minute pause re-writing the entire conversation, which is the right trade for
/// interactive work and the wrong one for a burst that never idles.
pub(super) fn cache_marker(compat: &AnthropicCompat) -> serde_json::Value {
match compat.long_cache_retention {
true => serde_json::json!({"type": "ephemeral", "ttl": "1h"}),
false => serde_json::json!({"type": "ephemeral"}),
}
}
/// Where this request ends, and where the last one did — oldest first, at most two.
///
/// Tool results serialize as a `user` turn, so the loop alternates and the previous request ended
/// at the `user` turn before the last message. A transcript that ends on an assistant reply (a
/// resumed session, a remediation) still gets both: the nearest earlier user turn, then the end.
fn rolling_breakpoints(messages: &[serde_json::Value]) -> Vec<usize> {
let Some(last) = messages.len().checked_sub(1) else { return Vec::new() };
let is_user =
|message: &serde_json::Value| message.get("role").and_then(|r| r.as_str()) == Some("user");
match messages[..last].iter().rposition(is_user) {
Some(previous) => vec![previous, last],
None => vec![last],
}
}
/// Attach `cache_control` to a message's last cacheable content block, normalizing string content
/// to a single text block first (Anthropic requires the marker on a content block, not the
/// message).
///
/// Reasoning blocks cannot carry one, so a turn that ends in thinking takes the marker on the last
/// block that can hold it rather than losing the breakpoint.
fn mark_message_content_cached(message: &mut serde_json::Value, marker: serde_json::Value) {
match message.get_mut("content") {
Some(serde_json::Value::String(text)) => {
let text = std::mem::take(text);
message["content"] =
serde_json::json!([{"type": "text", "text": text, "cache_control": marker}]);
}
Some(serde_json::Value::Array(blocks)) => {
let cacheable = blocks.iter().rposition(|block| {
!matches!(
block.get("type").and_then(|t| t.as_str()),
Some("thinking") | Some("redacted_thinking")
)
});
if let Some(block) = cacheable.and_then(|at| blocks[at].as_object_mut()) {
block.insert("cache_control".to_string(), marker);
}
}
_ => {}
}
}

View File

@@ -0,0 +1,243 @@
//! Anthropic message serialization — the transcript as the wire's `messages`.
use super::super::*;
use std::collections::{HashMap, HashSet};
/// [`serialize_messages_loading`] with nothing loaded in place.
#[cfg(test)]
pub(crate) fn serialize_messages(
messages: &[Message],
accepts_images: bool,
) -> Vec<serde_json::Value> {
serialize_messages_loading(messages, accepts_images, &HashSet::new())
}
/// Serialize core messages to Anthropic message format, loading the deferred tools named in
/// `in_place` where `activate_tools` asked for them.
///
/// Tool results map to a `user` turn, so a mid-turn steering message right after them would put
/// two `user` turns back to back — which the Messages API rejects. Adjacent same-role turns are
/// merged into one with their content blocks concatenated, which is exactly how the API treats
/// them anyway.
///
/// A turn that serializes to no blocks at all is dropped here rather than sent empty. This is the
/// one place that can know: blocks this adapter alone refuses — reasoning captured from another
/// provider, which has no Anthropic signature to replay — can leave a message with nothing in it,
/// and an empty `content` is a 400 that replays on every later request.
///
/// A successful activation's result becomes a `tool_result` of `tool_reference` blocks, which the
/// API expands into the full definitions at that point in the conversation. It's derived from the
/// transcript alone, so every later request carries the same bytes and the cache keeps them.
pub(crate) fn serialize_messages_loading(
messages: &[Message],
accepts_images: bool,
in_place: &HashSet<&str>,
) -> Vec<serde_json::Value> {
let activations = activations(messages, in_place);
let serialized = messages
.iter()
.filter_map(|msg| {
let (role, content) = match msg.role {
luxe_core::message::Role::User => ("user", serialize_content_blocks(&msg.content)),
luxe_core::message::Role::Assistant => {
("assistant", serialize_content_blocks(&msg.content))
}
luxe_core::message::Role::Tool => (
"user",
serialize_tool_result_blocks(&msg.content, accepts_images, &activations),
),
// The Messages API takes only `user` and `assistant` turns; a system message
// rides in `system`, and here it was a 400
luxe_core::message::Role::System => return None,
};
Some(serde_json::json!({ "role": role, "content": content }))
})
.filter(|message| {
message
.get("content")
.and_then(serde_json::Value::as_array)
.is_none_or(|content| !content.is_empty())
})
.collect::<Vec<_>>();
merge_adjacent_roles(serialized)
}
/// The deferred tools each `activate_tools` call loads in place, by call id.
///
/// Only names in `in_place`: a reference to a tool the request doesn't define is a 400 that would
/// replay on every later request, and a core tool needs no loading.
fn activations<'a>(
messages: &'a [Message],
in_place: &HashSet<&str>,
) -> HashMap<&'a str, Vec<String>> {
if in_place.is_empty() {
return HashMap::new();
}
messages
.iter()
.flat_map(|message| &message.content)
.filter_map(|block| match block {
luxe_core::message::ContentBlock::ToolCall { id, name, arguments }
if name == luxe_core::tool::ACTIVATE_TOOLS_NAME =>
{
let names: Vec<String> = luxe_core::tool_activation::requested_names(arguments)
.into_iter()
.filter(|name| in_place.contains(name.as_str()))
.collect();
(!names.is_empty()).then_some((id.as_str(), names))
}
_ => None,
})
.collect()
}
/// Folds consecutive same-role turns into one, concatenating their content arrays in order.
fn merge_adjacent_roles(messages: Vec<serde_json::Value>) -> Vec<serde_json::Value> {
let mut out: Vec<serde_json::Value> = Vec::with_capacity(messages.len());
for message in messages {
let same_role = out.last().is_some_and(|last| last.get("role") == message.get("role"));
if !same_role {
out.push(message);
continue;
}
let Some(previous) = out.last_mut() else { continue };
let (Some(target), Some(extra)) = (
previous.get_mut("content").and_then(serde_json::Value::as_array_mut),
message.get("content").and_then(serde_json::Value::as_array),
) else {
out.push(message);
continue;
};
target.extend(extra.iter().cloned());
}
out
}
/// Serialize content blocks to Anthropic format.
pub(crate) fn serialize_content_blocks(
blocks: &[luxe_core::message::ContentBlock],
) -> Vec<serde_json::Value> {
blocks
.iter()
.filter_map(|block| match block {
luxe_core::message::ContentBlock::Text(text) => Some(serde_json::json!({
"type": "text",
"text": text,
})),
// Reasoning must round-trip byte-for-byte or Anthropic rejects it. A block with no
// signature can't be replayed safely (it would 400 as an invalid/empty signature), so
// drop it — this also correctly skips reasoning captured from other providers.
luxe_core::message::ContentBlock::Thinking { text, signature, .. } => {
signature.as_ref().map(|signature| {
serde_json::json!({
"type": "thinking",
"thinking": text,
"signature": signature,
})
})
}
luxe_core::message::ContentBlock::RedactedThinking { data } => {
Some(serde_json::json!({
"type": "redacted_thinking",
"data": data,
}))
}
luxe_core::message::ContentBlock::ToolCall { id, name, arguments } => {
Some(serde_json::json!({
"type": "tool_use",
"id": id,
"name": name,
"input": arguments,
}))
}
// Tool results are serialized separately (see `serialize_tool_result_blocks`).
luxe_core::message::ContentBlock::ToolResult { .. } => None,
luxe_core::message::ContentBlock::Image { data, mime, .. } => Some(serde_json::json!({
"type": "image",
"source": {
"type": "base64",
"media_type": mime,
"data": data,
},
})),
})
.collect()
}
/// Serialize tool result blocks to Anthropic format.
///
/// `accepts_images` gates the pixels: this API takes image blocks inside a `tool_result`, so no
/// carrier message and no restructuring is needed — but a model that does not declare vision is
/// still billed for every base64 byte it is sent, so it never receives them.
///
/// A successful call in `activations` answers with its `tool_reference` blocks alone, so the tool's
/// own text is dropped. Nowhere else will take it: the API refuses a result that mixes references
/// with anything else, and a text block beside the results makes the turn a user message, which
/// strips earlier reasoning from the rendered prompt and misses the cache on everything after it.
/// The expanded definitions say what loaded anyway.
pub(crate) fn serialize_tool_result_blocks(
blocks: &[luxe_core::message::ContentBlock],
accepts_images: bool,
activations: &HashMap<&str, Vec<String>>,
) -> Vec<serde_json::Value> {
blocks
.iter()
.filter_map(|block| {
let luxe_core::message::ContentBlock::ToolResult { call_id, content, is_error } = block
else {
return None;
};
if let Some(names) = activations.get(call_id.as_str()).filter(|_| !is_error) {
let references: Vec<serde_json::Value> = names
.iter()
.map(|name| serde_json::json!({ "type": "tool_reference", "tool_name": name }))
.collect();
return Some(serde_json::json!({
"type": "tool_result",
"tool_use_id": call_id,
"content": references,
"is_error": false,
}));
}
let images: Vec<(&str, &str)> = if accepts_images {
luxe_core::message::ToolOutput::images(content).collect()
} else {
Vec::new()
};
let text = luxe_core::message::ToolOutput::joined_text(content);
// The plain string stays the shape for a text-only result, which is nearly all of
// them: every transcript and wire test already reads that way, and there is nothing to
// gain from churning it.
let content = if images.is_empty() {
serde_json::Value::String(text)
} else {
let mut parts = Vec::with_capacity(images.len() + 1);
if !text.is_empty() {
parts.push(serde_json::json!({ "type": "text", "text": text }));
}
parts.extend(images.iter().map(|(mime, data)| {
serde_json::json!({
"type": "image",
"source": { "type": "base64", "media_type": mime, "data": data },
})
}));
serde_json::Value::Array(parts)
};
Some(serde_json::json!({
"type": "tool_result",
"tool_use_id": call_id,
"content": content,
"is_error": is_error,
}))
})
.collect()
}
/// Find a `System`-role message's text, for a caller that passes the prompt that way.
///
/// Luxe's engine does not — it uses [`CompletionRequest::system`] — so this is a fallback.
pub(crate) fn find_system_message(messages: &[Message]) -> Option<String> {
messages.iter().find(|m| m.role == luxe_core::message::Role::System).map(Message::text)
}

View File

@@ -0,0 +1,463 @@
use super::*;
use luxe_core::message::{ContentBlock, Message, Role, ToolOutput};
use luxe_core::provider::PromptReuse;
fn request_with(system: Option<&str>, messages: Vec<Message>) -> CompletionRequest {
CompletionRequest {
model: ModelInfo::default(),
messages,
system: system.map(str::to_string),
tools: vec![],
thinking: ThinkingLevel::Off,
max_tokens: Some(1024),
..Default::default()
}
}
/// The regression that made every Anthropic turn run with no instructions at all: the body
/// was built from a `System`-role message the engine never creates.
#[test]
fn the_system_prompt_reaches_the_body_from_the_request_field() {
let req =
request_with(Some("## Role\n\nYou are a senior engineer."), vec![Message::user("hi")]);
let body = build_anthropic_request(
&req,
&ModelInfo::default(),
&AnthropicCompat { cache_control: false, ..AnthropicCompat::default() },
ThinkingPlan { mode: ThinkingMode::Extended, can_disable: true, between_tools: false },
ToolLoading::InPlace,
);
assert_eq!(body["system"], "## Role\n\nYou are a senior engineer.");
}
#[test]
fn a_system_role_message_still_works_for_an_embedder() {
let messages = vec![
Message { role: Role::System, content: vec![ContentBlock::Text("from a message".into())] },
Message::user("hi"),
];
let body = build_anthropic_request(
&request_with(None, messages),
&ModelInfo::default(),
&AnthropicCompat { cache_control: false, ..AnthropicCompat::default() },
ThinkingPlan { mode: ThinkingMode::Extended, can_disable: true, between_tools: false },
ToolLoading::InPlace,
);
assert_eq!(body["system"], "from a message");
// The Messages API takes only `user` and `assistant` turns: a system one there is a 400
let roles: Vec<&str> =
body["messages"].as_array().unwrap().iter().filter_map(|m| m["role"].as_str()).collect();
assert_eq!(roles, ["user"]);
}
#[test]
fn an_absent_system_prompt_omits_the_field_rather_than_sending_an_empty_one() {
let body = build_anthropic_request(
&request_with(None, vec![Message::user("hi")]),
&ModelInfo::default(),
&AnthropicCompat::default(),
ThinkingPlan { mode: ThinkingMode::Extended, can_disable: true, between_tools: false },
ToolLoading::InPlace,
);
assert!(body.get("system").is_none());
}
/// Caching only pays if the prompt is actually there to cache.
#[test]
fn the_system_prompt_carries_a_cache_breakpoint() {
let body = build_anthropic_request(
&request_with(Some("stable instructions"), vec![Message::user("hi")]),
&ModelInfo::default(),
&AnthropicCompat::default(),
ThinkingPlan { mode: ThinkingMode::Extended, can_disable: true, between_tools: false },
ToolLoading::InPlace,
);
assert_eq!(body["system"][0]["text"], "stable instructions");
assert_eq!(body["system"][0]["cache_control"]["type"], "ephemeral");
}
/// The marker that pays for itself: without one at the previous turn's end, a batch of
/// parallel tool calls appends more than the twenty content blocks a lookup will walk back
/// through, and the whole conversation is re-billed as a cache write.
#[test]
fn both_the_last_turn_and_the_one_before_it_are_marked() {
let messages = vec![
Message::user("start"),
Message {
role: Role::Assistant,
content: vec![ContentBlock::ToolCall {
id: "call-1".into(),
name: "read".into(),
arguments: serde_json::json!({}),
}],
},
Message {
role: Role::Tool,
content: vec![ContentBlock::ToolResult {
call_id: "call-1".into(),
content: vec![ToolOutput::Text("file body".into())],
is_error: false,
}],
},
];
let body = build_anthropic_request(
&request_with(Some("stable"), messages),
&ModelInfo::default(),
&AnthropicCompat::default(),
ThinkingPlan { mode: ThinkingMode::Extended, can_disable: true, between_tools: false },
ToolLoading::InPlace,
);
let marked: Vec<usize> = body["messages"]
.as_array()
.expect("messages")
.iter()
.enumerate()
.filter(|(_, message)| {
message["content"]
.as_array()
.is_some_and(|blocks| blocks.iter().any(|b| b.get("cache_control").is_some()))
})
.map(|(at, _)| at)
.collect();
assert_eq!(marked, vec![0, 2], "this turn's end and the previous one's");
}
/// Anthropic rejects a marker on a reasoning block, so a turn ending in one takes it on the
/// last block that can hold it instead of losing the breakpoint.
#[test]
fn a_reply_that_ends_in_reasoning_still_gets_a_breakpoint() {
let messages = vec![
Message::user("start"),
Message {
role: Role::Assistant,
content: vec![
ContentBlock::Text("working on it".into()),
ContentBlock::Thinking {
text: "hmm".into(),
signature: Some("sig".into()),
id: None,
encrypted: None,
opaque: None,
},
],
},
];
let body = build_anthropic_request(
&request_with(Some("stable"), messages),
&ModelInfo::default(),
&AnthropicCompat::default(),
ThinkingPlan { mode: ThinkingMode::Extended, can_disable: true, between_tools: false },
ToolLoading::InPlace,
);
let blocks = body["messages"][1]["content"].as_array().expect("content");
assert_eq!(blocks[0]["type"], "text");
assert_eq!(blocks[0]["cache_control"]["type"], "ephemeral");
assert!(blocks[1].get("cache_control").is_none(), "never on a thinking block");
}
/// The summarizer and the guide pass each build a prompt, send it once and throw it away.
/// Caching one costs a quarter more than sending it plainly and returns nothing, and the
/// summarizer's prompt is a whole context window by construction — so it is the expensive one
/// to get wrong.
#[test]
fn a_prompt_nothing_will_read_back_asks_for_no_cache_at_all() {
let body = |reuse| {
let mut request = request_with(Some("stable"), vec![Message::user("summarize this")]);
request.reuse = reuse;
build_anthropic_request(
&request,
&ModelInfo::default(),
&AnthropicCompat::default(),
ThinkingPlan { mode: ThinkingMode::Extended, can_disable: true, between_tools: false },
ToolLoading::InPlace,
)
};
let one_off = body(PromptReuse::OneOff);
assert!(one_off["system"].is_string(), "not even normalized to blocks: {one_off}");
assert_eq!(
serde_json::to_string(&one_off).expect("serializes").matches("cache_control").count(),
0,
);
// …and the conversation it was summarizing still asks for every breakpoint it can use.
let turn = body(PromptReuse::Conversation);
assert_eq!(turn["system"][0]["cache_control"]["type"], "ephemeral");
assert_eq!(turn["messages"][0]["content"][0]["cache_control"]["type"], "ephemeral");
}
/// The lifetime is opt-in and applies to every breakpoint at once, so a session either keeps
/// its cache for an hour or it doesn't — a prefix cached under two lifetimes is two entries.
#[test]
fn the_hour_long_cache_is_asked_for_only_when_the_endpoint_says_it_takes_one() {
let body = |long: bool| {
build_anthropic_request(
&request_with(Some("stable"), vec![Message::user("hi")]),
&ModelInfo::default(),
&AnthropicCompat { long_cache_retention: long, ..AnthropicCompat::default() },
ThinkingPlan { mode: ThinkingMode::Extended, can_disable: true, between_tools: false },
ToolLoading::InPlace,
)
};
assert!(body(false)["system"][0]["cache_control"].get("ttl").is_none());
let hour = body(true);
assert_eq!(hour["system"][0]["cache_control"]["ttl"], "1h");
assert_eq!(hour["messages"][0]["content"][0]["cache_control"]["ttl"], "1h");
}
/// A budget that tracked `max_tokens` exactly would move every turn as the prompt grows, and
/// Anthropic treats any change to it as a reason to drop the cached conversation.
#[test]
fn the_thinking_budget_holds_still_as_the_window_fills() {
// Room to spare: the level's own budget, unchanged.
assert_eq!(manual_thinking_budget(ThinkingLevel::High, 64_000), 16_384);
// Closing in: reduced, but snapped so a few hundred tokens of drift changes nothing.
let squeezed: Vec<u32> = [20_000, 19_800, 19_100, 18_500]
.into_iter()
.map(|max| manual_thinking_budget(ThinkingLevel::XHigh, max))
.collect();
assert_eq!(squeezed, vec![9_216, 9_216, 9_216, 9_216]);
}
/// Thinking and the reply share `max_tokens`, so a budget that doesn't fit must not take the
/// reply's share with it. Real caps: Copilot serves Sonnet 4.6 at 32k, Haiku 4.5 tops out at
/// 64k, and both still take a token budget.
#[test]
fn a_squeezed_thinking_budget_leaves_the_answer_room_to_finish() {
for (level, max) in [
(ThinkingLevel::XHigh, 32_000),
(ThinkingLevel::Ultra, 32_000),
(ThinkingLevel::Ultra, 64_000),
(ThinkingLevel::High, 20_000),
(ThinkingLevel::Medium, 8_000),
] {
let budget = manual_thinking_budget(level, max);
let answer = max - budget;
assert!(
answer >= (max / 2).min(16_384),
"{level:?} at {max}: budget {budget} leaves the answer only {answer}"
);
assert!(budget >= 1_024, "still a budget Anthropic accepts");
}
// A level that fits is never touched.
assert_eq!(manual_thinking_budget(ThinkingLevel::XHigh, 128_000), 32_768);
assert_eq!(manual_thinking_budget(ThinkingLevel::Ultra, 128_000), 65_536);
}
#[test]
fn a_steer_after_tool_results_merges_into_one_user_turn() {
// Tool results serialize as `user`, so a steering message right behind them would
// otherwise send two consecutive user turns.
let messages = vec![
Message::user("start"),
Message {
role: Role::Assistant,
content: vec![ContentBlock::ToolCall {
id: "call-1".into(),
name: "read".into(),
arguments: serde_json::json!({}),
}],
},
Message {
role: Role::Tool,
content: vec![ContentBlock::ToolResult {
call_id: "call-1".into(),
content: vec![ToolOutput::Text("file body".into())],
is_error: false,
}],
},
Message::user("actually, check the tests too"),
];
let serialized = serialize_messages(&messages, false);
let roles: Vec<&str> = serialized.iter().filter_map(|m| m["role"].as_str()).collect::<Vec<_>>();
assert_eq!(roles, vec!["user", "assistant", "user"], "roles must alternate");
let merged = serialized.last().expect("the merged user turn");
let blocks = merged["content"].as_array().expect("content array");
assert_eq!(blocks.len(), 2, "tool result + steer text share one turn");
assert_eq!(blocks[0]["type"], "tool_result");
assert_eq!(blocks[1]["type"], "text");
assert_eq!(blocks[1]["text"], "actually, check the tests too");
}
// === In-place tool loading ===
fn schema(name: &str) -> luxe_core::provider::ToolSchema {
luxe_core::provider::ToolSchema {
name: name.to_string(),
description: format!("The {name} tool."),
parameters: serde_json::json!({"type": "object", "properties": {}}),
}
}
fn schemas(names: &[&str]) -> Vec<luxe_core::provider::ToolSchema> {
names.iter().map(|name| schema(name)).collect()
}
fn activation(id: &str, names: &[&str], said: &str, is_error: bool) -> [Message; 2] {
[
Message {
role: Role::Assistant,
content: vec![ContentBlock::ToolCall {
id: id.to_string(),
name: luxe_core::tool::ACTIVATE_TOOLS_NAME.to_string(),
arguments: serde_json::json!({ "names": names }),
}],
},
Message::tool_result(id, said, is_error),
]
}
/// A lazy-tools request the way the engine builds one: the core tier plus whatever has been
/// activated in `tools`, and every deferred tool in `deferred_tools`.
fn lazy_request(activated: &[&str], messages: Vec<Message>) -> CompletionRequest {
let mut tools = schemas(&["activate_tools", "bash", "read"]);
tools.extend(schemas(activated));
tools.sort_by(|a, b| a.name.cmp(&b.name));
CompletionRequest {
tools,
deferred_tools: schemas(&["debug", "test"]),
..request_with(Some("stable"), messages)
}
}
fn body(req: &CompletionRequest, loading: ToolLoading) -> serde_json::Value {
build_anthropic_request(
req,
&ModelInfo::default(),
&AnthropicCompat::default(),
ThinkingPlan { mode: ThinkingMode::Extended, can_disable: true, between_tools: false },
loading,
)
}
fn tool_names(body: &serde_json::Value) -> Vec<String> {
body["tools"]
.as_array()
.expect("tools")
.iter()
.map(|tool| tool["name"].as_str().unwrap_or_default().to_string())
.collect()
}
/// The listed tools lead and the deferred ones follow with `defer_loading`. The cache marker
/// sits on the last listed tool, since Anthropic 400s on a deferred one that carries it.
#[test]
fn deferred_tools_follow_the_list_and_never_carry_the_marker() {
let body = body(&lazy_request(&[], vec![Message::user("hi")]), ToolLoading::InPlace);
assert_eq!(tool_names(&body), vec!["activate_tools", "bash", "read", "debug", "test"]);
let tools = body["tools"].as_array().unwrap();
for tool in &tools[..3] {
assert!(tool.get("defer_loading").is_none(), "listed: {tool}");
}
for tool in &tools[3..] {
assert_eq!(tool["defer_loading"], true, "deferred: {tool}");
assert!(tool.get("cache_control").is_none(), "never marked: {tool}");
}
assert_eq!(tools[2]["cache_control"]["type"], "ephemeral", "the last listed tool is");
}
/// The point of the whole thing: activating a tool leaves the tool list, the system prompt and
/// the conversation before it byte-identical, so the next request reads all of it from cache.
/// Listing it instead rewrites the list, which sits ahead of everything else in the prefix.
#[test]
fn an_activation_leaves_the_cached_prefix_alone() {
let opening = vec![Message::user("load the test runner")];
let before = lazy_request(&[], opening.clone());
let mut grown = opening;
grown.extend(activation("call-1", &["test"], "Activated: test.", false));
let after = lazy_request(&["test"], grown);
let (was, now) = (body(&before, ToolLoading::InPlace), body(&after, ToolLoading::InPlace));
assert_eq!(was["tools"], now["tools"], "the list holds still");
assert_eq!(was["system"], now["system"]);
let strip = |message: &serde_json::Value| {
let mut message = message.clone();
if let Some(blocks) = message["content"].as_array_mut() {
for block in blocks {
block.as_object_mut().map(|block| block.remove("cache_control"));
}
}
message
};
assert_eq!(strip(&was["messages"][0]), strip(&now["messages"][0]), "an append");
let listed = (body(&before, ToolLoading::Listed), body(&after, ToolLoading::Listed));
assert_ne!(listed.0["tools"], listed.1["tools"], "what listing it costs");
}
/// A successful activation answers with references and nothing else: the API refuses a result
/// that mixes them with text, and text beside the result strips earlier reasoning and misses
/// the cache (measured: a 7,794-token rewrite on the next call). Only a deferred tool is
/// referenced, since a core one needs no loading and an unknown one is a 400 that would replay
/// every turn.
#[test]
fn an_activation_answers_with_references_alone() {
let mut messages = vec![Message::user("go")];
messages.extend(activation(
"call-1",
&["test", "read", "nope"],
"Activated: test.\nNot activatable (already available or unknown): nope, read.",
false,
));
let body = body(&lazy_request(&["test"], messages), ToolLoading::InPlace);
let turn = body["messages"][2]["content"].as_array().expect("the result turn");
assert_eq!(turn.len(), 1, "the result and nothing beside it: {turn:?}");
assert_eq!(turn[0]["type"], "tool_result");
assert_eq!(turn[0]["tool_use_id"], "call-1");
assert_eq!(
turn[0]["content"],
serde_json::json!([{ "type": "tool_reference", "tool_name": "test" }])
);
}
/// An activation that loaded nothing stays what it was: a plain error result.
#[test]
fn a_failed_activation_is_left_as_text() {
let mut messages = vec![Message::user("go")];
messages.extend(activation("call-1", &["test"], "Error: no.", true));
let body = body(&lazy_request(&[], messages), ToolLoading::InPlace);
let turn = &body["messages"][2]["content"];
assert_eq!(turn[0]["content"], "Error: no.");
assert_eq!(turn[0]["is_error"], true);
}
/// Listing is the request Luxe always sent: the engine's list as is, and no reference anywhere.
/// The same holds for a pass that withholds tools, where a reference would point at nothing.
#[test]
fn listing_and_a_toolless_pass_send_no_deferred_tools() {
let mut messages = vec![Message::user("go")];
messages.extend(activation("call-1", &["test"], "Activated: test.", false));
let lazy = lazy_request(&["test"], messages.clone());
let listed = body(&lazy, ToolLoading::Listed);
assert_eq!(tool_names(&listed), vec!["activate_tools", "bash", "read", "test"]);
let plain = CompletionRequest { deferred_tools: Vec::new(), ..lazy.clone() };
assert_eq!(listed, body(&plain, ToolLoading::InPlace), "identical to no lazy tools at all");
let wrap_up = CompletionRequest { tools: Vec::new(), deferred_tools: Vec::new(), ..lazy };
let body = body(&wrap_up, ToolLoading::InPlace);
assert!(body.get("tools").is_none());
assert!(!body.to_string().contains("tool_reference"), "{body}");
}
#[test]
fn a_refusal_of_in_place_loading_is_recognized() {
for body in [
r#"{"error":{"message":"Tool reference 'nope' not found in available tools"}}"#,
r#"{"error":{"message":"tools.3.defer_loading: Extra inputs are not permitted"}}"#,
r#"{"error":{"message":"Tool definitions/code execution functions cannot be mixed with other content"}}"#,
r#"{"error":{"message":"messages.2.content.0.content.0.type: unknown variant tool_reference"}}"#,
] {
assert!(refuses_in_place_loading(body), "{body}");
}
assert!(!refuses_in_place_loading(r#"{"error":{"message":"max_tokens: too large"}}"#));
}

View File

@@ -0,0 +1,399 @@
//! Anthropic SSE decode — parse the event stream into `ProviderEvent`s.
use super::*;
/// Parse Anthropic SSE events from a whole response body into a vector of ProviderEvents.
///
/// The live path decodes record-by-record through [`AnthropicDecoder`]; this drives that same
/// decoder over an already-complete body, which is what the fixture tests exercise.
#[cfg(test)]
pub(crate) fn parse_anthropic_sse_text(text: &str) -> Vec<ProviderEvent> {
use crate::sse::SseDecoder;
let mut decoder = AnthropicDecoder::default();
let mut events = Vec::new();
for record in text.split("\n\n") {
decoder.record(record, &mut events);
}
events
}
/// Record-at-a-time Anthropic decoder.
///
/// Anthropic splits usage across the stream: `message_start` carries input + cache tokens,
/// `message_delta` carries the final output count. Both accumulate here and are emitted as one
/// normalized `Usage` just before the terminal `Done` (the turn loop stops on `Done`).
#[derive(Default)]
pub(crate) struct AnthropicDecoder {
usage: luxe_core::provider::Usage,
have_usage: bool,
}
impl crate::sse::SseDecoder for AnthropicDecoder {
fn record(&mut self, record: &str, out: &mut Vec<ProviderEvent>) {
let Some(event) = parse_sse_event(record) else { return };
match event {
AnthropicSseEvent::MessageStart(start_usage) => {
if let Some(u) = start_usage {
let read = u.cache_read_input_tokens.unwrap_or(0);
let write = u.cache_creation_input_tokens.unwrap_or(0);
// Normalize `prompt_tokens` to all input (Anthropic reports uncached only).
self.usage.prompt_tokens = u.input_tokens.unwrap_or(0) + read + write;
self.usage.cache_read_tokens = read;
self.usage.cache_write_tokens = write;
self.usage.cache_write_1h_tokens = u.hour_long_writes().min(write);
self.usage.completion_tokens = u.output_tokens.unwrap_or(0);
self.usage.reasoning_tokens = u.thinking_tokens();
self.have_usage = true;
}
}
AnthropicSseEvent::MessageDelta(delta) => {
if let Some(u) = &delta.usage {
if let Some(output) = u.output_tokens {
self.usage.completion_tokens = output;
}
// Thinking arrives with the final output count; a zero here would be the
// start-event value, so only a reported figure overwrites.
let thinking = u.thinking_tokens();
if thinking > 0 {
self.usage.reasoning_tokens = thinking;
}
self.have_usage = true;
}
if self.have_usage {
self.usage.total_tokens =
self.usage.prompt_tokens + self.usage.completion_tokens;
out.push(ProviderEvent::Usage(self.usage.clone()));
self.have_usage = false;
}
out.extend(map_anthropic_event(AnthropicSseEvent::MessageDelta(delta)));
}
other => out.extend(map_anthropic_event(other)),
}
}
}
/// Parse a single SSE event string.
pub(crate) fn parse_sse_event(event_str: &str) -> Option<AnthropicSseEvent> {
let lines: Vec<&str> = event_str.lines().collect();
if lines.is_empty() {
return None;
}
// Extract the event type.
let event_type = lines.iter().find(|l| l.starts_with("event: "))?.strip_prefix("event: ")?;
// Extract the data.
let data_lines: Vec<&str> = lines.iter().filter(|l| l.starts_with("data: ")).copied().collect();
if data_lines.is_empty() {
return None;
}
let data = data_lines[0].strip_prefix("data: ")?;
// Parse based on event type.
match event_type {
"content_block_start" => {
let block: AnthropicContentBlockStart = serde_json::from_str(data).ok()?;
Some(AnthropicSseEvent::ContentBlockStart(block))
}
"content_block_delta" => {
let delta: AnthropicContentBlockDelta = serde_json::from_str(data).ok()?;
Some(AnthropicSseEvent::ContentBlockDelta(delta))
}
"content_block_stop" => {
let stop: AnthropicContentBlockStop = serde_json::from_str(data).ok()?;
Some(AnthropicSseEvent::ContentBlockStop(stop))
}
"message_delta" => {
let delta: AnthropicMessageDelta = serde_json::from_str(data).ok()?;
Some(AnthropicSseEvent::MessageDelta(delta))
}
"message_start" => {
let start: AnthropicMessageStart = serde_json::from_str(data).ok()?;
Some(AnthropicSseEvent::MessageStart(start.message.and_then(|m| m.usage)))
}
"message_stop" => Some(AnthropicSseEvent::MessageStop),
"error" => {
let error: AnthropicError = serde_json::from_str(data).ok()?;
Some(AnthropicSseEvent::Error(error))
}
_ => None,
}
}
/// Map an Anthropic SSE event to a core ProviderEvent, or `None` for one that carries nothing the
/// engine reads.
pub(crate) fn map_anthropic_event(event: AnthropicSseEvent) -> Option<ProviderEvent> {
Some(match event {
// Its usage is read by `AnthropicDecoder::record`, which never hands it on
AnthropicSseEvent::MessageStart(_) => return None,
AnthropicSseEvent::ContentBlockStart(block) => {
// Use Anthropic's own content-block index so a tool call's later `input_json_delta`
// chunks match the `ToolCallStart` they belong to (a per-event counter does NOT match).
let index = block.index;
let inner = block.content_block.unwrap_or(AnthropicBlockInner {
inner_type: String::new(),
id: None,
name: None,
text: None,
thinking: None,
data: None,
});
match inner.inner_type.as_str() {
"text" => ProviderEvent::TextDelta { index, delta: inner.text.unwrap_or_default() },
"thinking" => ProviderEvent::ThinkingDelta {
index,
delta: inner.thinking.unwrap_or_default(),
},
"redacted_thinking" => {
ProviderEvent::RedactedThinking { index, data: inner.data.unwrap_or_default() }
}
"tool_use" => ProviderEvent::ToolCallStart {
index,
id: inner.id.unwrap_or_default(),
name: inner.name.unwrap_or_default(),
},
_ => return None,
}
}
AnthropicSseEvent::ContentBlockDelta(delta) => {
let index = delta.index;
let inner = delta.delta.unwrap_or(AnthropicDeltaInner {
inner_type: String::new(),
text: None,
thinking: None,
signature: None,
partial_json: None,
});
match inner.inner_type.as_str() {
"text_delta" => {
ProviderEvent::TextDelta { index, delta: inner.text.unwrap_or_default() }
}
"thinking_delta" => ProviderEvent::ThinkingDelta {
index,
delta: inner.thinking.unwrap_or_default(),
},
"signature_delta" => ProviderEvent::ThinkingSignature {
index,
signature: inner.signature.unwrap_or_default(),
},
"input_json_delta" => ProviderEvent::ToolCallDelta {
index,
json_delta: inner.partial_json.unwrap_or_default(),
},
_ => return None,
}
}
AnthropicSseEvent::ContentBlockStop(stop) => {
ProviderEvent::ToolCallEnd { index: stop.index }
}
AnthropicSseEvent::MessageDelta(delta) => {
let stop_reason = delta
.stop_reason
.or_else(|| delta.delta.as_ref().and_then(|d| d.stop_reason.clone()));
let reason = match stop_reason.as_deref() {
Some("end_turn") | None => StopReason::EndTurn,
Some("max_tokens") => StopReason::Length,
Some("tool_use") => StopReason::ToolCall,
// The model declined, which is not the same as finishing
Some("refusal") => StopReason::ContentFilter,
Some(other) => StopReason::Other(other.to_string()),
};
ProviderEvent::Done { reason }
}
AnthropicSseEvent::MessageStop => ProviderEvent::Done { reason: StopReason::EndTurn },
AnthropicSseEvent::Error(error) => {
let inner = error.error.as_ref();
let kind = inner.and_then(|inner| inner.r#type.as_deref()).map_or_else(
|| luxe_core::provider::ProviderErrorKind::Other("anthropic error".to_string()),
crate::http::kind_of_error_type,
);
let message = error.message.or_else(|| inner.and_then(|e| e.message.clone()));
ProviderEvent::Error { message: message.unwrap_or_default(), kind }
}
})
}
/// Anthropic SSE event types.
#[derive(Debug)]
pub(crate) enum AnthropicSseEvent {
/// `message_start` carries initial usage (input + cache tokens).
MessageStart(Option<AnthropicUsage>),
ContentBlockStart(AnthropicContentBlockStart),
ContentBlockDelta(AnthropicContentBlockDelta),
ContentBlockStop(AnthropicContentBlockStop),
MessageDelta(AnthropicMessageDelta),
MessageStop,
Error(AnthropicError),
}
/// Anthropic `message_start` wrapper (only its usage block matters here).
#[derive(Debug, Deserialize)]
pub(crate) struct AnthropicMessageStart {
#[serde(default)]
pub(crate) message: Option<AnthropicMessageStartInner>,
}
/// Inner `message` object of a `message_start` event.
#[derive(Debug, Deserialize)]
pub(crate) struct AnthropicMessageStartInner {
#[serde(default)]
pub(crate) usage: Option<AnthropicUsage>,
}
/// Anthropic usage block (on `message_start` and `message_delta`). `input_tokens` is the
/// UNCACHED input; cache read/creation are reported separately and added in.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct AnthropicUsage {
#[serde(default)]
pub(crate) input_tokens: Option<u32>,
#[serde(default)]
pub(crate) output_tokens: Option<u32>,
#[serde(default)]
pub(crate) cache_creation_input_tokens: Option<u32>,
#[serde(default)]
pub(crate) cache_read_input_tokens: Option<u32>,
/// Breakdown of `output_tokens`; carries the thinking subset.
#[serde(default)]
pub(crate) output_tokens_details: Option<AnthropicOutputDetails>,
/// Breakdown of `cache_creation_input_tokens` by how long the entries are kept.
#[serde(default)]
pub(crate) cache_creation: Option<AnthropicCacheCreation>,
}
/// Anthropic's `cache_creation` — the cache writes split by lifetime, which are priced apart.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct AnthropicCacheCreation {
#[serde(default)]
pub(crate) ephemeral_1h_input_tokens: Option<u32>,
}
impl AnthropicUsage {
/// Cache writes kept for an hour, or 0 when the API didn't break them out.
pub(crate) fn hour_long_writes(&self) -> u32 {
self.cache_creation.as_ref().and_then(|split| split.ephemeral_1h_input_tokens).unwrap_or(0)
}
/// Thinking tokens inside `output_tokens`, or 0 when the API didn't break them out.
pub(crate) fn thinking_tokens(&self) -> u32 {
self.output_tokens_details.as_ref().and_then(|details| details.thinking_tokens).unwrap_or(0)
}
}
/// Anthropic's `output_tokens_details` — the reasoning slice of the output count.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct AnthropicOutputDetails {
#[serde(default)]
pub(crate) thinking_tokens: Option<u32>,
}
/// Anthropic content block start event.
#[derive(Debug, Deserialize)]
pub(crate) struct AnthropicContentBlockStart {
/// The wire discriminator. Nothing branches on it — the envelope already routed by tag — but
/// the parser tests assert it, which is how a shape change gets caught rather than ignored.
#[serde(rename = "type")]
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) block_type: String,
/// Anthropic's content-block position; ties a tool call's deltas back to its start.
#[serde(default)]
pub(crate) index: usize,
#[serde(default)]
pub(crate) content_block: Option<AnthropicBlockInner>,
}
/// Anthropic `content_block_stop` — carries the block index that finished.
#[derive(Debug, Deserialize)]
pub(crate) struct AnthropicContentBlockStop {
#[serde(default)]
pub(crate) index: usize,
}
/// Inner content block structure.
#[derive(Debug, Deserialize)]
pub(crate) struct AnthropicBlockInner {
#[serde(rename = "type")]
pub(crate) inner_type: String,
#[serde(default)]
pub(crate) id: Option<String>,
#[serde(default)]
pub(crate) name: Option<String>,
#[serde(default)]
pub(crate) text: Option<String>,
#[serde(default)]
pub(crate) thinking: Option<String>,
/// Opaque encrypted reasoning for a `redacted_thinking` block.
#[serde(default)]
pub(crate) data: Option<String>,
}
/// Anthropic content block delta event.
#[derive(Debug, Deserialize)]
pub(crate) struct AnthropicContentBlockDelta {
/// The wire discriminator; see [`AnthropicContentBlockStart::block_type`].
#[serde(rename = "type")]
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) delta_type: String,
/// Anthropic's content-block position (matches the `ToolCallStart` index).
#[serde(default)]
pub(crate) index: usize,
#[serde(default)]
pub(crate) delta: Option<AnthropicDeltaInner>,
}
/// Inner delta structure for content block deltas.
#[derive(Debug, Deserialize)]
pub(crate) struct AnthropicDeltaInner {
#[serde(rename = "type")]
pub(crate) inner_type: String,
#[serde(default)]
pub(crate) text: Option<String>,
#[serde(default)]
pub(crate) thinking: Option<String>,
/// The block's opaque signature, delivered via `signature_delta`.
#[serde(default)]
pub(crate) signature: Option<String>,
#[serde(default)]
pub(crate) partial_json: Option<String>,
}
/// Anthropic message delta event.
#[derive(Debug, Deserialize)]
pub(crate) struct AnthropicMessageDelta {
#[serde(default)]
pub(crate) stop_reason: Option<String>,
#[serde(default)]
pub(crate) delta: Option<MessageDeltaInner>,
/// Final output-token count for the message.
#[serde(default)]
pub(crate) usage: Option<AnthropicUsage>,
}
/// Inner message delta structure.
#[derive(Debug, Deserialize)]
pub(crate) struct MessageDeltaInner {
#[serde(default)]
pub(crate) stop_reason: Option<String>,
}
/// Anthropic error format.
#[derive(Debug, Deserialize)]
pub(crate) struct AnthropicError {
#[serde(default)]
pub(crate) message: Option<String>,
#[serde(default)]
pub(crate) error: Option<AnthropicErrorInner>,
}
/// Inner error structure.
#[derive(Debug, Deserialize)]
pub(crate) struct AnthropicErrorInner {
#[serde(default)]
pub(crate) message: Option<String>,
/// `overloaded_error`, `rate_limit_error` and the like: what to do, without reading the words
#[serde(default, rename = "type")]
pub(crate) r#type: Option<String>,
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,54 @@
//! What the Anthropic decoder makes of the stream's errors and stop reasons.
use super::*;
fn decode(text: &str) -> Vec<ProviderEvent> {
parse_anthropic_sse_text(text)
}
/// An `overloaded_error` frame is a provider that cannot serve the request just now, whatever its
/// message says.
///
/// The break this catches: the frame's type was thrown away and its kind set to an opaque
/// "anthropic error", so whether it was retried rode on the message happening to say "overloaded".
#[test]
fn an_overloaded_error_frame_is_unavailable() {
let events = decode(
"event: error\ndata: {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Please try again\"}}",
);
let [ProviderEvent::Error { kind, message }] = &events[..] else { panic!("{events:?}") };
assert_eq!(*kind, luxe_core::provider::ProviderErrorKind::Unavailable);
assert_eq!(message, "Please try again");
}
fn stop(reason: &str) -> Vec<ProviderEvent> {
decode(&format!(
"event: message_delta\ndata: {{\"type\":\"message_delta\",\"delta\":{{\"stop_reason\":\"{reason}\"}}}}"
))
}
/// A refusal is the model declining, not finishing, and a stop reason Luxe does not know is
/// said as itself.
///
/// The break this catches: every stop reason the decoder did not name became `EndTurn`, so a
/// refused request looked like a finished answer.
#[test]
fn a_refusal_is_not_an_end_of_turn() {
let reason = |name: &str| match &stop(name)[..] {
[ProviderEvent::Done { reason }] => reason.clone(),
other => panic!("{other:?}"),
};
assert_eq!(reason("refusal"), StopReason::ContentFilter);
assert_eq!(reason("pause_turn"), StopReason::Other("pause_turn".into()));
assert_eq!(reason("end_turn"), StopReason::EndTurn);
}
/// Frames that carry nothing for the engine produce no event, rather than an empty text delta
/// the engine has to filter.
#[test]
fn an_unknown_block_or_delta_produces_nothing() {
let unknown_block = "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"server_tool_use\"}}";
assert!(decode(unknown_block).is_empty());
let unknown_delta = "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"citations_delta\"}}";
assert!(decode(unknown_delta).is_empty());
}

View File

@@ -0,0 +1,15 @@
use super::*;
use crate::test_server::{http_reply, serve_held_open, serve_once, serve_replies};
use futures::StreamExt;
use luxe_core::provider::{ModelRef, ThinkingControls};
use std::collections::HashMap;
mod request;
mod sse;
mod sse_flows;
mod streaming;
mod support;
mod thinking;
mod wire;
use support::*;

View File

@@ -0,0 +1,254 @@
//! Request — the body the adapter builds, tools, images and cache markers.
use super::*;
#[test]
fn test_build_anthropic_request_basic() {
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![Message::user("Hello")],
system: None,
tools: vec![],
max_tokens: Some(100),
thinking: ThinkingLevel::Off,
..Default::default()
};
let model_info = ModelInfo::default();
let compat = AnthropicCompat::default();
let body = build_request(&req, &model_info, &compat);
assert_eq!(body["max_tokens"], 100);
assert_eq!(body["messages"][0]["role"], "user");
assert_eq!(body["messages"][0]["content"][0]["type"], "text");
}
#[test]
fn test_build_anthropic_request_with_thinking() {
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![Message::user("Hello")],
system: None,
tools: vec![],
max_tokens: Some(64_000),
thinking: ThinkingLevel::High,
..Default::default()
};
let model_info = ModelInfo::default();
let compat = AnthropicCompat::default();
let body = build_request(&req, &model_info, &compat);
assert_eq!(body["thinking"]["type"], "enabled");
assert_eq!(body["thinking"]["budget_tokens"], 16_384);
}
#[test]
fn test_build_anthropic_request_with_tools() {
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![Message::user("Hello")],
system: None,
tools: vec![luxe_core::provider::ToolSchema {
name: "bash".to_string(),
description: "Run a bash command".to_string(),
parameters: serde_json::json!({
"type": "object",
"properties": {
"command": {"type": "string"}
}
}),
}],
max_tokens: Some(100),
thinking: ThinkingLevel::Off,
..Default::default()
};
let model_info = ModelInfo::default();
let compat = AnthropicCompat::default();
let body = build_request(&req, &model_info, &compat);
assert_eq!(body["tools"].as_array().unwrap().len(), 1);
assert_eq!(body["tools"][0]["name"], "bash");
}
/// Only `write` streams its arguments: unvalidated, Claude garbles `edit`'s.
#[test]
fn only_write_asks_for_its_arguments_as_they_are_written() {
let schema = |name: &str| luxe_core::provider::ToolSchema {
name: name.into(),
description: String::new(),
parameters: serde_json::json!({"type": "object"}),
};
let req = CompletionRequest {
messages: vec![Message::user("hi")],
tools: vec![schema("write"), schema("edit"), schema("bash")],
max_tokens: Some(100),
thinking: ThinkingLevel::Off,
..Default::default()
};
let eager = |compat: &AnthropicCompat| {
let body = build_request(&req, &ModelInfo::default(), compat);
body["tools"]
.as_array()
.unwrap()
.iter()
.map(|tool| tool.get("eager_input_streaming").is_some())
.collect::<Vec<_>>()
};
assert_eq!(eager(&AnthropicCompat::default()), [true, false, false]);
let off = AnthropicCompat { stream_tool_arguments: false, ..AnthropicCompat::default() };
assert_eq!(eager(&off), [false, false, false]);
}
#[test]
fn test_serialize_messages_tool_result() {
let msg = Message::tool_result("call_123", "output", false);
let serialized = serialize_messages(&[msg], false);
assert_eq!(serialized[0]["role"], "user");
assert_eq!(serialized[0]["content"][0]["type"], "tool_result");
assert_eq!(serialized[0]["content"][0]["tool_use_id"], "call_123");
}
/// A tool result carrying pixels, as `read` on an image or `screenshot` produces.
fn tool_result_with_image(text: &str) -> Message {
Message {
role: luxe_core::message::Role::Tool,
content: vec![luxe_core::message::ContentBlock::ToolResult {
call_id: "call_1".into(),
content: vec![
luxe_core::message::ToolOutput::Text(text.into()),
luxe_core::message::ToolOutput::Image {
data: "QUJD".into(),
mime: "image/png".into(),
name: Some("quad.png".into()),
},
],
is_error: false,
}],
}
}
/// This API takes image blocks inside a `tool_result`, so the pixels ride in the result they
/// belong to — no carrier message, no restructuring.
#[test]
fn a_tool_result_image_becomes_a_content_block_for_a_vision_model() {
let serialized = serialize_messages(&[tool_result_with_image("quad.png: PNG")], true);
let result = &serialized[0]["content"][0];
assert_eq!(result["type"], "tool_result");
let parts = result["content"].as_array().expect("the block array form");
assert_eq!(parts[0]["type"], "text");
assert_eq!(parts[0]["text"], "quad.png: PNG");
assert_eq!(parts[1]["type"], "image");
assert_eq!(parts[1]["source"]["type"], "base64");
assert_eq!(parts[1]["source"]["media_type"], "image/png");
assert_eq!(parts[1]["source"]["data"], "QUJD");
}
/// The common shape is unchanged: a text-only result stays a plain string, which is what every
/// existing transcript and wire test reads. Churning it buys nothing.
#[test]
fn a_text_only_result_keeps_the_plain_string_form() {
let serialized = serialize_messages(&[Message::tool_result("call_1", "done", false)], true);
assert_eq!(serialized[0]["content"][0]["content"], "done");
// And a model with no declared vision never receives the bytes, even when they exist.
let blind = serialize_messages(&[tool_result_with_image("quad.png: PNG")], false);
assert_eq!(blind[0]["content"][0]["content"], "quad.png: PNG");
let rendered = serde_json::Value::Array(blind).to_string();
assert!(!rendered.contains("QUJD"), "no base64 reaches a text-only model: {rendered}");
}
/// The default breakpoint marker, for the tests that are about placement rather than lifetime.
fn five_minute() -> serde_json::Value {
serde_json::json!({"type": "ephemeral"})
}
/// The breakpoint ends where every session's prompt stops being the same, so a session in
/// another directory reads the harness rather than writing it, and the rest follows uncached.
#[test]
fn the_system_breakpoint_ends_the_shared_part() {
let system = "## Role\n\nshared\n\n## Environment\n\n**cwd**: `/x`";
let shared = system.find("## Environment").unwrap();
let mut body = serde_json::json!({"system": system, "messages": []});
add_cache_control_markers(&mut body, five_minute(), shared);
assert_eq!(body["system"][0]["text"], "## Role\n\nshared\n\n");
assert_eq!(body["system"][0]["cache_control"]["type"], "ephemeral");
assert_eq!(body["system"][1]["text"], "## Environment\n\n**cwd**: `/x`");
assert!(body["system"][1].get("cache_control").is_none());
// Nothing shared, or nothing after it, is one block as before
for shared in [0, system.len(), system.len() + 5] {
let mut body = serde_json::json!({"system": system, "messages": []});
add_cache_control_markers(&mut body, five_minute(), shared);
assert_eq!(body["system"].as_array().unwrap().len(), 1, "{shared}");
assert_eq!(body["system"][0]["text"], system);
}
}
#[test]
fn test_cache_control_markers_system() {
let mut body = serde_json::json!({
"system": "You are a helpful assistant.",
"messages": [],
});
add_cache_control_markers(&mut body, five_minute(), 0);
// System should be converted to array with cache_control
assert!(body["system"].is_array());
assert_eq!(body["system"][0]["cache_control"]["type"], "ephemeral");
}
#[test]
fn test_cache_control_markers_tools() {
let mut body = serde_json::json!({
"tools": [
{"name": "bash", "description": "Run bash"},
{"name": "edit", "description": "Edit files"},
],
"messages": [],
});
add_cache_control_markers(&mut body, five_minute(), 0);
// Last tool should have cache_control
assert_eq!(body["tools"][1]["cache_control"]["type"], "ephemeral");
}
#[test]
fn test_cache_control_marks_last_conversation_message() {
// The key incremental-caching breakpoint: the last message is marked so the growing
// conversation is cached, not re-sent uncached each turn. String content is normalized
// to a block; array content marks its last block.
let mut body = serde_json::json!({
"system": "sys",
"tools": [{"name": "bash", "description": "Run bash"}],
"messages": [
{"role": "user", "content": "do the thing"},
{"role": "assistant", "content": [{"type": "text", "text": "ok"}]},
{"role": "user", "content": [
{"type": "tool_result", "content": "result A"},
{"type": "tool_result", "content": "result B"},
]},
],
});
add_cache_control_markers(&mut body, five_minute(), 0);
// The last message's last block is marked, which caches everything before it — and so is
// the previous user turn, which is where the last request stopped.
let last = &body["messages"][2]["content"];
assert!(last[0].get("cache_control").is_none());
assert_eq!(last[1]["cache_control"]["type"], "ephemeral");
assert_eq!(body["messages"][0]["content"][0]["cache_control"]["type"], "ephemeral");
// The assistant turn between them is not a breakpoint.
assert!(body["messages"][1]["content"][0].get("cache_control").is_none());
}
#[test]
fn test_cache_control_normalizes_string_message_content() {
let mut body = serde_json::json!({
"messages": [{"role": "user", "content": "hello world"}],
});
add_cache_control_markers(&mut body, five_minute(), 0);
let content = &body["messages"][0]["content"];
assert!(content.is_array());
assert_eq!(content[0]["text"], "hello world");
assert_eq!(content[0]["cache_control"]["type"], "ephemeral");
}

View File

@@ -0,0 +1,172 @@
//! SSE — event decoding and usage.
use super::*;
#[test]
fn test_parse_sse_event_text_delta() {
let event_str = r#"event: content_block_delta
data: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello"}}"#;
let event = parse_sse_event(event_str).unwrap();
match event {
AnthropicSseEvent::ContentBlockDelta(delta) => {
assert_eq!(delta.delta_type, "content_block_delta");
let inner = delta.delta.unwrap();
assert_eq!(inner.inner_type, "text_delta");
assert_eq!(inner.text.unwrap(), "Hello");
}
_ => panic!("Expected ContentBlockDelta"),
}
}
#[test]
fn sse_maps_signature_delta_and_redacted_thinking() {
let text = concat!(
"event: content_block_start\n",
"data: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"thinking\",\"thinking\":\"\"}}\n\n",
"event: content_block_delta\n",
"data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"thinking_delta\",\"thinking\":\"reasoning\"}}\n\n",
"event: content_block_delta\n",
"data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"signature_delta\",\"signature\":\"SIG==\"}}\n\n",
"event: content_block_start\n",
"data: {\"type\":\"content_block_start\",\"index\":1,\"content_block\":{\"type\":\"redacted_thinking\",\"data\":\"ENC==\"}}\n\n",
);
let events = parse_anthropic_sse_text(text);
assert!(
events.iter().any(|e| matches!(e, ProviderEvent::ThinkingSignature { index: 0, signature } if signature == "SIG==")),
"signature_delta maps to ThinkingSignature: {events:?}"
);
assert!(
events.iter().any(
|e| matches!(e, ProviderEvent::RedactedThinking { index: 1, data } if data == "ENC==")
),
"redacted_thinking start maps to RedactedThinking: {events:?}"
);
}
#[test]
fn test_parse_sse_event_tool_call_start() {
let event_str = r#"event: content_block_start
data: {"type": "content_block_start", "content_block": {"type": "tool_use", "id": "toolu_123", "name": "bash"}}"#;
let event = parse_sse_event(event_str).unwrap();
match event {
AnthropicSseEvent::ContentBlockStart(block) => {
assert_eq!(block.block_type, "content_block_start");
// The id and name are in the nested content_block field
// For now, just verify we got a ContentBlockStart event
}
_ => panic!("Expected ContentBlockStart"),
}
}
#[test]
fn test_parse_sse_event_message_delta() {
let event_str = r#"event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 1}}"#;
let event = parse_sse_event(event_str).unwrap();
match event {
AnthropicSseEvent::MessageDelta(delta) => {
let stop_reason = delta
.stop_reason
.or_else(|| delta.delta.as_ref().and_then(|d| d.stop_reason.clone()));
assert_eq!(stop_reason.unwrap(), "end_turn");
}
_ => panic!("Expected MessageDelta"),
}
}
#[test]
fn test_parse_anthropic_sse_text_multiple_events() {
let text = r#"event: content_block_start
data: {"type": "content_block_start", "content_block": {"type": "text", "id": "block_1"}}
event: content_block_delta
data: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello"}}
event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 1}}"#;
let events = parse_anthropic_sse_text(text);
// Two text deltas, then a Usage event (from message_delta), then Done.
assert_eq!(events.len(), 4);
assert!(events.iter().any(|e| matches!(e, ProviderEvent::Usage(_))));
}
#[test]
fn test_anthropic_usage_normalizes_input_and_cache() {
// message_start carries input + cache; message_delta carries the final output count.
let text = concat!(
"event: message_start\n",
"data: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":500,",
"\"cache_read_input_tokens\":4000,\"cache_creation_input_tokens\":200,",
"\"output_tokens\":1}}}\n\n",
"event: message_delta\n",
"data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},",
"\"usage\":{\"output_tokens\":320}}",
);
let events = parse_anthropic_sse_text(text);
let usage = events
.iter()
.find_map(|e| match e {
ProviderEvent::Usage(u) => Some(u),
_ => None,
})
.expect("a Usage event");
// prompt_tokens is normalized to all input: 500 uncached + 4000 read + 200 write.
assert_eq!(usage.prompt_tokens, 4700);
assert_eq!(usage.cache_read_tokens, 4000);
assert_eq!(usage.cache_write_tokens, 200);
assert_eq!(usage.completion_tokens, 320);
assert_eq!(usage.total_tokens, 5020);
}
/// Writes kept for an hour are split out of the write count, because they cost 2x input rather
/// than 1.25x. The shape is Copilot's `/v1/messages` reply, copied from a live one.
#[test]
fn hour_long_cache_writes_are_counted_apart() {
let text = concat!(
"event: message_start\n",
"data: {\"type\":\"message_start\",\"message\":{\"usage\":{\"cache_creation\":",
"{\"ephemeral_1h_input_tokens\":9813,\"ephemeral_5m_input_tokens\":0},",
"\"cache_creation_input_tokens\":9813,\"cache_read_input_tokens\":0,",
"\"input_tokens\":7,\"output_tokens\":1}}}\n\n",
"event: message_delta\n",
"data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},",
"\"usage\":{\"output_tokens\":10}}",
);
let events = parse_anthropic_sse_text(text);
let usage = events
.iter()
.find_map(|e| match e {
ProviderEvent::Usage(u) => Some(u),
_ => None,
})
.expect("a Usage event");
assert_eq!((usage.cache_write_tokens, usage.cache_write_1h_tokens), (9813, 9813));
}
/// Thinking is billed inside `output_tokens` and broken out in `output_tokens_details`, the only
/// place Anthropic reports the reasoning share of a turn.
#[test]
fn anthropic_usage_carries_the_thinking_share_of_the_output() {
let text = concat!(
"event: message_start\n",
"data: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":105,",
"\"output_tokens\":1}}}\n\n",
"event: message_delta\n",
"data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},",
"\"usage\":{\"output_tokens\":4000,\"output_tokens_details\":{\"thinking_tokens\":3999}}}",
);
let events = parse_anthropic_sse_text(text);
let usage = events
.iter()
.find_map(|e| match e {
ProviderEvent::Usage(u) => Some(u),
_ => None,
})
.expect("a Usage event");
assert_eq!(usage.completion_tokens, 4_000);
assert_eq!(usage.reasoning_tokens, 3_999, "the reasoning subset of the output");
}

View File

@@ -0,0 +1,129 @@
//! SSE flows — whole streams decoded end to end.
use super::*;
#[test]
fn test_integration_streaming_conversation() {
// Simulate a complete streaming conversation with text, thinking, and tool calls
let sse_text = r#"event: content_block_start
data: {"type": "content_block_start", "content_block": {"type": "thinking", "id": "think_1"}}
event: content_block_delta
data: {"type": "content_block_delta", "delta": {"type": "thinking_delta", "thinking": "I need to"}}
event: content_block_delta
data: {"type": "content_block_delta", "delta": {"type": "thinking_delta", "thinking": "."}}
event: content_block_stop
data: {}
event: content_block_start
data: {"type": "content_block_start", "content_block": {"type": "text", "id": "block_1"}}
event: content_block_delta
data: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello"}}
event: content_block_delta
data: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": " world"}}
event: content_block_start
data: {"type": "content_block_start", "content_block": {"type": "tool_use", "id": "toolu_123", "name": "bash"}}
event: content_block_delta
data: {"type": "content_block_delta", "delta": {"type": "input_json_delta", "partial_json": "{\"command\":"}}
event: content_block_delta
data: {"type": "content_block_delta", "delta": {"type": "input_json_delta", "partial_json": ": \"ls\"}"}}
event: content_block_stop
data: {}
event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 50}}
event: message_stop
data: {}"#;
let events = parse_anthropic_sse_text(sse_text);
// Should have multiple events
assert!(events.len() >= 8);
// Verify we got thinking, text, and tool events
let has_thinking = events.iter().any(|e| matches!(e, ProviderEvent::ThinkingDelta { .. }));
let has_text = events.iter().any(|e| matches!(e, ProviderEvent::TextDelta { .. }));
let has_tool_start = events.iter().any(|e| matches!(e, ProviderEvent::ToolCallStart { .. }));
let has_tool_delta = events.iter().any(|e| matches!(e, ProviderEvent::ToolCallDelta { .. }));
let has_done = events.iter().any(|e| matches!(e, ProviderEvent::Done { .. }));
assert!(has_thinking, "Should have thinking events");
assert!(has_text, "Should have text events");
assert!(has_tool_start, "Should have tool call start");
assert!(has_tool_delta, "Should have tool call delta");
assert!(has_done, "Should have done event");
}
#[test]
fn tool_call_deltas_accumulate_at_the_blocks_own_index() {
// A realistic stream: text at index 0, then a tool call at index 1 whose two
// `input_json_delta` chunks also carry index 1. The tool args must accumulate against the
// ToolCallStart's index (regression: a per-event counter gave the deltas a different index,
// so args never assembled and every tool call arrived empty).
let sse_text = r#"event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Sure."}}
event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "tool_use", "id": "toolu_9", "name": "task"}}
event: content_block_delta
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"action\":"}}
event: content_block_delta
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": " \"list\"}"}}
event: content_block_stop
data: {"type": "content_block_stop", "index": 1}"#;
let events = parse_anthropic_sse_text(sse_text);
// The tool start and both deltas must share the SAME index.
let start_index = events.iter().find_map(|e| match e {
ProviderEvent::ToolCallStart { index, name, .. } if name == "task" => Some(*index),
_ => None,
});
assert_eq!(start_index, Some(1), "tool call keeps Anthropic's block index");
// Reproduce turn.rs accumulation: append deltas whose index matches the start.
let mut args = String::new();
for e in &events {
if let ProviderEvent::ToolCallDelta { index, json_delta } = e {
if *index == 1 {
args.push_str(json_delta);
}
}
}
assert_eq!(args, r#"{"action": "list"}"#, "tool arguments fully assembled");
let parsed: serde_json::Value = serde_json::from_str(&args).unwrap();
assert_eq!(parsed["action"], "list");
}
#[test]
fn test_parse_error_event() {
let event_str = r#"event: error
data: {"type": "error", "error": {"message": "Rate limit exceeded", "type": "rate_limit_error"}}"#;
let event = parse_sse_event(event_str).unwrap();
match event {
AnthropicSseEvent::Error(error) => {
let msg = error
.message
.or_else(|| error.error.as_ref().and_then(|e| e.message.clone()))
.unwrap();
assert_eq!(msg, "Rate limit exceeded");
}
_ => panic!("Expected Error event"),
}
}

View File

@@ -0,0 +1,451 @@
//! Streaming — the adapter against a canned server: headers, retries, refreshes.
use super::*;
/// Regression: the adapter must POST to `{base}/messages` (NOT `/messages/stream`, which
/// 404s on real Anthropic), authenticate with `x-api-key` (NOT `Authorization: Bearer`),
/// and request SSE via `stream: true` in the body. Verified against the real
/// `AnthropicProvider::stream` using a std TcpListener mock (no extra deps).
#[tokio::test]
async fn stream_posts_to_messages_with_x_api_key_and_stream_flag() {
let server = serve_once("200 OK", "text/event-stream", &sse_turn("pong"));
let port = server.port();
let model =
ModelInfo { r#ref: ModelRef::new("anthropic", "claude-sonnet-4-6"), ..Default::default() };
let provider = AnthropicProvider::new(
"test-key".into(),
Some(format!("http://127.0.0.1:{port}/v1")),
model.clone(),
AnthropicCompat::default(),
);
let (_keep, cancel) = tokio::sync::watch::channel(false);
let stream = provider
.stream(turn_request(&model, ThinkingLevel::Off), cancel)
.await
.expect("stream opens");
let events: Vec<ProviderEvent> = stream.collect().await;
let raw = server.requests().remove(0);
let request_line = raw.lines().next().unwrap_or_default();
assert!(
request_line.starts_with("POST /v1/messages "),
"must POST to /v1/messages, got: {request_line:?}"
);
assert!(!request_line.contains("/messages/stream"), "the /messages/stream path 404s");
let lower = raw.to_ascii_lowercase();
assert!(lower.contains("x-api-key: test-key"), "must authenticate with x-api-key");
assert!(!lower.contains("authorization:"), "Anthropic rejects Authorization: Bearer");
assert!(lower.contains("anthropic-version:"), "must send anthropic-version");
let body = raw.split("\r\n\r\n").nth(1).unwrap_or_default();
assert!(body.contains("\"stream\":true"), "body must request SSE: {body}");
let text: String = events
.iter()
.filter_map(|event| match event {
ProviderEvent::TextDelta { delta, .. } => Some(delta.as_str()),
_ => None,
})
.collect();
assert!(text.contains("pong"), "provider should parse the SSE text delta, got: {events:?}");
}
/// Runtime model switching: the streamed body must carry the *request's* model id, not the
/// adapter's build-time model. Without this, `Action::SetModel` couldn't change the Anthropic
/// model within one adapter.
#[tokio::test]
async fn stream_uses_the_per_request_model_id() {
let server = serve_once("200 OK", "text/event-stream", &sse_turn(""));
let port = server.port();
// Adapter built for one model; the request asks for a *different* one.
let provider = AnthropicProvider::new(
"test-key".into(),
Some(format!("http://127.0.0.1:{port}/v1")),
ModelInfo { r#ref: ModelRef::new("anthropic", "claude-sonnet-4-6"), ..Default::default() },
AnthropicCompat::default(),
);
let requested =
ModelInfo { r#ref: ModelRef::new("anthropic", "claude-opus-4-8"), ..Default::default() };
let (_keep, cancel) = tokio::sync::watch::channel(false);
let stream = provider
.stream(turn_request(&requested, ThinkingLevel::Off), cancel)
.await
.expect("stream opens");
let _events: Vec<ProviderEvent> = stream.collect().await;
let raw = server.requests().remove(0);
let body = raw.split("\r\n\r\n").nth(1).unwrap_or_default();
assert!(
body.contains("\"model\":\"claude-opus-4-8\""),
"body must carry the request's model, got: {body}"
);
assert!(
!body.contains("claude-sonnet-4-6"),
"body must not fall back to the adapter's build-time model: {body}"
);
}
/// A 400 that names the thinking mode is a mismatch we can fix, not a turn to fail: the adapter
/// flips the encoding, retries once, and remembers the answer so the next turn goes out right
/// the first time. This is the path a stale catalog lands on when a new model drops extended
/// thinking.
#[tokio::test]
async fn a_rejected_thinking_mode_is_retried_and_remembered() {
let rejection = r#"{"type":"error","error":{"type":"invalid_request_error","message":"thinking.type.enabled is not supported for this model. Use thinking.type.adaptive and output_config.effort to control thinking behavior"}}"#;
let server = serve_replies(vec![
http_reply("400 Bad Request", "application/json", rejection),
http_reply("200 OK", "text/event-stream", &sse_turn("pong")),
http_reply("200 OK", "text/event-stream", &sse_turn("pong")),
]);
let port = server.port();
// No catalog metadata at all, so the adapter opens on extended thinking — exactly the
// situation the retry exists for.
let model = ModelInfo {
r#ref: ModelRef::new("anthropic", "claude-sonnet-9"),
reasoning: true,
..Default::default()
};
let provider = AnthropicProvider::new(
"test-key".into(),
Some(format!("http://127.0.0.1:{port}/v1")),
model.clone(),
AnthropicCompat::default(),
);
for _ in 0..2 {
let (_keep, cancel) = tokio::sync::watch::channel(false);
let stream = provider
.stream(turn_request(&model, ThinkingLevel::High), cancel)
.await
.expect("the retry recovers the turn");
let events: Vec<ProviderEvent> = stream.collect().await;
assert!(
events.iter().any(|event| matches!(event, ProviderEvent::TextDelta { .. })),
"the retried turn streams: {events:?}"
);
}
let bodies = server
.requests()
.iter()
.map(|raw| raw.split("\r\n\r\n").nth(1).unwrap_or_default().to_string())
.collect::<Vec<_>>();
assert_eq!(bodies.len(), 3, "one rejected attempt, its retry, then the next turn");
assert!(bodies[0].contains("\"budget_tokens\""), "first attempt: {}", bodies[0]);
assert!(bodies[1].contains("\"adaptive\""), "retry flips to adaptive: {}", bodies[1]);
assert!(bodies[1].contains("\"effort\":\"high\""), "retry carries effort: {}", bodies[1]);
assert!(
bodies[2].contains("\"adaptive\"") && !bodies[2].contains("\"budget_tokens\""),
"the learned encoding is reused without a second rejection: {}",
bodies[2]
);
}
/// A model the catalog doesn't know goes out at the current generation's ceiling, and one that
/// can't honor it is not a failed turn: Anthropic names the real limit, the adapter retries at
/// it, and every later turn opens there without a second rejection.
#[tokio::test]
async fn a_refused_output_cap_is_retried_at_the_named_limit_and_remembered() {
// Verbatim shape from a real rejection.
let rejection = r#"{"type":"error","error":{"type":"invalid_request_error","message":"max_tokens: 128000 > 32000, which is the maximum allowed number of output tokens for claude-opus-4-1-20250805"},"request_id":"req_011CXxg3eqF8ZMvqtkKHNjKQ"}"#;
let server = serve_replies(vec![
http_reply("400 Bad Request", "application/json", rejection),
http_reply("200 OK", "text/event-stream", &sse_turn("pong")),
http_reply("200 OK", "text/event-stream", &sse_turn("pong")),
]);
let port = server.port();
let model = ModelInfo {
r#ref: ModelRef::new("foundry-anthropic", "opus-legacy-prod"),
..Default::default()
};
let provider = AnthropicProvider::new(
"test-key".into(),
Some(format!("http://127.0.0.1:{port}/v1")),
model.clone(),
AnthropicCompat::default(),
);
for _ in 0..2 {
let (_keep, cancel) = tokio::sync::watch::channel(false);
let request = CompletionRequest {
max_tokens: Some(128_000),
..turn_request(&model, ThinkingLevel::Off)
};
let stream = provider.stream(request, cancel).await.expect("the retry recovers");
let events: Vec<ProviderEvent> = stream.collect().await;
assert!(events.iter().any(|event| matches!(event, ProviderEvent::TextDelta { .. })));
}
let bodies = server
.requests()
.iter()
.map(|raw| raw.split("\r\n\r\n").nth(1).unwrap_or_default().to_string())
.collect::<Vec<_>>();
assert_eq!(bodies.len(), 3, "one refusal, its retry, then the next turn");
assert!(bodies[0].contains("\"max_tokens\":128000"), "{}", bodies[0]);
assert!(bodies[1].contains("\"max_tokens\":32000"), "retried at the limit: {}", bodies[1]);
assert!(bodies[2].contains("\"max_tokens\":32000"), "and remembered: {}", bodies[2]);
}
/// An endpoint that doesn't know in-place tool loading is told once: the adapter lists the
/// deferred tools instead, retries, and keeps listing them for that model, so a proxy that
/// lags behind Anthropic costs one wasted round trip rather than a session.
#[tokio::test]
async fn a_refusal_of_in_place_loading_falls_back_to_listing_and_is_remembered() {
use luxe_core::provider::ToolSchema;
let rejection = r#"{"type":"error","error":{"type":"invalid_request_error","message":"tools.3.defer_loading: Extra inputs are not permitted"}}"#;
let server = serve_replies(vec![
http_reply("400 Bad Request", "application/json", rejection),
http_reply("200 OK", "text/event-stream", &sse_turn("pong")),
http_reply("200 OK", "text/event-stream", &sse_turn("pong")),
]);
let port = server.port();
let model =
ModelInfo { r#ref: ModelRef::new("proxy", "claude-sonnet-5"), ..Default::default() };
let provider = AnthropicProvider::new(
"test-key".into(),
Some(format!("http://127.0.0.1:{port}/v1")),
model.clone(),
AnthropicCompat::default(),
);
let schema = |name: &str| ToolSchema {
name: name.to_string(),
description: String::new(),
parameters: serde_json::json!({"type": "object"}),
};
for _ in 0..2 {
let (_keep, cancel) = tokio::sync::watch::channel(false);
let request = CompletionRequest {
tools: vec![schema("activate_tools"), schema("read")],
deferred_tools: vec![schema("debug")],
..turn_request(&model, ThinkingLevel::Off)
};
let stream = provider.stream(request, cancel).await.expect("the retry recovers");
let events: Vec<ProviderEvent> = stream.collect().await;
assert!(events.iter().any(|event| matches!(event, ProviderEvent::TextDelta { .. })));
}
let bodies = server
.requests()
.iter()
.map(|raw| raw.split("\r\n\r\n").nth(1).unwrap_or_default().to_string())
.collect::<Vec<_>>();
assert_eq!(bodies.len(), 3, "one refusal, its retry, then the next turn");
assert!(bodies[0].contains("\"defer_loading\":true"), "{}", bodies[0]);
assert!(!bodies[1].contains("defer_loading"), "retried listed: {}", bodies[1]);
assert!(!bodies[1].contains("\"debug\""), "and the inactive tool stays out: {}", bodies[1]);
assert!(!bodies[2].contains("defer_loading"), "and remembered: {}", bodies[2]);
}
/// A refresh is the turn's own request with a one-token cap — same breakpoints, same thinking
/// encoding — because anything else would write a different cache entry instead of reading
/// the one it exists to keep. Its usage comes back so the cost is recorded like any call's.
#[tokio::test]
async fn a_cache_refresh_replays_the_request_at_one_token_and_reports_its_cost() {
let refresh = concat!(
"event: message_start\n",
"data: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":3,",
"\"cache_read_input_tokens\":180000,\"cache_creation_input_tokens\":0,",
"\"output_tokens\":1}}}\n\n",
"event: message_delta\n",
"data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"max_tokens\"},",
"\"usage\":{\"output_tokens\":1}}\n\n",
"event: message_stop\n",
"data: {\"type\":\"message_stop\"}\n",
);
let server = serve_replies(vec![
http_reply("200 OK", "text/event-stream", &sse_turn("pong")),
http_reply("200 OK", "text/event-stream", refresh),
]);
let port = server.port();
let model = ModelInfo {
r#ref: ModelRef::new("anthropic", "claude-opus-5"),
reasoning: true,
thinking_controls: ThinkingControls { effort: true, ..Default::default() },
thinking_level_map: HashMap::from([("high".to_string(), Some("high".to_string()))]),
..Default::default()
};
let provider = AnthropicProvider::new(
"test-key".into(),
Some(format!("http://127.0.0.1:{port}/v1")),
model.clone(),
AnthropicCompat::default(),
);
let request = CompletionRequest {
system: Some("You are terse.".into()),
..turn_request(&model, ThinkingLevel::High)
};
assert_eq!(
provider.prompt_cache_ttl(&request),
Some(std::time::Duration::from_secs(300)),
"adaptive thinking replays cleanly on the default five-minute tier"
);
let (_keep, cancel) = tokio::sync::watch::channel(false);
let _turn: Vec<ProviderEvent> =
provider.stream(request.clone(), cancel).await.expect("turn").collect().await;
let usage = provider.warm_cache(request).await.expect("the refresh reports usage");
assert_eq!(usage.cache_read_tokens, 180_000);
assert_eq!(usage.cache_write_tokens, 0);
assert_eq!(usage.completion_tokens, 1);
let bodies: Vec<serde_json::Value> = server
.requests()
.iter()
.map(|raw| {
serde_json::from_str(raw.split("\r\n\r\n").nth(1).unwrap_or_default())
.expect("a JSON body")
})
.collect();
let (mut turn, mut warm) = (bodies[0].clone(), bodies[1].clone());
assert_eq!(warm["max_tokens"], 1);
assert_ne!(turn["max_tokens"], 1);
turn.as_object_mut().unwrap().remove("max_tokens");
warm.as_object_mut().unwrap().remove("max_tokens");
assert_eq!(turn, warm, "nothing but the cap may differ, or the refresh writes a new entry");
}
/// A refresh that fails says why, so the warmer's log names the provider's reason rather than
/// a generic "no usage".
#[tokio::test]
async fn a_refresh_the_provider_refuses_reports_its_reason() {
let overloaded = concat!(
"event: error\n",
"data: {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",",
"\"message\":\"Overloaded\"}}\n\n",
);
let server = serve_once("200 OK", "text/event-stream", overloaded);
let port = server.port();
let model = ModelInfo::default();
let provider = AnthropicProvider::new(
"test-key".into(),
Some(format!("http://127.0.0.1:{port}/v1")),
model.clone(),
AnthropicCompat::default(),
);
let error = provider
.warm_cache(turn_request(&model, ThinkingLevel::Off))
.await
.expect_err("an error event fails the refresh");
assert!(error.to_string().contains("Overloaded"), "{error}");
server.requests();
}
/// A refresh returns at the end of the reply, not at the end of the connection. A server or
/// proxy that holds the socket open after `message_stop` would otherwise keep the refresh
/// waiting until the warmer gave up on it.
#[tokio::test]
async fn a_refresh_returns_when_the_reply_ends_even_if_the_connection_does_not() {
// No length and no close: the body ends only when the socket does
let (server, release) = serve_held_open(concat!(
"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\r\n",
"event: message_start\n",
"data: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":2,",
"\"cache_read_input_tokens\":9000,\"output_tokens\":1}}}\n\n",
"event: message_delta\n",
"data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"max_tokens\"},",
"\"usage\":{\"output_tokens\":1}}\n\n",
"event: message_stop\n",
"data: {\"type\":\"message_stop\"}\n\n",
));
let port = server.port();
let model = ModelInfo::default();
let provider = AnthropicProvider::new(
"test-key".into(),
Some(format!("http://127.0.0.1:{port}/v1")),
model.clone(),
AnthropicCompat::default(),
);
let usage = tokio::time::timeout(
std::time::Duration::from_secs(5),
provider.warm_cache(turn_request(&model, ThinkingLevel::Off)),
)
.await
.expect("the refresh returns without waiting for the socket")
.expect("usage");
assert_eq!(usage.cache_read_tokens, 9_000);
let _ = release.send(());
server.requests();
}
/// Which requests can be kept warm at all.
#[test]
fn only_a_request_that_replays_byte_for_byte_is_offered_for_warming() {
use luxe_core::provider::{ModelRef, PromptReuse};
let adapter = |compat| AnthropicProvider::new("k".into(), None, ModelInfo::default(), compat);
let budgeted = ModelInfo {
r#ref: ModelRef::new("anthropic", "claude-sonnet-4-5"),
reasoning: true,
thinking_controls: ThinkingControls { budget_tokens: true, ..Default::default() },
..Default::default()
};
let five = Some(std::time::Duration::from_secs(300));
let default = adapter(AnthropicCompat::default());
assert_eq!(
default.prompt_cache_ttl(&turn_request(&budgeted, ThinkingLevel::High)),
None,
"the budget follows max_tokens and keys the message cache, so a replay can't match"
);
assert_eq!(
default.prompt_cache_ttl(&turn_request(&budgeted, ThinkingLevel::Off)),
five,
"with thinking off there is no budget to move"
);
let one_off = CompletionRequest {
reuse: PromptReuse::OneOff,
..turn_request(&budgeted, ThinkingLevel::Off)
};
assert_eq!(default.prompt_cache_ttl(&one_off), None, "nothing cached, nothing to keep");
assert_eq!(
adapter(AnthropicCompat { cache_control: false, ..AnthropicCompat::default() })
.prompt_cache_ttl(&turn_request(&budgeted, ThinkingLevel::Off)),
None
);
assert_eq!(
adapter(AnthropicCompat { long_cache_retention: true, ..AnthropicCompat::default() })
.prompt_cache_ttl(&turn_request(&budgeted, ThinkingLevel::Off)),
Some(std::time::Duration::from_secs(3600)),
"the hour-long tier refreshes on its own clock"
);
// The request's own model decides, as it does for `stream`; the adapter's build-time one
// stands in only for the `unknown` placeholder
let adaptive = ModelInfo {
r#ref: ModelRef::new("anthropic", "claude-opus-5"),
reasoning: true,
thinking_controls: ThinkingControls { effort: true, ..Default::default() },
..Default::default()
};
let built_adaptive =
AnthropicProvider::new("k".into(), None, adaptive.clone(), AnthropicCompat::default());
assert_eq!(
built_adaptive.prompt_cache_ttl(&turn_request(&budgeted, ThinkingLevel::High)),
None,
"a switch to a budgeted model is judged as that model"
);
assert_eq!(
built_adaptive.prompt_cache_ttl(&turn_request(&ModelInfo::default(), ThinkingLevel::High)),
five,
"the placeholder falls back to the adapter's adaptive model"
);
}
#[test]
fn the_output_limit_is_read_only_out_of_the_rejection_that_names_it() {
assert_eq!(
max_tokens_limit(
"max_tokens: 100001 > 64000, which is the maximum allowed number of output tokens \
for claude-sonnet-4-5-20250929"
),
Some(64_000)
);
// Another 400 that happens to mention max_tokens teaches nothing.
assert_eq!(max_tokens_limit("max_tokens: must be greater than thinking.budget_tokens"), None);
assert_eq!(max_tokens_limit("prompt is too long: 210000 tokens > 200000 maximum"), None);
assert_eq!(
max_tokens_limit("max_tokens: 5 > 0, which is the maximum allowed number of output tokens"),
None,
"a zero limit is nothing to retry at"
);
}

View File

@@ -0,0 +1,42 @@
//! Support — the request builder and the canned turn the adapter tests share.
use super::*;
/// Builds a body the way the adapter does: the thinking encoding follows from the model's own
/// declared controls, so a test only has to describe the model.
pub(super) fn build_request(
req: &CompletionRequest,
model: &ModelInfo,
compat: &AnthropicCompat,
) -> serde_json::Value {
build_anthropic_request(
req,
model,
compat,
ThinkingPlan::for_model(model, compat),
ToolLoading::InPlace,
)
}
/// A minimal SSE turn that streams `text` and stops.
pub(super) fn sse_turn(text: &str) -> String {
format!(
"event: content_block_delta\n\
data: {{\"type\": \"content_block_delta\", \"delta\": {{\"type\": \"text_delta\", \"text\": \"{text}\"}}}}\n\n\
event: message_stop\n\
data: {{\"type\": \"message_stop\"}}\n"
)
}
/// A request against `model`, at `thinking`.
pub(super) fn turn_request(model: &ModelInfo, thinking: ThinkingLevel) -> CompletionRequest {
CompletionRequest {
model: model.clone(),
messages: vec![Message::user("ping")],
system: None,
tools: Vec::new(),
thinking,
max_tokens: Some(20_000),
..Default::default()
}
}

View File

@@ -0,0 +1,280 @@
//! Thinking — which thinking encoding each model gets, and how a rejection revises it.
use super::*;
#[test]
fn test_adaptive_thinking_mode() {
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![Message::user("Hello")],
system: None,
tools: vec![],
max_tokens: Some(4000),
thinking: ThinkingLevel::High,
..Default::default()
};
let model_info = ModelInfo::default();
let mut compat = AnthropicCompat::default();
compat.force_adaptive_thinking = true;
let body = build_request(&req, &model_info, &compat);
assert_eq!(body["thinking"]["type"], "adaptive");
assert_eq!(body["output_config"]["effort"], "high");
assert!(body["thinking"].get("budget_tokens").is_none());
}
/// The reported failure: Claude Sonnet 5 / Opus 5 advertise effort levels and nothing else, and
/// reject `thinking.type: "enabled"` outright. The declared controls alone must pick adaptive —
/// no compat flag, no hand-written config.
#[test]
fn an_effort_only_model_is_steered_with_adaptive_thinking_and_effort() {
let model = ModelInfo {
reasoning: true,
thinking_controls: ThinkingControls { effort: true, ..Default::default() },
thinking_level_map: HashMap::from([
("minimal".to_string(), None),
("low".to_string(), Some("low".to_string())),
("medium".to_string(), Some("medium".to_string())),
("high".to_string(), Some("high".to_string())),
("xhigh".to_string(), Some("xhigh".to_string())),
("ultra".to_string(), Some("max".to_string())),
]),
..Default::default()
};
let compat = AnthropicCompat::default();
let xhigh = build_request(&turn_request(&model, ThinkingLevel::XHigh), &model, &compat);
assert_eq!(xhigh["thinking"]["type"], "adaptive");
assert_eq!(xhigh["output_config"]["effort"], "xhigh");
assert!(xhigh["thinking"].get("budget_tokens").is_none(), "extended thinking would 400");
// Luxe shows reasoning in the transcript, and these models omit the text by default.
assert_eq!(xhigh["thinking"]["display"], "summarized");
// A level the model doesn't offer clamps to one it does rather than inventing an effort.
let minimal = build_request(&turn_request(&model, ThinkingLevel::Minimal), &model, &compat);
assert_eq!(minimal["output_config"]["effort"], "low");
// Off keeps its own switch and sends no effort, which also stays clear of the newer rule
// rejecting a disabled block at xhigh/max effort.
let off = build_request(&turn_request(&model, ThinkingLevel::Off), &model, &compat);
assert_eq!(off["thinking"]["type"], "disabled");
assert!(off.get("output_config").is_none());
}
/// A model that still advertises a token budget keeps extended thinking: the catalog can't tell
/// an extended-only model that happens to support effort (Opus 4.5, which rejects adaptive) from
/// one that takes both, so the mode that works for every such model wins.
#[test]
fn a_model_offering_a_token_budget_keeps_extended_thinking() {
let model = ModelInfo {
reasoning: true,
thinking_controls: ThinkingControls {
effort: true,
budget_tokens: true,
..Default::default()
},
thinking_level_map: HashMap::from([("high".to_string(), Some("high".to_string()))]),
..Default::default()
};
let request =
CompletionRequest { max_tokens: Some(64_000), ..turn_request(&model, ThinkingLevel::High) };
let body = build_request(&request, &model, &<_>::default());
assert_eq!(body["thinking"]["type"], "enabled");
assert_eq!(body["thinking"]["budget_tokens"], 16_384);
assert!(body.get("output_config").is_none());
}
/// Only a thinking-mode rejection is worth a retry, and each rejection teaches exactly one
/// thing: an always-on model loses `disabled`, an adaptive-only model loses `enabled`.
#[test]
fn a_revised_plan_answers_the_rejection_it_was_given() {
let extended =
ThinkingPlan { mode: ThinkingMode::Extended, can_disable: true, between_tools: false };
let adaptive =
ThinkingPlan { mode: ThinkingMode::Adaptive, can_disable: true, between_tools: false };
let dropped_extended = "thinking.type.enabled is not supported for this model. Use \
thinking.type.adaptive and output_config.effort to control thinking behavior";
assert_eq!(
extended.revised(dropped_extended),
Some(ThinkingPlan {
mode: ThinkingMode::Adaptive,
can_disable: true,
between_tools: false
})
);
assert_eq!(
adaptive.revised("thinking.type.adaptive is not supported for this model"),
Some(ThinkingPlan {
mode: ThinkingMode::Extended,
can_disable: true,
between_tools: false
})
);
assert_eq!(
adaptive.revised("thinking.type.disabled is not supported for this model"),
Some(ThinkingPlan {
mode: ThinkingMode::Adaptive,
can_disable: false,
between_tools: false
}),
"an always-on model keeps its mode and stops being told to stop thinking"
);
let named = r#"To turn thinking off on this model, send "thinking": {"type": "between_tools"} instead of {"type": "disabled"}."#;
assert_eq!(
adaptive.revised(named),
Some(ThinkingPlan {
mode: ThinkingMode::Adaptive,
can_disable: false,
between_tools: true
}),
"a model that names its own off switch gets it"
);
let learned = adaptive.revised(named).expect("learned");
let model = ModelInfo { reasoning: true, ..Default::default() };
let body = build_anthropic_request(
&turn_request(&model, ThinkingLevel::Off),
&model,
&<_>::default(),
learned,
ToolLoading::InPlace,
);
assert_eq!(body["thinking"], serde_json::json!({"type": "between_tools"}));
assert_eq!(learned.revised(named), None, "and keeps it");
// Anything else is a real error the user needs to see.
assert_eq!(extended.revised("max_tokens: must be greater than thinking.budget_tokens"), None);
assert_eq!(
extended.revised(dropped_extended).and_then(|plan| plan.revised(dropped_extended)),
None,
"one flip only"
);
}
/// With `disabled` off the table, "thinking off" sends no thinking parameter at all — Anthropic's
/// own remedy for the always-on models.
#[test]
fn an_always_on_model_omits_the_thinking_parameter_instead_of_disabling() {
let model = ModelInfo { reasoning: true, ..Default::default() };
let plan =
ThinkingPlan { mode: ThinkingMode::Adaptive, can_disable: false, between_tools: false };
let body = build_anthropic_request(
&turn_request(&model, ThinkingLevel::Off),
&model,
&<_>::default(),
plan,
ToolLoading::InPlace,
);
assert!(body.get("thinking").is_none(), "no thinking block at all: {body}");
assert!(body.get("output_config").is_none());
}
#[test]
fn test_adaptive_ultra_and_unsupported_off_mapping() {
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![Message::user("Hello")],
system: None,
tools: vec![],
max_tokens: Some(16_000),
thinking: ThinkingLevel::Ultra,
..Default::default()
};
let mut model_info = ModelInfo {
reasoning: true,
thinking_level_map: std::collections::HashMap::from([
("off".to_string(), None),
("minimal".to_string(), None),
("low".to_string(), None),
("medium".to_string(), None),
("high".to_string(), Some("high".to_string())),
]),
..Default::default()
};
let compat = AnthropicCompat { force_adaptive_thinking: true, ..Default::default() };
let ultra = build_request(&req, &model_info, &compat);
assert_eq!(ultra["thinking"]["type"], "adaptive");
assert_eq!(ultra["output_config"]["effort"], "max");
model_info.thinking_level_map.insert("ultra".to_string(), None);
let off_request = CompletionRequest { thinking: ThinkingLevel::Off, ..req };
let clamped = build_request(&off_request, &model_info, &compat);
assert_eq!(clamped["thinking"]["type"], "adaptive");
assert_eq!(clamped["output_config"]["effort"], "high");
}
#[test]
fn test_serialize_thinking_block() {
let msg = Message {
role: luxe_core::message::Role::Assistant,
content: vec![luxe_core::message::ContentBlock::Thinking {
text: "Let me think...".to_string(),
signature: Some("sig123".to_string()),
id: None,
encrypted: None,
opaque: None,
}],
};
let serialized = serialize_content_blocks(&msg.content);
assert_eq!(serialized[0]["type"], "thinking");
assert_eq!(serialized[0]["thinking"], "Let me think...");
assert_eq!(serialized[0]["signature"], "sig123");
}
#[test]
fn thinking_without_signature_is_dropped_from_replay() {
// A signature-less reasoning block can't be replayed safely (Anthropic 400s on an
// invalid/empty signature), so it's omitted entirely — this also skips reasoning that
// originated from another provider before a mid-session model switch.
let content = vec![
luxe_core::message::ContentBlock::Thinking {
text: "unsigned".to_string(),
signature: None,
id: None,
encrypted: None,
opaque: None,
},
luxe_core::message::ContentBlock::Text("answer".to_string()),
];
let serialized = serialize_content_blocks(&content);
assert_eq!(serialized.len(), 1, "the unsigned thinking block is dropped");
assert_eq!(serialized[0]["type"], "text");
}
/// The block this adapter drops can be the only one a message had. What is left is an empty
/// `content`, which the API rejects — and since the message is history, it rejects every
/// later request too, so the drop has to take the message with it.
#[test]
fn a_turn_left_with_no_blocks_is_dropped_rather_than_sent_empty() {
let messages = vec![
Message::user("go"),
Message {
role: luxe_core::message::Role::Assistant,
content: vec![luxe_core::message::ContentBlock::Thinking {
text: "reasoning from another provider".to_string(),
signature: None,
id: Some("rs_1".to_string()),
encrypted: Some("opaque".to_string()),
opaque: None,
}],
},
Message::user("carry on"),
];
let serialized = serialize_messages(&messages, false);
assert_eq!(serialized.len(), 1, "the emptied turn is gone and the two users merge");
let content = serialized[0]["content"].as_array().expect("content array");
assert_eq!(content.len(), 2);
assert!(content.iter().all(|block| block["text"].as_str().is_some_and(|t| !t.is_empty())));
}
#[test]
fn redacted_thinking_round_trips_verbatim() {
let content = vec![luxe_core::message::ContentBlock::RedactedThinking {
data: "ENCRYPTED==".to_string(),
}];
let serialized = serialize_content_blocks(&content);
assert_eq!(serialized[0]["type"], "redacted_thinking");
assert_eq!(serialized[0]["data"], "ENCRYPTED==");
}

View File

@@ -0,0 +1,576 @@
//! Wire — the error map, thinking levels, cache control and message serialization.
use super::*;
#[test]
fn test_map_error_to_provider_event() {
let error = AnthropicError {
message: None,
error: Some(AnthropicErrorInner {
message: Some("Authentication failed".into()),
r#type: None,
}),
};
match map_anthropic_event(AnthropicSseEvent::Error(error)) {
Some(ProviderEvent::Error { message, .. }) => assert_eq!(message, "Authentication failed"),
_ => panic!("Expected Error event"),
}
}
#[test]
fn test_thinking_level_mapping() {
use luxe_core::provider::ThinkingLevel;
// Test Off level
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![Message::user("Hello")],
system: None,
tools: vec![],
max_tokens: Some(100),
thinking: ThinkingLevel::Off,
..Default::default()
};
let model_info = ModelInfo::default();
let compat = AnthropicCompat::default();
let body = build_request(&req, &model_info, &compat);
assert_eq!(body["thinking"]["type"], "disabled");
// Test Minimal level
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![Message::user("Hello")],
system: None,
tools: vec![],
max_tokens: Some(100),
thinking: ThinkingLevel::Minimal,
..Default::default()
};
let body = build_request(&req, &model_info, &compat);
assert!(body.get("thinking").is_some());
assert_eq!(body["thinking"]["type"], "enabled");
// Test Low level
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![Message::user("Hello")],
system: None,
tools: vec![],
max_tokens: Some(100),
thinking: ThinkingLevel::Low,
..Default::default()
};
let body = build_request(&req, &model_info, &compat);
assert_eq!(body["thinking"]["type"], "enabled");
// Test Medium level
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![Message::user("Hello")],
system: None,
tools: vec![],
max_tokens: Some(100),
thinking: ThinkingLevel::Medium,
..Default::default()
};
let body = build_request(&req, &model_info, &compat);
assert_eq!(body["thinking"]["type"], "enabled");
// Test High level
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![Message::user("Hello")],
system: None,
tools: vec![],
max_tokens: Some(100),
thinking: ThinkingLevel::High,
..Default::default()
};
let body = build_request(&req, &model_info, &compat);
assert_eq!(body["thinking"]["type"], "enabled");
// Top-end levels fall back to the highest standard budget unless a model maps them.
for thinking in [ThinkingLevel::XHigh, ThinkingLevel::Ultra] {
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![Message::user("Hello")],
system: None,
tools: vec![],
max_tokens: Some(64_000),
thinking,
..Default::default()
};
let body = build_request(&req, &model_info, &compat);
assert_eq!(body["thinking"]["type"], "enabled");
assert_eq!(body["thinking"]["budget_tokens"], 16_384);
}
}
#[test]
fn test_system_prompt_cache_control() {
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![
Message {
role: luxe_core::message::Role::System,
content: vec![luxe_core::message::ContentBlock::Text(
"You are a helpful assistant".to_string(),
)],
},
Message::user("Hello"),
],
system: None,
tools: vec![],
max_tokens: Some(100),
thinking: ThinkingLevel::Off,
..Default::default()
};
let model_info = ModelInfo::default();
let compat = AnthropicCompat::default();
let body = build_request(&req, &model_info, &compat);
// System prompt should be an array with cache_control marker
assert!(body["system"].is_array(), "System should be an array, got: {:?}", body["system"]);
assert_eq!(body["system"][0]["type"], "text");
assert_eq!(body["system"][0]["cache_control"]["type"], "ephemeral");
}
#[test]
fn test_tool_cache_control() {
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![Message::user("Hello")],
system: None,
tools: vec![luxe_core::provider::ToolSchema {
name: "bash".to_string(),
description: "Run a bash command".to_string(),
parameters: serde_json::json!({
"type": "object",
"properties": {
"command": {"type": "string"}
}
}),
}],
max_tokens: Some(100),
thinking: ThinkingLevel::Off,
..Default::default()
};
let model_info = ModelInfo::default();
let compat = AnthropicCompat::default();
let body = build_request(&req, &model_info, &compat);
// Tools should have cache_control on the last tool
assert!(body["tools"].is_array());
let tools = body["tools"].as_array().unwrap();
assert_eq!(tools.len(), 1);
// Last tool should have cache_control
assert_eq!(tools[0]["cache_control"]["type"], "ephemeral");
}
#[test]
fn test_empty_thinking_signature_allowed() {
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![Message::assistant("Let me think...")],
system: None,
tools: vec![],
max_tokens: Some(100),
thinking: ThinkingLevel::High,
..Default::default()
};
let model_info = ModelInfo::default();
let compat = AnthropicCompat::default();
let body = build_request(&req, &model_info, &compat);
// Should succeed even with empty thinking signature
assert!(body["thinking"].is_object());
}
#[test]
fn test_multiple_tool_calls() {
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![Message::assistant("I'll help with that")],
system: None,
tools: vec![
luxe_core::provider::ToolSchema {
name: "bash".to_string(),
description: "Run a bash command".to_string(),
parameters: serde_json::json!({
"type": "object",
"properties": {
"command": {"type": "string"}
}
}),
},
luxe_core::provider::ToolSchema {
name: "read_file".to_string(),
description: "Read a file".to_string(),
parameters: serde_json::json!({
"type": "object",
"properties": {
"path": {"type": "string"}
}
}),
},
],
max_tokens: Some(100),
thinking: ThinkingLevel::Off,
..Default::default()
};
let model_info = ModelInfo::default();
let compat = AnthropicCompat::default();
let body = build_request(&req, &model_info, &compat);
// Both tools should be present
let tools = body["tools"].as_array().unwrap();
assert_eq!(tools.len(), 2);
// Last tool should have cache_control
assert_eq!(tools[1]["cache_control"]["type"], "ephemeral");
// First tool should not have cache_control
assert!(!tools[0].get("cache_control").is_some());
}
#[test]
fn test_tool_result_with_text() {
let msg = Message::tool_result("call_123", "Command executed successfully", false);
let serialized = serialize_messages(&[msg], false);
assert_eq!(serialized.len(), 1);
assert_eq!(serialized[0]["role"], "user");
// Tool results are serialized as an array with tool_result object
assert!(serialized[0]["content"].is_array());
let content = serialized[0]["content"].as_array().unwrap();
assert_eq!(content.len(), 1);
assert_eq!(content[0]["type"], "tool_result");
assert_eq!(content[0]["tool_use_id"], "call_123");
assert_eq!(content[0]["content"], "Command executed successfully");
assert_eq!(content[0]["is_error"], false);
}
#[test]
fn test_tool_result_with_error() {
let msg = Message::tool_result("call_456", "Error: command failed", true);
let serialized = serialize_messages(&[msg], false);
assert_eq!(serialized.len(), 1);
let content = serialized[0]["content"].as_array().unwrap();
assert_eq!(content[0]["is_error"], true);
assert_eq!(content[0]["content"], "Error: command failed");
}
#[test]
fn test_cache_control_with_tools_and_system() {
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![
Message {
role: luxe_core::message::Role::System,
content: vec![luxe_core::message::ContentBlock::Text(
"You are a helpful assistant".to_string(),
)],
},
Message::user("Hello"),
],
system: None,
tools: vec![luxe_core::provider::ToolSchema {
name: "bash".to_string(),
description: "Run a bash command".to_string(),
parameters: serde_json::json!({"type": "object", "properties": {}}),
}],
max_tokens: Some(100),
thinking: ThinkingLevel::Off,
..Default::default()
};
let model_info = ModelInfo::default();
let compat = AnthropicCompat::default();
let body = build_request(&req, &model_info, &compat);
// System should have cache_control
assert!(body["system"].is_array());
assert_eq!(body["system"][0]["cache_control"]["type"], "ephemeral");
// Last tool should have cache_control
let tools = body["tools"].as_array().unwrap();
assert_eq!(tools.len(), 1);
assert_eq!(tools[0]["cache_control"]["type"], "ephemeral");
}
#[test]
fn test_thinking_block_with_signature() {
let msg = Message {
role: luxe_core::message::Role::Assistant,
content: vec![luxe_core::message::ContentBlock::Thinking {
text: "Let me think about this...".to_string(),
signature: Some("sig123".to_string()),
id: None,
encrypted: None,
opaque: None,
}],
};
let serialized = serialize_messages(&[msg], false);
assert_eq!(serialized.len(), 1);
let content = serialized[0]["content"].as_array().unwrap();
assert_eq!(content[0]["type"], "thinking");
assert_eq!(content[0]["thinking"], "Let me think about this...");
assert_eq!(content[0]["signature"], "sig123");
}
#[test]
fn test_thinking_block_without_signature_is_dropped() {
// A signature-less reasoning block can't round-trip to Anthropic (it would 400 on an
// invalid/empty signature), so it's dropped; the rest of the message survives.
let msg = Message {
role: luxe_core::message::Role::Assistant,
content: vec![
luxe_core::message::ContentBlock::Thinking {
text: "Let me think about this...".to_string(),
signature: None,
id: None,
encrypted: None,
opaque: None,
},
luxe_core::message::ContentBlock::Text("the answer".to_string()),
],
};
let serialized = serialize_messages(&[msg], false);
assert_eq!(serialized.len(), 1);
let content = serialized[0]["content"].as_array().unwrap();
assert_eq!(content.len(), 1, "the unsigned thinking block is omitted");
assert_eq!(content[0]["type"], "text");
assert_eq!(content[0]["text"], "the answer");
}
#[test]
fn test_tool_call_serialization() {
let msg = Message {
role: luxe_core::message::Role::Assistant,
content: vec![luxe_core::message::ContentBlock::ToolCall {
id: "call_abc".to_string(),
name: "bash".to_string(),
arguments: serde_json::json!({"command": "ls -la"}),
}],
};
let serialized = serialize_messages(&[msg], false);
assert_eq!(serialized.len(), 1);
let content = serialized[0]["content"].as_array().unwrap();
assert_eq!(content[0]["type"], "tool_use");
assert_eq!(content[0]["id"], "call_abc");
assert_eq!(content[0]["name"], "bash");
assert_eq!(content[0]["input"]["command"], "ls -la");
}
#[test]
fn test_mixed_content_blocks() {
let msg = Message {
role: luxe_core::message::Role::Assistant,
content: vec![
luxe_core::message::ContentBlock::Thinking {
text: "Let me think...".to_string(),
signature: Some("sig1".to_string()),
id: None,
encrypted: None,
opaque: None,
},
luxe_core::message::ContentBlock::Text("I'll help you.".to_string()),
],
};
let serialized = serialize_messages(&[msg], false);
assert_eq!(serialized.len(), 1);
let content = serialized[0]["content"].as_array().unwrap();
assert_eq!(content.len(), 2);
// First block should be thinking
assert_eq!(content[0]["type"], "thinking");
assert_eq!(content[0]["thinking"], "Let me think...");
// Second block should be text
assert_eq!(content[1]["type"], "text");
assert_eq!(content[1]["text"], "I'll help you.");
}
#[test]
fn test_anthropic_compat_default() {
let compat = AnthropicCompat::default();
assert!(!compat.force_adaptive_thinking);
assert!(compat.cache_control, "prompt caching is on unless a config turns it off");
}
/// A model's own flags decide how *its* requests are shaped, on the adapter every Claude shares.
///
/// The two this API has an opinion about: how thinking is asked for, and whether cache markers
/// go out. Both used to be fixed when the adapter was built, so a model whose generation
/// disagreed with its siblings could only be corrected by changing the provider — for all of
/// them. The projection is per request now, and reads through the same two-field conversion the
/// build-time path uses, so neither can drift.
#[test]
fn a_models_compat_shapes_its_own_request_on_a_shared_adapter() {
let provider = AnthropicProvider::new(
crate::config::ApiKey::default(),
None,
ModelInfo::default(),
AnthropicCompat::default(),
);
let with_flags = |flags: luxe_core::provider::CompatFlags| ModelInfo {
r#ref: luxe_core::provider::ModelRef::new("anthropic", "claude-x"),
reasoning: true,
compat: Some(flags),
..Default::default()
};
// Adaptive thinking forced for this model alone.
let adaptive = with_flags(luxe_core::provider::CompatFlags {
force_adaptive_thinking: true,
cache_control_format: Some("anthropic".into()),
..Default::default()
});
let compat = provider.compat_for(&adaptive);
assert!(compat.force_adaptive_thinking);
assert!(compat.cache_control);
let body = build_request(&turn_request(&adaptive, ThinkingLevel::High), &adaptive, &compat);
assert_eq!(body["thinking"]["type"], "adaptive");
assert_eq!(body["output_config"]["effort"], "high");
assert!(body["messages"][0]["content"][0].get("cache_control").is_some());
// Prompt caching refused for this one — a `null` format is how that is said.
let uncached = with_flags(luxe_core::provider::CompatFlags::default());
let compat = provider.compat_for(&uncached);
assert!(!compat.cache_control);
assert!(!compat.force_adaptive_thinking);
let body = build_request(&turn_request(&uncached, ThinkingLevel::High), &uncached, &compat);
assert!(body["messages"][0].get("cache_control").is_none());
assert!(body["messages"][0]["content"][0].get("cache_control").is_none());
// And a model with nothing of its own keeps the adapter's flags, caching included.
let plain = ModelInfo { reasoning: true, ..Default::default() };
assert_eq!(provider.compat_for(&plain), AnthropicCompat::default());
}
#[test]
fn test_multi_turn_conversation() {
let messages = vec![
Message::user("Hello"),
Message::assistant("Hi there!"),
Message::user("How are you?"),
];
let serialized = serialize_messages(&messages, false);
assert_eq!(serialized.len(), 3);
assert_eq!(serialized[0]["role"], "user");
assert_eq!(serialized[0]["content"][0]["text"], "Hello");
assert_eq!(serialized[1]["role"], "assistant");
assert_eq!(serialized[1]["content"][0]["text"], "Hi there!");
assert_eq!(serialized[2]["role"], "user");
assert_eq!(serialized[2]["content"][0]["text"], "How are you?");
}
#[test]
fn test_full_request_building() {
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![
Message {
role: luxe_core::message::Role::System,
content: vec![luxe_core::message::ContentBlock::Text(
"You are helpful".to_string(),
)],
},
Message::user("Hello"),
],
system: None,
tools: vec![luxe_core::provider::ToolSchema {
name: "bash".to_string(),
description: "Run bash".to_string(),
parameters: serde_json::json!({"type": "object", "properties": {}}),
}],
max_tokens: Some(2000),
thinking: ThinkingLevel::High,
..Default::default()
};
let model_info = ModelInfo::default();
let compat = AnthropicCompat::default();
let body = build_request(&req, &model_info, &compat);
// Should have all fields
assert_eq!(body["max_tokens"], 2000);
assert!(body["thinking"].is_object());
assert!(body["tools"].is_array());
assert!(body["system"].is_array());
assert!(body["messages"].is_array());
}
#[test]
fn test_sse_parse_tool_call_events() {
let sse_text = r#"event: content_block_start
data: {"type": "content_block_start", "content_block": {"type": "tool_use", "id": "toolu_123", "name": "bash"}}
event: content_block_delta
data: {"type": "content_block_delta", "delta": {"type": "input_json_delta", "partial_json": "{\"command\":"}}
event: content_block_delta
data: {"type": "content_block_delta", "delta": {"type": "input_json_delta", "partial_json": ": \"ls\"}"}}
event: content_block_stop
data: {}
event: message_stop
data: {}"#;
let events = parse_anthropic_sse_text(sse_text);
// Should have multiple events
assert!(events.len() >= 4);
// Verify we got tool call events
let has_tool_start = events.iter().any(|e| matches!(e, ProviderEvent::ToolCallStart { .. }));
let has_tool_delta = events.iter().any(|e| matches!(e, ProviderEvent::ToolCallDelta { .. }));
let has_done = events.iter().any(|e| matches!(e, ProviderEvent::Done { .. }));
assert!(has_tool_start, "Should have tool call start");
assert!(has_tool_delta, "Should have tool call delta");
assert!(has_done, "Should have done event");
}
#[test]
fn test_adaptive_thinking_effort() {
let req = CompletionRequest {
model: ModelInfo::default(),
messages: vec![Message::user("Hello")],
system: None,
tools: vec![],
max_tokens: Some(4000),
thinking: ThinkingLevel::High,
..Default::default()
};
let model_info = ModelInfo::default();
let mut compat = AnthropicCompat::default();
compat.force_adaptive_thinking = true;
let body = build_request(&req, &model_info, &compat);
assert_eq!(body["thinking"]["type"], "adaptive");
assert_eq!(body["output_config"]["effort"], "high");
assert!(body["thinking"].get("budget_tokens").is_none());
}

View File

@@ -0,0 +1,67 @@
//! Auth — credential storage, the provider catalog, OAuth flows, and per-request auth.
//!
//! `luxe_core::auth` defines what a front-end sees; this module is the machinery behind it. The
//! split exists because signing in needs the network and the filesystem, and neither the core nor
//! the UI crates may have those dependencies.
//!
//! - `store` — the `0600`, never-lossy `auth.json`.
//! - [`credential`] — one entry's typed contents.
//! - [`deployments`] — asking an Azure resource what it has actually deployed.
//! - [`config_file`] — the surgical `models.json` writes a login makes (endpoints, defaults).
//! - [`json_file`] — lossless, locked, atomic read-modify-write shared by both files (from
//! `luxe_core`, which the MCP token store uses too).
//! - [`catalog`] — the curated providers a user can configure, and how each is reached.
//! - `source` — per-request auth: resolve a credential, refresh an expiring token once under a
//! lock, and hand the adapter the headers (and sometimes the base URL) for this one call.
//! - [`oauth`] — PKCE, the loopback callback, device-code polling, and the subscription flows.
//! - `service` — the [`luxe_core::auth::AuthService`] the front-ends drive.
pub mod catalog;
pub mod config_file;
pub mod credential;
pub mod deployments;
pub use luxe_core::json_file;
pub mod oauth;
mod service;
mod source;
mod store;
pub use catalog::{
canonical_id, provider_descriptor, provider_descriptors, wire_api_compat_floor,
ProviderDescriptor, ServedModels,
};
pub use config_file::ConfigFile;
pub use credential::{ApiKeyCredential, Credential, OAuthCredential};
pub use service::ProviderAuth;
pub use source::{AuthSource, KeyStyle, RequestAuth, StaticAuth, StoreAuth};
pub use store::{AuthStore, StoreError};
use std::path::PathBuf;
/// Luxe's config directory, where the credential store and `models.json` live. See
/// [`luxe_core::user_dirs::luxe_config_dir`], the one owner.
pub fn config_dir() -> PathBuf {
luxe_core::user_dirs::luxe_config_dir()
}
#[cfg(test)]
mod tests {
use super::*;
/// The store and the config loader must agree on where config lives; a mismatch would present as
/// "I logged in and it didn't take".
#[test]
fn the_config_dir_follows_xdg() {
let previous = std::env::var_os("XDG_CONFIG_HOME");
std::env::set_var("XDG_CONFIG_HOME", "/tmp/luxe-xdg-test");
assert_eq!(config_dir(), PathBuf::from("/tmp/luxe-xdg-test/luxe"));
assert_eq!(
AuthStore::default_path().path(),
PathBuf::from("/tmp/luxe-xdg-test/luxe/auth.json")
);
match previous {
Some(value) => std::env::set_var("XDG_CONFIG_HOME", value),
None => std::env::remove_var("XDG_CONFIG_HOME"),
}
}
}

View File

@@ -0,0 +1,345 @@
//! Provider catalog — the curated set of providers a user can configure, and how each is reached.
//!
//! Curated rather than derived: models.dev knows every provider's models but not the wire quirks
//! Luxe needs (which API a provider speaks, whether it takes `developer` roles, how it spells a
//! thinking toggle), and a *wrong* default is worse than an absent one. Anything not listed here
//! still works — `custom` covers any OpenAI-compatible endpoint, and a hand-written `models.json`
//! provider block always wins over these defaults.
//!
//! The catalog is the single source of truth for: which adapter a provider id routes to, its default
//! base URL, its environment variables, its compat flags, and which login methods it offers.
use std::borrow::Cow;
use luxe_core::auth::{ApiKind, AuthMethod, AuthMethodKind};
use self::table::{flags::anthropic_flags, BASE, CATALOG};
use super::source::KeyStyle;
use crate::config::CompatFlags;
mod table;
/// Which OAuth flow a subscription login runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OauthFlow {
/// ChatGPT Plus/Pro via the Codex client (PKCE loopback, or OpenAI's device-code flow).
OpenaiCodex,
/// GitHub Copilot (RFC 8628 device flow, then a Copilot token exchange).
GithubCopilot,
/// OpenRouter's published PKCE flow, which mints a user-owned API key.
OpenRouter,
}
/// Which of its metadata catalog's models a provider actually serves.
///
/// A catalog id is not always one-to-one with an endpoint. Two of them are not: a subscription
/// backend serves a different product than the API behind the same brand, and one Microsoft Foundry
/// resource is two providers over a single models.dev catalog, split by who published the model.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ServedModels {
/// Everything the metadata catalog lists.
#[default]
Catalog,
/// Exactly these ids.
///
/// The ChatGPT-account Codex endpoint refuses `gpt-5.3-codex` ("not supported when using Codex
/// with a ChatGPT account") while serving models the API catalog lists separately.
Only(&'static [&'static str]),
/// The catalog's models whose id starts with one of these.
Prefixed(&'static [&'static str]),
/// The catalog's models whose id starts with none of these — the other half of a
/// [`ServedModels::Prefixed`] split.
///
/// A prefix rather than a list because the rule is the *publisher*: Foundry reaches Anthropic's
/// models at `/anthropic/v1` and everyone else's at `/openai/v1`, so a list would go stale the
/// next time Anthropic ships and put a brand-new model on the wrong path.
Unprefixed(&'static [&'static str]),
}
impl ServedModels {
/// Whether this provider serves `id`, ignoring case.
///
/// Case-blind because a model id is not always a catalog id: Azure reports a deployment of
/// DeepSeek as `DeepSeek-V4-Flash`, and a case-sensitive `deepseek-` would have sent it down the
/// OpenAI path.
pub fn serves(self, id: &str) -> bool {
let id = id.to_ascii_lowercase();
match self {
Self::Catalog => true,
Self::Only(ids) => ids.iter().any(|known| known.eq_ignore_ascii_case(&id)),
Self::Prefixed(prefixes) => prefixes.iter().any(|prefix| id.starts_with(prefix)),
Self::Unprefixed(prefixes) => !prefixes.iter().any(|prefix| id.starts_with(prefix)),
}
}
}
/// Where a provider lives under a resource the user names.
///
/// For a host that serves several APIs off one resource. What a user has to hand is the resource
/// name, or a target URI copied off a deployment's Details tab — never the base URLs, whose paths
/// they would have to know and which differ per API.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResourceEndpoint {
/// Host form for a bare resource name, with `{resource}` standing in for it.
pub host: &'static str,
/// Path this provider serves under, appended to the resource root.
pub path: &'static str,
}
/// One curated provider.
#[derive(Debug, Clone)]
pub struct ProviderDescriptor {
/// Provider id — the `auth.json` key and the `provider` half of a `provider/model` ref.
pub id: Cow<'static, str>,
/// Display name.
pub name: Cow<'static, str>,
/// Which wire API this provider speaks.
pub api: ApiKind,
/// Default endpoint, including the version segment. `None` when the user must supply one.
pub base_url: Option<&'static str>,
/// How this provider's base URL is derived from a resource, when it isn't typed whole.
pub endpoint: Option<ResourceEndpoint>,
/// Environment variables consulted for an ambient key, most specific first.
pub env: &'static [&'static str],
/// How this provider wants its API key presented. `None` derives it from [`Self::api`].
///
/// Only a host that re-serves another vendor's API needs to say: Foundry's passthrough speaks
/// Anthropic Messages and authenticates the Azure way.
pub key_style: Option<KeyStyle>,
/// models.dev provider id for model metadata, when it has one.
pub models_dev: Option<&'static str>,
/// Whether an API key can be stored for this provider.
pub api_key_login: bool,
/// The subscription flow this provider offers, and how to label it.
pub oauth: Option<(OauthFlow, &'static str)>,
/// Where to get an API key.
pub console_url: Option<&'static str>,
/// Shape hint shown next to the key prompt (`sk-ant-…`).
pub key_hint: Option<&'static str>,
/// A caveat the user should read *before* choosing this provider (a terms restriction, a
/// billing surprise). Shown when the flow starts.
pub note: Option<&'static str>,
/// Advice that only makes sense once the credential exists — shown with the outcome.
pub after_login: Option<&'static str>,
/// Whether this provider needs no credential at all (a local server).
pub keyless: bool,
/// Whether logging in must ask for a base URL (a custom endpoint, Azure).
pub needs_base_url: bool,
/// Whether `{base_url}/models` answers.
///
/// Foundry's Anthropic passthrough has no such endpoint — Anthropic's own Foundry client
/// removes it — so a login must not read the 404 as a broken key.
pub lists_models: bool,
/// Whether this is an Azure resource that can say what it has deployed.
///
/// The `azure` catalog lists every model Azure offers, which is not what a resource serves:
/// that is whatever somebody deployed, under whatever name they chose. Discovery asks the
/// resource ([`super::deployments`]) and records the answer as `served_models`.
pub lists_deployments: bool,
/// The other providers the same credential configures.
///
/// One Foundry resource, one key, three wire APIs: logging in to any of them configures all,
/// because asking someone to paste the same key three times is a papercut, not a design. Every
/// member names all the others, and a test holds the group closed.
pub paired_with: &'static [&'static str],
/// Compat defaults; a `models.json` provider block overrides them.
pub compat_defaults: fn() -> CompatFlags,
/// Which of its metadata catalog's models this provider serves.
pub served_models: ServedModels,
/// Whether tokens are billed to a subscription rather than per token.
///
/// Separate from having an OAuth method: OpenRouter's flow mints a key that bills real credits
/// per token, so it is *not* subscription-metered.
pub subscription_billed: bool,
/// Models worth defaulting to, best first.
///
/// A capable workhorse rather than the flagship: nobody who never chose a model should be handed
/// the most expensive one. Only ever used when the account can actually reach the id, so a stale
/// entry costs nothing but a fallback.
pub preferred_models: &'static [&'static str],
}
impl ProviderDescriptor {
/// A provider the user named at login: an endpoint with nothing curated about it.
pub(crate) fn custom(id: String, api: ApiKind) -> Self {
Self { id: Cow::Owned(id.clone()), name: Cow::Owned(id), api, needs_base_url: true, ..BASE }
}
/// The login methods to offer, in order.
pub fn methods(&self) -> Vec<AuthMethod> {
let mut methods = Vec::new();
if let Some((_, label)) = self.oauth {
methods.push(AuthMethod::subscription(label, self.oauth_detail()));
}
if self.api_key_login {
methods.push(AuthMethod::api_key(self.key_detail()));
}
if self.keyless {
methods.push(AuthMethod {
id: "local".to_string(),
label: "Connect to the local server".to_string(),
kind: AuthMethodKind::ApiKey,
detail: self.base_url.map(|url| format!("expects {url}")),
});
}
methods
}
/// The compat flags to start from for this provider.
pub fn compat(&self) -> CompatFlags {
(self.compat_defaults)()
}
/// How this provider's API key goes on the wire.
pub fn key_style(&self) -> KeyStyle {
self.key_style.unwrap_or_else(|| KeyStyle::for_api(self.api))
}
/// This provider's base URL under a resource root.
pub fn endpoint_for(&self, root: &str) -> String {
let root = root.trim_end_matches('/');
match self.endpoint {
Some(endpoint) if !root.ends_with(endpoint.path) => format!("{root}{}", endpoint.path),
_ => root.to_string(),
}
}
/// What the user typed, reduced to the resource root every half hangs off.
///
/// Accepts all three things someone actually has: `my-resource`, the resource root, or a full
/// target URI — including the *other* half's, since one key configures both and nobody should
/// have to notice which one they pasted.
pub fn resource_root(&self, typed: &str) -> String {
let typed = typed.trim().trim_end_matches('/');
let Some(endpoint) = self.endpoint else { return typed.to_string() };
if !typed.is_empty() && !typed.contains(['.', '/', ':']) {
return endpoint.host.replace("{resource}", typed);
}
let candidate = match typed.contains("://") {
true => typed.to_string(),
false => format!("https://{typed}"),
};
// Match on the parsed path, never on the whole string: a resource actually named
// `openai-eastus` puts `/openai` inside its own hostname.
let Ok(mut url) = reqwest::Url::parse(&candidate) else { return typed.to_string() };
if self.resource_paths().into_iter().any(|path| url.path().starts_with(path)) {
url.set_path("");
}
url.to_string().trim_end_matches('/').to_string()
}
/// The leading path segment each provider on this resource serves under (`/anthropic`,
/// `/openai`).
fn resource_paths(&self) -> Vec<&'static str> {
std::iter::once(self)
.chain(self.paired_with.iter().filter_map(|id| provider_descriptor(id)))
.filter_map(|descriptor| descriptor.endpoint)
.map(|endpoint| leading_segment(endpoint.path))
.collect()
}
/// Which OAuth flow this provider's subscription login runs.
pub fn oauth_flow(&self) -> Option<OauthFlow> {
self.oauth.map(|(flow, _)| flow)
}
fn oauth_detail(&self) -> Option<String> {
match self.oauth_flow()? {
OauthFlow::OpenaiCodex => Some("Needs a ChatGPT Plus or Pro plan".to_string()),
OauthFlow::GithubCopilot => {
Some("Needs a Copilot subscription; supports GitHub Enterprise".to_string())
}
OauthFlow::OpenRouter => {
Some("Creates an API key you own, billed from OpenRouter credits".to_string())
}
}
}
fn key_detail(&self) -> Option<String> {
match (self.key_hint, self.env.first()) {
(Some(hint), Some(env)) => Some(format!("{hint} — or set {env}")),
(Some(hint), None) => Some(hint.to_string()),
(None, Some(env)) => Some(format!("or set {env}")),
(None, None) => None,
}
}
}
/// Alternate spellings accepted on the command line and in config.
///
/// `openai_compat` is Luxe's historical default provider name; the rest are the names people
/// actually type.
const ALIASES: &[(&str, &str)] = &[
("openai_compat", "openai"),
("openai-compat", "openai"),
("foundry", "foundry-openai"),
("microsoft-foundry", "foundry-openai"),
("azure-foundry", "foundry-openai"),
("ai-foundry", "foundry-openai"),
("foundry-claude", "foundry-anthropic"),
("foundry-partners", "foundry-completions"),
("codex", "openai-codex"),
("chatgpt", "openai-codex"),
("copilot", "github-copilot"),
("github_copilot", "github-copilot"),
("gemini", "google"),
("google-gemini", "google"),
("grok", "xai"),
("kimi", "moonshotai"),
("moonshot", "moonshotai"),
("qwen", "dashscope"),
("together", "togetherai"),
("z-ai", "zai"),
("glm", "zai"),
];
/// `/anthropic/v1` -> `/anthropic`.
fn leading_segment(path: &'static str) -> &'static str {
match path.get(1..).and_then(|rest| rest.find('/')) {
Some(at) => &path[..=at],
None => path,
}
}
/// Resolve a user-typed provider name to a catalog id.
pub fn canonical_id(raw: &str) -> String {
let name = raw.trim().to_ascii_lowercase();
ALIASES
.iter()
.find_map(|(alias, id)| (*alias == name).then_some(*id))
.unwrap_or(name.as_str())
.to_string()
}
/// Every curated provider, in the order the wizard lists them: the ones most people want first,
/// then the rest alphabetically, then local servers and the custom escape hatch.
pub fn provider_descriptors() -> &'static [ProviderDescriptor] {
CATALOG
}
/// One provider by id, accepting the aliases in [`canonical_id`].
pub fn provider_descriptor(id: &str) -> Option<&'static ProviderDescriptor> {
let canonical = canonical_id(id);
CATALOG.iter().find(|descriptor| descriptor.id == canonical)
}
/// The API-key environment variable for a provider, if it has one.
pub fn provider_env_vars(id: &str) -> &'static [&'static str] {
provider_descriptor(id).map(|descriptor| descriptor.env).unwrap_or(&[])
}
/// The compat floor a declared wire API implies, for a provider the catalog has never heard of.
///
/// Keyed on the API rather than the brand, for the same reason the `max_tokens` floor is: a proxy
/// or a private deployment of Anthropic Messages caches by `cache_control` exactly as Anthropic's
/// own endpoint does. A hand-declared provider that misses it is not slightly wrong — it re-reads
/// the entire transcript at full input price on every turn, and there is no error to notice.
pub fn wire_api_compat_floor(api: &str) -> Option<CompatFlags> {
match ApiKind::parse(api)? {
ApiKind::AnthropicMessages => Some(anthropic_flags()),
_ => None,
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,403 @@
//! The table — every curated provider, one entry each.
//!
//! Entries spell out only what differs from [`BASE`]; the rest of the catalog's machinery lives in
//! the parent module.
use luxe_core::auth::ApiKind;
use std::borrow::Cow::Borrowed;
use flags::*;
use foundry::*;
use super::{OauthFlow, ProviderDescriptor, ServedModels};
use crate::auth::source::KeyStyle;
pub(super) mod flags;
pub(super) mod foundry;
/// Shared defaults every entry starts from; an entry spells out only what differs.
///
/// `id`, `name` and `api` are placeholders, as every entry sets them.
pub(super) const BASE: ProviderDescriptor = ProviderDescriptor {
id: Borrowed(""),
name: Borrowed(""),
api: ApiKind::OpenaiCompletions,
base_url: None,
endpoint: None,
env: &[],
key_style: None,
models_dev: None,
api_key_login: true,
oauth: None,
console_url: None,
key_hint: None,
note: None,
after_login: None,
keyless: false,
needs_base_url: false,
lists_models: true,
lists_deployments: false,
paired_with: &[],
compat_defaults: plain,
served_models: ServedModels::Catalog,
subscription_billed: false,
preferred_models: &[],
};
/// The curated catalog.
///
/// Adding an entry: get the base URL's version segment right, name the environment variable the
/// provider's own docs use, and point `models_dev` at a real catalog id (a test enforces that).
pub(super) static CATALOG: &[ProviderDescriptor] = &[
ProviderDescriptor {
id: Borrowed("openai"),
name: Borrowed("OpenAI"),
api: ApiKind::OpenaiResponses,
base_url: Some("https://api.openai.com/v1"),
env: &["OPENAI_API_KEY"],
models_dev: Some("openai"),
console_url: Some("https://platform.openai.com/api-keys"),
key_hint: Some("sk-…"),
preferred_models: &["gpt-5.6", "gpt-5.4", "gpt-5.2", "gpt-5"],
compat_defaults: openai_flags,
..BASE
},
ProviderDescriptor {
id: Borrowed("openai-codex"),
name: Borrowed("OpenAI Codex (ChatGPT Plus/Pro)"),
api: ApiKind::OpenaiCodex,
base_url: Some("https://chatgpt.com/backend-api"),
models_dev: Some("openai"),
api_key_login: false,
oauth: Some((OauthFlow::OpenaiCodex, "Sign in with ChatGPT")),
note: Some(
"Uses your ChatGPT plan's Codex quota. For pay-as-you-go API billing, pick OpenAI instead.",
),
served_models: ServedModels::Only(&[
"gpt-5.6-sol",
"gpt-5.6-luna",
"gpt-5.6-terra",
"gpt-5.5",
"gpt-5.4",
"gpt-5.4-mini",
"gpt-5.3-codex-spark",
]),
subscription_billed: true,
preferred_models: &["gpt-5.6-sol", "gpt-5.4", "gpt-5.3-codex-spark"],
compat_defaults: codex_flags,
..BASE
},
ProviderDescriptor {
id: Borrowed("anthropic"),
name: Borrowed("Anthropic"),
api: ApiKind::AnthropicMessages,
base_url: Some("https://api.anthropic.com/v1"),
env: &["ANTHROPIC_API_KEY"],
models_dev: Some("anthropic"),
console_url: Some("https://console.anthropic.com/settings/keys"),
key_hint: Some("sk-ant-…"),
note: Some(
"API key only. Anthropic's terms forbid using a Claude Pro/Max subscription from a \
third-party harness, so Luxe does not offer that sign-in.",
),
preferred_models: &["claude-sonnet-5-5", "claude-sonnet-5", "claude-sonnet-4-6"],
compat_defaults: anthropic_flags,
..BASE
},
ProviderDescriptor {
id: Borrowed("github-copilot"),
name: Borrowed("GitHub Copilot"),
api: ApiKind::OpenaiCompletions,
base_url: Some("https://api.individual.githubcopilot.com"),
env: &["COPILOT_GITHUB_TOKEN"],
models_dev: Some("github-copilot"),
api_key_login: false,
oauth: Some((OauthFlow::GithubCopilot, "Sign in with GitHub")),
after_login: Some(
"If a model reports \"not supported\", enable it once in VS Code: Copilot Chat → model \
picker → Enable.",
),
subscription_billed: true,
preferred_models: &["claude-sonnet-5", "gpt-5.6-sol", "gpt-5.4"],
compat_defaults: copilot_flags,
..BASE
},
ProviderDescriptor {
id: Borrowed("openrouter"),
name: Borrowed("OpenRouter"),
api: ApiKind::OpenaiCompletions,
base_url: Some("https://openrouter.ai/api/v1"),
env: &["OPENROUTER_API_KEY"],
models_dev: Some("openrouter"),
oauth: Some((OauthFlow::OpenRouter, "Sign in with OpenRouter")),
console_url: Some("https://openrouter.ai/keys"),
key_hint: Some("sk-or-…"),
preferred_models: &["anthropic/claude-sonnet-5", "openai/gpt-5.6-sol"],
compat_defaults: openrouter_flags,
..BASE
},
ProviderDescriptor {
id: Borrowed("google"),
name: Borrowed("Google Gemini"),
api: ApiKind::OpenaiCompletions,
base_url: Some("https://generativelanguage.googleapis.com/v1beta/openai"),
env: &["GEMINI_API_KEY", "GOOGLE_API_KEY"],
models_dev: Some("google"),
console_url: Some("https://aistudio.google.com/apikey"),
key_hint: Some("AIza…"),
note: Some(
"API key only. Google's terms forbid using Gemini CLI / Google AI subscription sign-in \
from a third-party harness, so Luxe does not offer that sign-in.",
),
preferred_models: &["gemini-3.1-pro-preview", "gemini-3.8-flash", "gemini-2.5-pro"],
..BASE
},
ProviderDescriptor {
id: Borrowed("xai"),
name: Borrowed("xAI (Grok)"),
api: ApiKind::OpenaiCompletions,
base_url: Some("https://api.x.ai/v1"),
env: &["XAI_API_KEY"],
models_dev: Some("xai"),
console_url: Some("https://console.x.ai"),
key_hint: Some("xai-…"),
preferred_models: &["grok-4.5", "grok-4.3"],
..BASE
},
ProviderDescriptor {
id: Borrowed("deepseek"),
name: Borrowed("DeepSeek"),
api: ApiKind::OpenaiCompletions,
base_url: Some("https://api.deepseek.com/v1"),
env: &["DEEPSEEK_API_KEY"],
models_dev: Some("deepseek"),
console_url: Some("https://platform.deepseek.com/api_keys"),
key_hint: Some("sk-…"),
preferred_models: &["deepseek-v4-pro", "deepseek-flash", "deepseek-v4-flash"],
compat_defaults: deepseek_flags,
..BASE
},
ProviderDescriptor {
id: Borrowed("groq"),
name: Borrowed("Groq"),
api: ApiKind::OpenaiCompletions,
base_url: Some("https://api.groq.com/openai/v1"),
env: &["GROQ_API_KEY"],
models_dev: Some("groq"),
console_url: Some("https://console.groq.com/keys"),
key_hint: Some("gsk_…"),
..BASE
},
ProviderDescriptor {
id: Borrowed("cerebras"),
name: Borrowed("Cerebras"),
api: ApiKind::OpenaiCompletions,
base_url: Some("https://api.cerebras.ai/v1"),
env: &["CEREBRAS_API_KEY"],
models_dev: Some("cerebras"),
console_url: Some("https://cloud.cerebras.ai"),
key_hint: Some("csk-…"),
..BASE
},
ProviderDescriptor {
id: Borrowed("mistral"),
name: Borrowed("Mistral"),
api: ApiKind::OpenaiCompletions,
base_url: Some("https://api.mistral.ai/v1"),
env: &["MISTRAL_API_KEY"],
models_dev: Some("mistral"),
console_url: Some("https://console.mistral.ai/api-keys"),
..BASE
},
ProviderDescriptor {
id: Borrowed("dashscope"),
name: Borrowed("Alibaba DashScope (Qwen)"),
api: ApiKind::OpenaiCompletions,
base_url: Some("https://dashscope-intl.aliyuncs.com/compatible-mode/v1"),
env: &["DASHSCOPE_API_KEY"],
models_dev: Some("alibaba"),
console_url: Some("https://bailian.console.alibabacloud.com"),
key_hint: Some("sk-…"),
compat_defaults: qwen_flags,
..BASE
},
ProviderDescriptor {
id: Borrowed("zai"),
name: Borrowed("Z.AI (GLM)"),
api: ApiKind::OpenaiCompletions,
base_url: Some("https://api.z.ai/api/paas/v4"),
env: &["ZAI_API_KEY"],
models_dev: Some("zai"),
console_url: Some("https://z.ai/manage-apikey/apikey-list"),
preferred_models: &["glm-4.6", "glm-4.5"],
..BASE
},
ProviderDescriptor {
id: Borrowed("moonshotai"),
name: Borrowed("Moonshot AI (Kimi)"),
api: ApiKind::OpenaiCompletions,
base_url: Some("https://api.moonshot.ai/v1"),
env: &["MOONSHOT_API_KEY"],
models_dev: Some("moonshotai"),
console_url: Some("https://platform.moonshot.ai/console/api-keys"),
key_hint: Some("sk-…"),
..BASE
},
ProviderDescriptor {
id: Borrowed("togetherai"),
name: Borrowed("Together AI"),
api: ApiKind::OpenaiCompletions,
base_url: Some("https://api.together.xyz/v1"),
env: &["TOGETHER_API_KEY"],
models_dev: Some("togetherai"),
console_url: Some("https://api.together.ai/settings/api-keys"),
compat_defaults: together_flags,
..BASE
},
ProviderDescriptor {
id: Borrowed("fireworks"),
name: Borrowed("Fireworks AI"),
api: ApiKind::OpenaiCompletions,
base_url: Some("https://api.fireworks.ai/inference/v1"),
env: &["FIREWORKS_API_KEY"],
models_dev: Some("fireworks-ai"),
console_url: Some("https://fireworks.ai/account/api-keys"),
key_hint: Some("fw_…"),
..BASE
},
ProviderDescriptor {
id: Borrowed("nvidia"),
name: Borrowed("NVIDIA NIM"),
api: ApiKind::OpenaiCompletions,
base_url: Some("https://integrate.api.nvidia.com/v1"),
env: &["NVIDIA_API_KEY"],
models_dev: Some("nvidia"),
console_url: Some("https://build.nvidia.com"),
key_hint: Some("nvapi-…"),
..BASE
},
ProviderDescriptor {
id: Borrowed("vercel"),
name: Borrowed("Vercel AI Gateway"),
api: ApiKind::OpenaiCompletions,
base_url: Some("https://ai-gateway.vercel.sh/v1"),
env: &["AI_GATEWAY_API_KEY"],
models_dev: Some("vercel"),
console_url: Some("https://vercel.com/dashboard/ai-gateway/api-keys"),
key_hint: Some("vck_…"),
..BASE
},
ProviderDescriptor {
id: Borrowed("foundry-openai"),
name: Borrowed("Microsoft Foundry (OpenAI models)"),
api: ApiKind::OpenaiResponses,
endpoint: Some(FOUNDRY_OPENAI_ENDPOINT),
env: &["FOUNDRY_API_KEY"],
models_dev: Some("azure"),
console_url: Some("https://ai.azure.com"),
note: Some(
"Needs your Foundry resource — its name, or any endpoint off a deployment's Details \
tab. The same key configures your Claude deployments too.",
),
needs_base_url: true,
lists_deployments: true,
paired_with: &["foundry-anthropic", "foundry-completions"],
served_models: ServedModels::Unprefixed(FOUNDRY_NON_RESPONSES_PREFIXES),
preferred_models: &["gpt-5.6-terra", "gpt-5.6-sol", "gpt-5.6-luna", "gpt-5.4"],
compat_defaults: openai_flags,
..BASE
},
ProviderDescriptor {
id: Borrowed("foundry-anthropic"),
name: Borrowed("Microsoft Foundry (Claude)"),
api: ApiKind::AnthropicMessages,
endpoint: Some(FOUNDRY_ANTHROPIC_ENDPOINT),
env: &["FOUNDRY_API_KEY", "ANTHROPIC_FOUNDRY_API_KEY"],
key_style: Some(KeyStyle::FoundryKey),
models_dev: Some("azure"),
console_url: Some("https://ai.azure.com"),
note: Some(
"Needs your Foundry resource — its name, or any endpoint off a deployment's Details \
tab. The same key configures your GPT deployments too.",
),
after_login: Some(
"Claude on Foundry is Azure's product: its context limits and rates come from the \
Azure catalog, which does not always match Anthropic's own.",
),
needs_base_url: true,
lists_models: false,
lists_deployments: true,
paired_with: &["foundry-openai", "foundry-completions"],
served_models: ServedModels::Prefixed(FOUNDRY_ANTHROPIC_PREFIXES),
preferred_models: &["claude-sonnet-5-5", "claude-sonnet-5", "claude-sonnet-4-6"],
compat_defaults: anthropic_flags,
..BASE
},
ProviderDescriptor {
id: Borrowed("foundry-completions"),
name: Borrowed("Microsoft Foundry (partner models)"),
api: ApiKind::OpenaiCompletions,
endpoint: Some(FOUNDRY_OPENAI_ENDPOINT),
env: &["FOUNDRY_API_KEY"],
models_dev: Some("azure"),
console_url: Some("https://ai.azure.com"),
note: Some(
"For the models on a Foundry resource that OpenAI and Anthropic did not publish — \
DeepSeek, Grok, Llama, Mistral, Phi, Cohere. They answer on chat/completions.",
),
needs_base_url: true,
lists_deployments: true,
paired_with: &["foundry-openai", "foundry-anthropic"],
served_models: ServedModels::Prefixed(FOUNDRY_COMPLETIONS_PREFIXES),
preferred_models: &["deepseek-v4-pro", "grok-4-20-reasoning", "llama-3.3-70b-instruct"],
..BASE
},
ProviderDescriptor {
id: Borrowed("azure"),
name: Borrowed("Azure OpenAI (classic)"),
api: ApiKind::OpenaiResponses,
env: &["AZURE_OPENAI_API_KEY"],
models_dev: Some("azure"),
console_url: Some("https://portal.azure.com"),
note: Some(
"For an `openai.azure.com` resource. A `services.ai.azure.com` one is Microsoft \
Foundry — pick that instead and Luxe derives both endpoints for you.",
),
needs_base_url: true,
lists_deployments: true,
compat_defaults: openai_flags,
..BASE
},
ProviderDescriptor {
id: Borrowed("lmstudio"),
name: Borrowed("LM Studio (local)"),
api: ApiKind::OpenaiCompletions,
base_url: Some("http://127.0.0.1:1234/v1"),
models_dev: Some("lmstudio"),
api_key_login: false,
console_url: Some("https://lmstudio.ai"),
keyless: true,
compat_defaults: local_flags,
..BASE
},
ProviderDescriptor {
id: Borrowed("ollama"),
name: Borrowed("Ollama (local)"),
api: ApiKind::OpenaiCompletions,
base_url: Some("http://127.0.0.1:11434/v1"),
api_key_login: false,
console_url: Some("https://ollama.com"),
keyless: true,
compat_defaults: local_flags,
..BASE
},
ProviderDescriptor {
id: Borrowed("custom"),
name: Borrowed("Custom OpenAI-compatible endpoint"),
api: ApiKind::OpenaiCompletions,
note: Some("vLLM, llama.cpp, a proxy, or anything else that speaks /chat/completions"),
needs_base_url: true,
..BASE
},
];

View File

@@ -0,0 +1,79 @@
//! Compat defaults — the wire quirks each catalog entry starts from.
//!
//! One constructor per distinct set, so an entry names its flavour rather than spelling the flags
//! out. A hand-written `models.json` provider block overrides whatever these say.
use crate::config::CompatFlags;
pub(in crate::auth::catalog) fn plain() -> CompatFlags {
CompatFlags::default()
}
pub(in crate::auth::catalog) fn openai_flags() -> CompatFlags {
CompatFlags {
supports_developer_role: true,
supports_reasoning_effort: true,
use_responses_api: true,
max_tokens_field: "max_completion_tokens".to_string(),
..CompatFlags::default()
}
}
pub(in crate::auth::catalog) fn codex_flags() -> CompatFlags {
CompatFlags { supports_reasoning_effort: true, ..CompatFlags::default() }
}
pub(in crate::auth::catalog) fn anthropic_flags() -> CompatFlags {
CompatFlags { cache_control_format: Some("anthropic".to_string()), ..CompatFlags::default() }
}
pub(in crate::auth::catalog) fn thinking(format: &str) -> CompatFlags {
CompatFlags { thinking_format: Some(format.to_string()), ..CompatFlags::default() }
}
pub(in crate::auth::catalog) fn openrouter_flags() -> CompatFlags {
CompatFlags {
supports_reasoning_effort: true,
// OpenRouter does not cache Claude implicitly, so an agentic session re-reads its whole
// transcript at full price on every turn unless asked otherwise. One field asks.
cache_control_format: Some("openrouter".to_string()),
openrouter_headers: true,
..thinking("openrouter")
}
}
pub(in crate::auth::catalog) fn deepseek_flags() -> CompatFlags {
CompatFlags { supports_reasoning_effort: true, ..thinking("deepseek") }
}
pub(in crate::auth::catalog) fn together_flags() -> CompatFlags {
CompatFlags { supports_reasoning_effort: true, ..thinking("together") }
}
pub(in crate::auth::catalog) fn qwen_flags() -> CompatFlags {
thinking("qwen")
}
pub(in crate::auth::catalog) fn local_flags() -> CompatFlags {
CompatFlags {
supports_developer_role: true,
thinking_format: Some("chat_template".to_string()),
..CompatFlags::default()
}
}
pub(in crate::auth::catalog) fn copilot_flags() -> CompatFlags {
// Copilot's endpoint accepts `stream_options: {include_usage: true}` and returns usage, so the
// default (on) stands: turning it off was a guess that would have silently zeroed the token
// count on every Copilot turn. It does need per-request editor headers, which the adapter adds.
// The cache format is for Claude, which Copilot serves on `/v1/messages` and which caches only
// where it is asked to; the chat and Responses adapters have no use for it. Effort reaches
// the chat-completions models (Gemini, Kimi) as `reasoning_effort`, held to the values each
// model lists by `copilot::adopt_efforts`.
CompatFlags {
copilot_headers: true,
supports_reasoning_effort: true,
cache_control_format: Some("anthropic".to_string()),
..CompatFlags::default()
}
}

View File

@@ -0,0 +1,52 @@
//! Microsoft Foundry — the model-id prefixes and endpoints that split one resource into providers.
use crate::auth::catalog::ResourceEndpoint;
/// Model-id prefixes that Microsoft Foundry reaches through its Anthropic passthrough.
///
/// The split between Luxe's two Foundry providers, stated once. Every Anthropic-published model in
/// the models.dev `azure` catalog is named `claude-*`, and a test holds that true.
pub(in crate::auth::catalog) const FOUNDRY_ANTHROPIC_PREFIXES: &[&str] = &["claude-"];
/// Model-id prefixes that Microsoft Foundry serves on `/openai/v1/chat/completions`.
///
/// A Foundry resource can host models nobody at OpenAI or Anthropic published — Cohere, DeepSeek,
/// Grok, Kimi, Llama, Mistral, Phi — and those speak the older chat/completions dialect rather than
/// the Responses API sold beside them at the same path.
pub(in crate::auth::catalog) const FOUNDRY_COMPLETIONS_PREFIXES: &[&str] = &[
"codestral-",
"cohere-",
"deepseek-",
"grok-",
"kimi-",
"llama-",
"ministral-",
"mistral-",
"phi-",
];
/// Everything a Foundry resource does **not** reach through `/openai/v1/responses`.
///
/// The union of the other two surfaces' prefixes, spelled out because stable Rust cannot
/// concatenate const slices — a test holds it equal to that union, so the three rules cannot drift
/// into a model served twice or not at all.
pub(in crate::auth::catalog) const FOUNDRY_NON_RESPONSES_PREFIXES: &[&str] = &[
"claude-",
"codestral-",
"cohere-",
"deepseek-",
"grok-",
"kimi-",
"llama-",
"ministral-",
"mistral-",
"phi-",
];
/// A Foundry resource's OpenAI-shaped surface.
pub(in crate::auth::catalog) const FOUNDRY_OPENAI_ENDPOINT: ResourceEndpoint =
ResourceEndpoint { host: "https://{resource}.services.ai.azure.com", path: "/openai/v1" };
/// A Foundry resource's Anthropic passthrough.
pub(in crate::auth::catalog) const FOUNDRY_ANTHROPIC_ENDPOINT: ResourceEndpoint =
ResourceEndpoint { host: "https://{resource}.services.ai.azure.com", path: "/anthropic/v1" };

View File

@@ -0,0 +1,462 @@
use super::table::foundry::{
FOUNDRY_ANTHROPIC_PREFIXES, FOUNDRY_COMPLETIONS_PREFIXES, FOUNDRY_NON_RESPONSES_PREFIXES,
};
use super::*;
#[test]
fn ids_are_unique_and_lowercase() {
let mut ids: Vec<&str> = CATALOG.iter().map(|descriptor| &*descriptor.id).collect();
let count = ids.len();
ids.sort_unstable();
ids.dedup();
assert_eq!(ids.len(), count, "duplicate provider id in the catalog");
for descriptor in CATALOG {
assert_eq!(
descriptor.id.to_ascii_lowercase(),
descriptor.id,
"{} must be lowercase",
descriptor.id
);
assert!(!descriptor.name.is_empty());
}
}
/// A provider nobody can log in to is a dead row in the wizard.
#[test]
fn every_provider_offers_at_least_one_method() {
for descriptor in CATALOG {
assert!(!descriptor.methods().is_empty(), "{} offers no login method", descriptor.id);
}
}
/// The whole point of the catalog is that its defaults are right. A base URL without the
/// version segment 404s at request time, which is a miserable thing to debug.
#[test]
fn base_urls_are_absolute_and_unslashed() {
for descriptor in CATALOG {
let Some(url) = descriptor.base_url else {
assert!(
descriptor.needs_base_url,
"{} has no base URL and doesn't ask for one",
descriptor.id
);
continue;
};
assert!(
url.starts_with("http://") || url.starts_with("https://"),
"{} base URL is not absolute: {url}",
descriptor.id
);
assert!(!url.ends_with('/'), "{} base URL has a trailing slash: {url}", descriptor.id);
}
}
/// A renamed models.dev provider would silently degrade every model to fallback metadata.
///
/// Resolution goes through [`models_dev_provider`], the same mapping lookup uses, because most
/// providers carry no explicit `models_dev` override — they map verbatim or through the alias
/// table. Reading the field directly skipped all of them, which is how `google` and `deepseek`
/// kept preference lists upstream had already retired.
#[test]
fn models_dev_ids_exist_in_the_embedded_snapshot() {
let snapshot = crate::catalog::snapshot();
for descriptor in CATALOG {
if descriptor.keyless || descriptor.base_url.is_none() {
continue; // a local server or a BYO endpoint has no upstream vendor to check
}
let id = crate::catalog::alias::models_dev_provider(&descriptor.id, None);
let count = snapshot.provider_models(id).count();
assert!(
count > 0,
"{}: models.dev id '{id}' has no models in the embedded snapshot — fix the id or \
rerun scripts/update-models-snapshot.sh",
descriptor.id
);
}
}
/// A preference list of ids nothing recognizes is worse than no list: it would hand a new user a
/// model their account can't serve. At least one entry must still exist upstream.
///
/// The leading id is the one a new account actually gets, so it is held to the stricter bar: a
/// dead first choice is a silent demotion to the runner-up on every fresh install.
#[test]
fn preferred_models_still_exist_in_the_embedded_snapshot() {
let snapshot = crate::catalog::snapshot();
for descriptor in CATALOG {
if descriptor.preferred_models.is_empty() {
continue;
}
let models_dev = crate::catalog::alias::models_dev_provider(&descriptor.id, None);
let known = |id: &str| {
snapshot.model(models_dev, id).is_some()
|| crate::catalog::alias::normalize_model_id(id)
.is_some_and(|base| snapshot.model(models_dev, base).is_some())
};
let live = descriptor.preferred_models.iter().filter(|id| known(id)).count();
assert!(
live > 0,
"{}: none of its preferred models {:?} exist under models.dev '{models_dev}' \
— refresh the list or the snapshot",
descriptor.id,
descriptor.preferred_models
);
let first = descriptor.preferred_models[0];
assert!(
known(first),
"{}: its first-choice model '{first}' is gone from models.dev '{models_dev}', so \
every new account silently falls through to the next entry — promote a live id",
descriptor.id
);
}
}
/// A served rule is a promise: an explicit id the metadata catalog doesn't know would show up
/// as a model with no context window, and a prefix nothing matches would empty the picker.
#[test]
fn served_rules_match_real_models_and_cover_the_preferred_ones() {
let snapshot = crate::catalog::snapshot();
for descriptor in CATALOG {
if descriptor.served_models == ServedModels::Catalog {
continue;
}
let models_dev = descriptor.models_dev.expect("a served rule needs metadata to hang on");
match descriptor.served_models {
ServedModels::Catalog => unreachable!("skipped above"),
ServedModels::Only(ids) => {
assert!(!ids.is_empty(), "{}: an empty list serves nothing", descriptor.id);
for id in ids {
assert!(
snapshot.model(models_dev, id).is_some(),
"{}: served model '{id}' is unknown to models.dev '{models_dev}'",
descriptor.id
);
}
}
ServedModels::Prefixed(prefixes) | ServedModels::Unprefixed(prefixes) => {
assert!(
!prefixes.is_empty(),
"{}: a rule with no prefixes says nothing",
descriptor.id
);
for prefix in prefixes {
assert!(
snapshot.provider_models(models_dev).any(|(id, _)| id.starts_with(prefix)),
"{}: no models.dev '{models_dev}' model starts with '{prefix}'",
descriptor.id
);
}
}
}
// Defaulting to a model the backend refuses is the bug this pairing prevents.
for preferred in descriptor.preferred_models {
assert!(
descriptor.served_models.serves(preferred),
"{}: prefers '{preferred}', which it does not serve",
descriptor.id
);
}
}
}
/// The three Foundry providers share one models.dev catalog and must partition it **exactly**.
/// A model two of them serve is a coin toss over which path a request takes; a model none of
/// them serves is one nobody can reach through a picker.
#[test]
fn the_three_foundry_surfaces_partition_the_azure_catalog() {
let snapshot = crate::catalog::snapshot();
let surfaces: Vec<&ProviderDescriptor> =
["foundry-openai", "foundry-anthropic", "foundry-completions"]
.iter()
.map(|id| provider_descriptor(id).expect("in catalog"))
.collect();
for surface in &surfaces {
assert_eq!(
surface.models_dev,
Some("azure"),
"{}: one catalog, three surfaces",
surface.id
);
}
let mut counts = [0usize; 3];
for (id, _) in snapshot.provider_models("azure") {
let serving: Vec<&str> = surfaces
.iter()
.filter(|surface| surface.served_models.serves(id))
.map(|surface| &*surface.id)
.collect();
assert_eq!(serving.len(), 1, "'{id}' is served by {serving:?}, not by exactly one");
let at = surfaces.iter().position(|s| s.id == serving[0]).expect("known surface");
counts[at] += 1;
}
for (surface, count) in surfaces.iter().zip(counts) {
assert!(count >= 5, "{} serves only {count} models", surface.id);
}
// The split is the publisher, so a deployment name Luxe has never heard of still lands on
// the OpenAI-shaped surface rather than nowhere.
let served_by = |id: &str| -> Vec<&str> {
surfaces
.iter()
.filter(|surface| surface.served_models.serves(id))
.map(|surface| &*surface.id)
.collect()
};
assert_eq!(served_by("my-own-deployment"), vec!["foundry-openai"]);
assert_eq!(served_by("claude-something-new"), vec!["foundry-anthropic"]);
assert_eq!(served_by("deepseek-v4-pro"), vec!["foundry-completions"]);
}
/// `FOUNDRY_NON_RESPONSES_PREFIXES` is a hand-written union because stable Rust cannot
/// concatenate const slices. Nothing but this stops the three rules drifting apart into a model
/// served twice, or one served nowhere.
#[test]
fn the_responses_exclusion_list_is_exactly_the_other_two_surfaces() {
let mut union: Vec<&str> =
FOUNDRY_ANTHROPIC_PREFIXES.iter().chain(FOUNDRY_COMPLETIONS_PREFIXES).copied().collect();
union.sort_unstable();
let mut excluded: Vec<&str> = FOUNDRY_NON_RESPONSES_PREFIXES.to_vec();
excluded.sort_unstable();
assert_eq!(excluded, union);
}
/// Each surface reaches its own path under one resource, and a root that already names the path
/// is left alone — someone who pasted a full target URI must not get
/// `/anthropic/v1/anthropic/v1`.
#[test]
fn a_foundry_resource_root_becomes_every_endpoint() {
let root = "https://acme-foundry.services.ai.azure.com";
let openai = provider_descriptor("foundry-openai").expect("in catalog");
let anthropic = provider_descriptor("foundry-anthropic").expect("in catalog");
let completions = provider_descriptor("foundry-completions").expect("in catalog");
assert_eq!(openai.endpoint_for(root), "https://acme-foundry.services.ai.azure.com/openai/v1");
// Two APIs on one path: the adapter decides `/responses` against `/chat/completions`.
assert_eq!(completions.endpoint_for(root), openai.endpoint_for(root));
assert_ne!(completions.api, openai.api);
assert_eq!(
anthropic.endpoint_for(root),
"https://acme-foundry.services.ai.azure.com/anthropic/v1"
);
assert_eq!(
anthropic.endpoint_for(&format!("{root}/anthropic/v1/")),
anthropic.endpoint_for(root)
);
// A provider with no resource shape takes the endpoint as typed.
assert_eq!(provider_descriptor("azure").expect("in catalog").endpoint_for(root), root);
}
/// The three things a user actually has — the resource name, the root, and a target URI copied
/// off either deployment — all have to reduce to the same root, or half the pair 404s.
#[test]
fn every_way_of_naming_a_foundry_resource_reduces_to_the_same_root() {
let root = "https://acme-foundry.services.ai.azure.com";
let anthropic = provider_descriptor("foundry-anthropic").expect("in catalog");
let openai = provider_descriptor("foundry-openai").expect("in catalog");
for typed in [
"acme-foundry",
root,
"acme-foundry.services.ai.azure.com",
"https://acme-foundry.services.ai.azure.com/",
"https://acme-foundry.services.ai.azure.com/anthropic/v1/messages",
"https://acme-foundry.services.ai.azure.com/openai/v1/responses",
" https://acme-foundry.services.ai.azure.com/anthropic ",
] {
assert_eq!(anthropic.resource_root(typed), root, "typed {typed:?}");
assert_eq!(openai.resource_root(typed), root, "typed {typed:?}");
}
// A resource whose own name contains a path marker must not be truncated to its scheme.
let awkward = "https://openai-eastus.services.ai.azure.com";
assert_eq!(anthropic.resource_root(awkward), awkward);
// A gateway that fronts the resource under a path of its own keeps it.
assert_eq!(
openai.endpoint_for(&openai.resource_root("https://gw.corp.example/foundry")),
"https://gw.corp.example/foundry/openai/v1"
);
}
/// The group is the whole reason several ids exist, and it has to be closed: logging in to any
/// member configures the others, so a one-way link leaves part of a resource unreachable.
#[test]
fn paired_providers_form_a_closed_group() {
for descriptor in CATALOG {
if descriptor.paired_with.is_empty() {
continue;
}
let group = |d: &'static ProviderDescriptor| {
let mut ids: Vec<&str> =
std::iter::once(&*d.id).chain(d.paired_with.iter().copied()).collect();
ids.sort_unstable();
ids
};
let mine = group(descriptor);
for id in descriptor.paired_with {
let sibling = provider_descriptor(id).expect("a pair names a real provider");
assert_eq!(
group(sibling),
mine,
"{} and {} disagree about who shares their resource",
descriptor.id,
sibling.id
);
assert_ne!(
sibling.api, descriptor.api,
"{} and {} would be the same adapter",
descriptor.id, sibling.id
);
assert!(
sibling.endpoint.is_some(),
"{}: a shared resource means every member derives its own endpoint",
sibling.id
);
}
assert!(
descriptor.endpoint.is_some(),
"{}: a shared resource means every member derives its own endpoint",
descriptor.id
);
assert!(
std::iter::once(descriptor)
.chain(descriptor.paired_with.iter().filter_map(|id| provider_descriptor(id)))
.any(|member| member.lists_models),
"{}: no member of the group can verify a credential",
descriptor.id
);
}
}
/// Foundry's Anthropic passthrough speaks Anthropic Messages and authenticates the Azure way,
/// which is the entire reason the key style is not derived from the API.
#[test]
fn foundry_sends_both_key_headers_where_the_passthrough_wants_them() {
let anthropic = provider_descriptor("foundry-anthropic").expect("in catalog");
assert_eq!(anthropic.api, ApiKind::AnthropicMessages);
assert_eq!(anthropic.key_style(), KeyStyle::FoundryKey);
// The OpenAI-shaped half takes a bearer token, exactly as Microsoft's own samples send it.
assert_eq!(
provider_descriptor("foundry-openai").expect("in catalog").key_style(),
KeyStyle::Bearer
);
// Everyone else still derives from their API.
assert_eq!(
provider_descriptor("anthropic").expect("in catalog").key_style(),
KeyStyle::AnthropicKey
);
assert_eq!(provider_descriptor("openai").expect("in catalog").key_style(), KeyStyle::Bearer);
}
#[test]
fn aliases_resolve_to_real_providers() {
for (alias, target) in ALIASES {
assert!(
CATALOG.iter().any(|descriptor| descriptor.id == *target),
"alias {alias} points at unknown provider {target}"
);
assert_eq!(provider_descriptor(alias).map(|d| &*d.id), Some(*target));
}
assert_eq!(canonical_id(" CoPilot "), "github-copilot");
assert_eq!(canonical_id("openai_compat"), "openai");
assert_eq!(canonical_id("unknown-thing"), "unknown-thing");
assert!(provider_descriptor("unknown-thing").is_none());
}
#[test]
fn env_lookup_covers_the_common_providers() {
assert_eq!(provider_env_vars("anthropic"), &["ANTHROPIC_API_KEY"]);
assert_eq!(provider_env_vars("openai_compat"), &["OPENAI_API_KEY"]);
assert_eq!(provider_env_vars("google"), &["GEMINI_API_KEY", "GOOGLE_API_KEY"]);
assert!(provider_env_vars("lmstudio").is_empty());
assert!(provider_env_vars("nope").is_empty());
}
#[test]
fn subscription_providers_carry_a_flow_and_a_label() {
let subscription: Vec<&ProviderDescriptor> =
CATALOG.iter().filter(|d| d.oauth.is_some()).collect();
let ids: Vec<&str> = subscription.iter().map(|d| &*d.id).collect();
assert_eq!(ids, vec!["openai-codex", "github-copilot", "openrouter"]);
for descriptor in subscription {
let methods = descriptor.methods();
assert_eq!(
methods.first().map(|method| method.kind),
Some(AuthMethodKind::Subscription),
"{}: the subscription option should lead",
descriptor.id
);
}
}
/// Anthropic and Google are API-key-only *by decision*, and must say why rather than looking
/// like an oversight. If someone adds a subscription flow for either, this test is the
/// conversation.
#[test]
fn providers_without_a_sanctioned_subscription_explain_themselves() {
for id in ["anthropic", "google"] {
let descriptor = provider_descriptor(id).expect("in catalog");
assert!(descriptor.oauth.is_none(), "{id} must not offer subscription auth");
let note = descriptor.note.expect("must carry a note");
assert!(note.contains("terms"), "{id} note should say why: {note}");
}
}
/// The mistake this guards against was mine: I turned usage-in-streaming *off* for Copilot on a
/// hunch, which would have silently zeroed the token count on every Copilot turn. Copilot
/// accepts `stream_options` and returns usage — token accounting is not optional.
#[test]
fn copilot_still_reports_usage_and_asks_for_its_editor_headers() {
let copilot = provider_descriptor("github-copilot").expect("in catalog").compat();
assert!(
copilot.supports_usage_in_streaming,
"Copilot returns usage; disabling it loses every token count"
);
assert!(copilot.copilot_headers, "Copilot's endpoint expects its per-request headers");
assert_eq!(
copilot.cache_control_format.as_deref(),
Some("anthropic"),
"Claude over Copilot's /v1/messages caches only where a breakpoint asks it to"
);
}
/// Subscription metering is about *how tokens are paid for*, not about having an OAuth flow:
/// OpenRouter's flow mints a key that spends real credits per token.
#[test]
fn subscription_billing_is_marked_only_where_a_plan_pays() {
let billed: Vec<&str> =
CATALOG.iter().filter(|d| d.subscription_billed).map(|d| &*d.id).collect();
assert_eq!(billed, vec!["openai-codex", "github-copilot"]);
assert!(
!provider_descriptor("openrouter").expect("in catalog").subscription_billed,
"OpenRouter bills credits per token, so its costs are real spend"
);
}
#[test]
fn compat_defaults_match_what_the_adapters_expect() {
let openai = provider_descriptor("openai").expect("in catalog").compat();
assert!(openai.use_responses_api, "gpt-5-class models require /responses");
assert_eq!(openai.max_tokens_field, "max_completion_tokens");
let anthropic = provider_descriptor("anthropic").expect("in catalog").compat();
assert_eq!(anthropic.cache_control_format.as_deref(), Some("anthropic"));
assert!(provider_descriptor("lmstudio").expect("in catalog").compat().supports_developer_role);
}
/// The two spellings a gateway needs and nobody else does. Caching is the expensive one:
/// OpenRouter caches OpenAI and DeepSeek implicitly but *not* Claude, so an unasked session
/// re-reads its whole transcript at full price on every turn.
#[test]
fn openrouter_asks_for_caching_and_names_itself() {
let openrouter = provider_descriptor("openrouter").expect("in catalog").compat();
assert_eq!(openrouter.cache_control_format.as_deref(), Some("openrouter"));
assert!(openrouter.openrouter_headers);
assert_eq!(openrouter.thinking_format.as_deref(), Some("openrouter"));
let named: Vec<&str> = CATALOG
.iter()
.filter(|descriptor| descriptor.compat().openrouter_headers)
.map(|descriptor| &*descriptor.id)
.collect();
assert_eq!(named, vec!["openrouter"], "one gateway's headers, on one gateway");
}

View File

@@ -0,0 +1,302 @@
//! Config patching — the small, surgical writes onboarding makes to `models.json`.
//!
//! Credentials go in `auth.json`; *configuration* a login learns goes here. Two cases only:
//!
//! - a provider the catalog can't know about (a custom OpenAI-compatible endpoint, an Azure
//! resource) needs its `base_url` recorded, and
//! - finishing a login should leave the user pointed at something that works, which means
//! `default_provider` (and a model, when we know a good one).
//!
//! Every write is lossless and locked — a user's hand-maintained `models.json` is theirs, and this
//! only ever adds or replaces the specific keys named below.
use std::path::{Path, PathBuf};
use luxe_core::auth::ApiKind;
use serde_json::{Map, Value};
use super::json_file::{FileError, FileMode, JsonFile};
/// `~/.config/luxe/models.json`.
#[derive(Debug, Clone)]
pub struct ConfigFile {
file: JsonFile,
}
impl ConfigFile {
/// A config file at an explicit path.
pub fn new(path: PathBuf) -> Self {
Self { file: JsonFile::new(path, FileMode::PreserveExisting) }
}
/// The default `models.json` next to the credential store.
pub fn default_path() -> Self {
Self::new(luxe_core::user_dirs::luxe_config_file("models.json"))
}
/// Where this writes.
pub fn path(&self) -> &Path {
self.file.path()
}
/// Point Luxe at a provider (and optionally a model) by default.
///
/// This is what makes a first login actually take effect for the *next* launch; the running
/// session switches through `Action::SetModel`.
pub fn set_defaults(&self, provider: &str, model: Option<&str>) -> Result<(), FileError> {
self.file.modify(|root| {
root.insert("default_provider".into(), Value::String(provider.to_string()));
if let Some(model) = model.filter(|model| !model.is_empty()) {
root.insert("default_model".into(), Value::String(model.to_string()));
}
Ok(())
})
}
/// Record a provider block: base URL, which API it speaks, and where to find its metadata.
///
/// Merges into an existing block rather than replacing it, so a user's compat tweaks survive a
/// re-login.
pub fn upsert_provider(
&self,
provider: &str,
base_url: Option<&str>,
api: Option<ApiKind>,
models_dev: Option<&str>,
) -> Result<(), FileError> {
self.file.modify(|root| {
let block = provider_block(root, provider)?;
if let Some(base_url) = base_url {
block.insert(
"base_url".into(),
Value::String(base_url.trim_end_matches('/').into()),
);
}
if let Some(models_dev) = models_dev {
block.insert("models_dev".into(), Value::String(models_dev.to_string()));
}
if let Some(api) = api {
// The field that actually carries every API, including Anthropic's: writing only
// the compat flag below recorded an `anthropic-messages` endpoint as
// chat/completions, and the choice made in the wizard was silently lost.
block.insert("api".into(), Value::String(api.as_str().to_string()));
// Kept beside it because a Luxe old enough to predate `api` reads this one, and a
// config file outlives the release that wrote it.
let compat = block
.entry("compat".to_string())
.or_insert_with(|| Value::Object(Map::new()))
.as_object_mut()
.ok_or_else(|| {
FileError::Rejected(format!(
"\"providers.{provider}.compat\" in models.json is not an object"
))
})?;
compat.insert(
"use_responses_api".into(),
Value::Bool(api == ApiKind::OpenaiResponses),
);
}
Ok(())
})
}
/// Record what an endpoint answered `/models` with.
///
/// Written whenever the answer changes and read when the server is unreachable, so the picker
/// offers the models this machine actually has rather than the catalog's idea of them — and
/// still offers something with the server switched off.
pub fn set_served_models(&self, provider: &str, models: &[String]) -> Result<(), FileError> {
self.file.modify(|root| {
provider_block(root, provider)?.insert(
"served_models".into(),
Value::Array(models.iter().cloned().map(Value::String).collect()),
);
Ok(())
})
}
/// Record what an Azure resource has deployed for one provider: the names it serves, and the
/// model behind each name that is not the model's own.
///
/// `deployments` is replaced whole rather than merged, so a deployment that was deleted stops
/// mapping to anything. An empty map removes the key, keeping a block that needs none tidy.
pub fn set_deployments(
&self,
provider: &str,
served: &super::deployments::Served,
) -> Result<(), FileError> {
self.file.modify(|root| {
let block = provider_block(root, provider)?;
block.insert(
"served_models".into(),
Value::Array(served.models.iter().cloned().map(Value::String).collect()),
);
match served.deployments.is_empty() {
true => {
block.remove("deployments");
}
false => {
let map = served
.deployments
.iter()
.map(|(name, model)| (name.clone(), Value::String(model.clone())))
.collect();
block.insert("deployments".into(), Value::Object(map));
}
}
Ok(())
})
}
/// Provider ids already declared in the file.
pub fn declared_providers(&self) -> Vec<String> {
self.read().map(|root| declared_in(&root)).unwrap_or_default()
}
/// The whole file, parsed once, for a caller that reads it more than one way.
pub(crate) fn read(&self) -> Option<Map<String, Value>> {
self.file.read()
}
}
/// The provider ids a parsed `models.json` has blocks for.
pub(crate) fn declared_in(root: &Map<String, Value>) -> Vec<String> {
let providers = root.get("providers").and_then(Value::as_object);
providers.map(|providers| providers.keys().cloned().collect()).unwrap_or_default()
}
/// `providers.<id>` in a parsed `models.json`, created when it is missing.
fn provider_block<'a>(
root: &'a mut Map<String, Value>,
provider: &str,
) -> Result<&'a mut Map<String, Value>, FileError> {
root.entry("providers".to_string())
.or_insert_with(|| Value::Object(Map::new()))
.as_object_mut()
.ok_or_else(|| {
FileError::Rejected("\"providers\" in models.json is not an object".to_string())
})?
.entry(provider.to_string())
.or_insert_with(|| Value::Object(Map::new()))
.as_object_mut()
.ok_or_else(|| {
FileError::Rejected(format!("\"providers.{provider}\" in models.json is not an object"))
})
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
fn config() -> (tempfile::TempDir, ConfigFile) {
let dir = tempfile::tempdir().unwrap();
let config = ConfigFile::new(dir.path().join("models.json"));
(dir, config)
}
#[test]
fn defaults_are_written_without_disturbing_anything_else() {
let (_dir, config) = config();
std::fs::write(
config.path(),
r#"{"models": {"a/b": {"context_window": 1}}, "default_model": "old"}"#,
)
.unwrap();
config.set_defaults("openai", Some("gpt-5.4")).unwrap();
let root = serde_json::from_str::<Value>(&std::fs::read_to_string(config.path()).unwrap())
.unwrap();
assert_eq!(root["default_provider"], "openai");
assert_eq!(root["default_model"], "gpt-5.4");
assert_eq!(root["models"]["a/b"]["context_window"], 1, "unrelated config survives");
}
#[test]
fn a_provider_block_merges_rather_than_replaces() {
let (_dir, config) = config();
std::fs::write(
config.path(),
r#"{"providers": {"my-proxy": {"compat": {"supports_developer_role": true}}}}"#,
)
.unwrap();
config
.upsert_provider(
"my-proxy",
Some("https://proxy.example/v1/"),
Some(ApiKind::OpenaiResponses),
Some("openai"),
)
.unwrap();
let root = serde_json::from_str::<Value>(&std::fs::read_to_string(config.path()).unwrap())
.unwrap();
let block = &root["providers"]["my-proxy"];
assert_eq!(block["base_url"], "https://proxy.example/v1", "trailing slash trimmed");
assert_eq!(block["models_dev"], "openai");
assert_eq!(block["api"], "openai-responses");
assert_eq!(block["compat"]["use_responses_api"], true);
assert_eq!(
block["compat"]["supports_developer_role"], true,
"the user's own compat flag survives"
);
assert_eq!(config.declared_providers(), vec!["my-proxy".to_string()]);
}
#[test]
fn a_completions_api_provider_records_that_explicitly() {
let (_dir, config) = config();
config
.upsert_provider(
"local",
Some("http://127.0.0.1:8000/v1"),
Some(ApiKind::OpenaiCompletions),
None,
)
.unwrap();
let root = serde_json::from_str::<Value>(&std::fs::read_to_string(config.path()).unwrap())
.unwrap();
assert_eq!(root["providers"]["local"]["api"], "openai-completions");
assert_eq!(root["providers"]["local"]["compat"]["use_responses_api"], false);
assert!(root["providers"]["local"].get("models_dev").is_none());
}
/// The bug this catches shipped: an Anthropic-speaking endpoint has no `use_responses_api`
/// spelling, so recording only the compat flag read back as chat/completions on the next
/// launch and every request went to the wrong path.
#[test]
fn an_anthropic_endpoint_is_recorded_as_one() {
let (_dir, config) = config();
config
.upsert_provider(
"foundry-anthropic",
Some("https://r.services.ai.azure.com/anthropic/v1"),
Some(ApiKind::AnthropicMessages),
Some("azure"),
)
.unwrap();
let raw = std::fs::read_to_string(config.path()).unwrap();
let parsed = crate::config::load_models_config(config.path()).expect("loads");
let block = parsed.providers.get("foundry-anthropic").expect("block");
assert_eq!(block.api.as_deref(), Some("anthropic-messages"), "got {raw}");
assert_eq!(
crate::config::resolve_api("foundry-anthropic", Some(block)),
ApiKind::AnthropicMessages
);
}
#[test]
fn a_providers_key_of_the_wrong_shape_is_reported_not_overwritten() {
let (_dir, config) = config();
std::fs::write(config.path(), r#"{"providers": "oops"}"#).unwrap();
let error =
config.upsert_provider("x", Some("http://x/v1"), None, None).expect_err("must refuse");
assert!(format!("{error}").contains("not an object"), "got: {error}");
assert_eq!(std::fs::read_to_string(config.path()).unwrap(), r#"{"providers": "oops"}"#);
}
#[test]
fn declared_providers_is_empty_when_there_is_no_file() {
let (_dir, config) = config();
assert!(config.declared_providers().is_empty());
}
}

View File

@@ -0,0 +1,298 @@
//! Credentials — the typed contents of one `auth.json` entry.
//!
//! Serialization is hand-written rather than derived, deliberately: [`crate::config::ApiKey`]
//! serializes to `[REDACTED]` as a fail-safe, so a derived `Serialize` on a credential would write
//! placeholders into the user's auth file. [`Credential::to_json`] is the one place allowed to put a
//! secret on disk, and it is the only path the store uses.
use std::collections::BTreeMap;
use luxe_core::auth::{CredentialKind, StoredCredentialInfo};
use serde_json::{Map, Value};
use crate::config::ApiKey;
/// One provider's stored credential.
#[derive(Debug, Clone)]
pub enum Credential {
/// A long-lived API key (possibly a `$ENV` / `!command` spec, resolved at request time).
ApiKey(ApiKeyCredential),
/// An OAuth token pair that expires and refreshes.
OAuth(OAuthCredential),
}
/// A stored API key, plus any provider-scoped configuration values that travel with it.
#[derive(Debug, Clone, Default)]
pub struct ApiKeyCredential {
/// The key, verbatim as stored. `$ENV`, `${ENV}` and `!command` forms are resolved on use, not
/// here — status output must never execute a user's command to render a table.
pub key: ApiKey,
/// Provider-scoped values (deployment names, account ids) consulted before the process
/// environment. Kept so a provider needing more than a key doesn't need a second config file.
pub env: BTreeMap<String, String>,
}
/// A stored OAuth credential.
#[derive(Debug, Clone, Default)]
pub struct OAuthCredential {
/// Bearer token used on requests.
pub access: ApiKey,
/// Token used to mint a new access token. For GitHub Copilot this is the long-lived GitHub
/// token and "refresh" means re-exchanging it.
pub refresh: ApiKey,
/// Unix-millisecond expiry of `access`.
pub expires_at_ms: u64,
/// Account label the provider gave us (ChatGPT account id, GitHub login).
pub account: Option<String>,
/// A per-credential endpoint, when the provider hands one out (Copilot's `proxy-ep`).
pub endpoint: Option<String>,
/// GitHub Enterprise domain, when the login targeted one.
pub enterprise_domain: Option<String>,
/// Model ids this account may actually use, when the provider enumerates them.
pub available_models: Vec<String>,
}
impl Credential {
/// Which kind of credential this is.
pub fn kind(&self) -> CredentialKind {
match self {
Self::ApiKey(_) => CredentialKind::ApiKey,
Self::OAuth(_) => CredentialKind::OAuth,
}
}
/// Non-secret metadata for status output.
pub fn info(&self) -> StoredCredentialInfo {
match self {
Self::ApiKey(_) => StoredCredentialInfo {
kind: CredentialKind::ApiKey,
expires_at_ms: None,
account: None,
},
Self::OAuth(oauth) => StoredCredentialInfo {
kind: CredentialKind::OAuth,
expires_at_ms: Some(oauth.expires_at_ms),
account: oauth.account.clone(),
},
}
}
/// An API-key credential from a bare key.
pub fn api_key(key: impl Into<String>) -> Self {
Self::ApiKey(ApiKeyCredential { key: ApiKey::new(key.into()), env: BTreeMap::new() })
}
/// The stored OAuth credential, when this is one.
pub fn as_oauth(&self) -> Option<&OAuthCredential> {
match self {
Self::OAuth(oauth) => Some(oauth),
Self::ApiKey(_) => None,
}
}
/// Serialize for the auth file. The only sanctioned path from a secret to disk.
pub fn to_json(&self) -> Value {
let mut map = Map::new();
match self {
Self::ApiKey(api) => {
map.insert("type".into(), Value::String("api_key".into()));
map.insert("key".into(), Value::String(api.key.expose().to_string()));
if !api.env.is_empty() {
let env: Map<String, Value> = api
.env
.iter()
.map(|(name, value)| (name.clone(), Value::String(value.clone())))
.collect();
map.insert("env".into(), Value::Object(env));
}
}
Self::OAuth(oauth) => {
map.insert("type".into(), Value::String("oauth".into()));
map.insert("access".into(), Value::String(oauth.access.expose().to_string()));
map.insert("refresh".into(), Value::String(oauth.refresh.expose().to_string()));
map.insert("expires".into(), Value::Number(oauth.expires_at_ms.into()));
insert_opt(&mut map, "account", oauth.account.as_deref());
insert_opt(&mut map, "endpoint", oauth.endpoint.as_deref());
insert_opt(&mut map, "enterprise_domain", oauth.enterprise_domain.as_deref());
if !oauth.available_models.is_empty() {
map.insert(
"available_models".into(),
Value::Array(
oauth
.available_models
.iter()
.map(|id| Value::String(id.clone()))
.collect(),
),
);
}
}
}
Value::Object(map)
}
/// Parse one auth-file entry, returning `None` for anything that isn't a credential.
///
/// Tolerant on purpose: an entry missing its `type` but carrying a `key` is an api-key
/// credential (that is how a hand-written file usually looks), and an unrecognized shape is
/// skipped rather than allowed to sink the whole file.
pub fn from_json(value: &Value) -> Option<Self> {
let map = value.as_object()?;
let tag = map.get("type").and_then(Value::as_str).map(str::to_ascii_lowercase);
match tag.as_deref() {
Some("oauth") => {
let access = map.get("access").and_then(Value::as_str)?;
let refresh = map.get("refresh").and_then(Value::as_str).unwrap_or_default();
// the refresh token never rides a header, so this is where it becomes known
for token in [access, refresh] {
luxe_core::redact::process_secrets().add(token);
}
Some(Self::OAuth(OAuthCredential {
access: ApiKey::new(access),
refresh: ApiKey::new(refresh),
expires_at_ms: map.get("expires").and_then(Value::as_u64).unwrap_or(0),
account: string_field(map, "account"),
endpoint: string_field(map, "endpoint"),
enterprise_domain: string_field(map, "enterprise_domain"),
available_models: map
.get("available_models")
.and_then(Value::as_array)
.map(|ids| {
ids.iter().filter_map(Value::as_str).map(str::to_string).collect()
})
.unwrap_or_default(),
}))
}
Some("api_key") | None => {
let key = map.get("key").and_then(Value::as_str)?;
// a `$VAR` or `!command` spec is not the key; it is remembered once resolved
if !key.starts_with(['$', '!']) {
luxe_core::redact::process_secrets().add(key);
}
let env = map
.get("env")
.and_then(Value::as_object)
.map(|env| {
env.iter()
.filter_map(|(name, value)| {
value.as_str().map(|value| (name.clone(), value.to_string()))
})
.collect()
})
.unwrap_or_default();
Some(Self::ApiKey(ApiKeyCredential { key: ApiKey::new(key), env }))
}
Some(_) => None,
}
}
}
fn insert_opt(map: &mut Map<String, Value>, key: &str, value: Option<&str>) {
if let Some(value) = value.filter(|value| !value.is_empty()) {
map.insert(key.to_string(), Value::String(value.to_string()));
}
}
fn string_field(map: &Map<String, Value>, key: &str) -> Option<String> {
map.get(key).and_then(Value::as_str).filter(|value| !value.is_empty()).map(str::to_string)
}
/// Unix milliseconds now — the clock every expiry is measured against.
pub fn now_ms() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|elapsed| elapsed.as_millis() as u64)
.unwrap_or(0)
}
#[cfg(test)]
mod tests {
use super::*;
/// Both tokens of a stored OAuth login, and a stored key, are remembered on load: the refresh
/// token never rides a header, and `cat auth.json` must not hand any of them to the model.
#[test]
fn a_loaded_oauth_login_is_remembered_for_redaction() {
let json = serde_json::json!({"type": "oauth", "access": "access-plain-8812",
"refresh": "refresh-plain-8812", "expires": 1});
Credential::from_json(&json).unwrap();
let seen =
luxe_core::redact::process_secrets().redact("access-plain-8812 refresh-plain-8812");
assert_eq!(seen, "[REDACTED] [REDACTED]");
// a stored key is too, before any request uses it; a spec for one is not the key
Credential::from_json(&serde_json::json!({"type": "api_key", "key": "stored-plain-8812"}));
Credential::from_json(&serde_json::json!({"type": "api_key", "key": "$OPENAI_API_KEY"}));
let seen = luxe_core::redact::process_secrets().redact("stored-plain-8812 $OPENAI_API_KEY");
assert_eq!(seen, "[REDACTED] $OPENAI_API_KEY");
}
#[test]
fn api_key_round_trips_with_the_real_secret() {
let mut env = BTreeMap::new();
env.insert("AZURE_DEPLOYMENT".to_string(), "gpt5".to_string());
let credential =
Credential::ApiKey(ApiKeyCredential { key: ApiKey::new("sk-live"), env: env.clone() });
let json = credential.to_json();
assert_eq!(json["type"], "api_key");
assert_eq!(json["key"], "sk-live", "the store must write the real key, not [REDACTED]");
assert_eq!(json["env"]["AZURE_DEPLOYMENT"], "gpt5");
let back = Credential::from_json(&json).expect("parses back");
match back {
Credential::ApiKey(api) => {
assert_eq!(api.key.expose(), "sk-live");
assert_eq!(api.env, env);
}
Credential::OAuth(_) => panic!("kind changed"),
}
}
#[test]
fn oauth_round_trips_every_field() {
let credential = Credential::OAuth(OAuthCredential {
access: ApiKey::new("tid=abc;proxy-ep=proxy.individual.githubcopilot.com"),
refresh: ApiKey::new("gho_refresh"),
expires_at_ms: 1_785_964_482_483,
account: Some("octocat".into()),
endpoint: Some("https://api.individual.githubcopilot.com".into()),
enterprise_domain: None,
available_models: vec!["gpt-5.6-sol".into(), "claude-sonnet-5".into()],
});
let json = credential.to_json();
assert_eq!(json["expires"], 1_785_964_482_483u64);
assert!(json.get("enterprise_domain").is_none(), "absent fields stay absent");
let back = Credential::from_json(&json).expect("parses back");
let oauth = back.as_oauth().expect("still oauth");
assert_eq!(oauth.refresh.expose(), "gho_refresh");
assert_eq!(oauth.account.as_deref(), Some("octocat"));
assert_eq!(oauth.available_models.len(), 2);
assert_eq!(back.info().kind, CredentialKind::OAuth);
assert_eq!(back.info().expires_at_ms, Some(1_785_964_482_483));
}
#[test]
fn a_bare_key_entry_parses_as_an_api_key() {
// How a hand-written file usually looks: no `type` tag at all.
let credential = Credential::from_json(&serde_json::json!({ "key": "sk-hand-written" }))
.expect("tolerated");
assert_eq!(credential.kind(), CredentialKind::ApiKey);
}
#[test]
fn unrecognizable_entries_are_skipped_not_guessed() {
assert!(Credential::from_json(&serde_json::json!({ "type": "webauthn" })).is_none());
assert!(Credential::from_json(&serde_json::json!({ "type": "oauth" })).is_none());
assert!(Credential::from_json(&serde_json::json!({ "unrelated": true })).is_none());
assert!(Credential::from_json(&serde_json::json!("a string")).is_none());
}
#[test]
fn debug_never_prints_a_secret() {
let credential = Credential::api_key("sk-super-secret");
let rendered = format!("{credential:?}");
assert!(!rendered.contains("sk-super-secret"), "leaked in Debug: {rendered}");
assert!(rendered.contains("REDACTED"));
}
}

View File

@@ -0,0 +1,343 @@
//! Deployments — what an Azure resource serves, asked of the resource.
//!
//! The models.dev `azure` catalog lists every model Azure *offers*. A resource serves only what
//! somebody deployed on it, under whatever name they picked, so a picker built from the catalog
//! offers models the resource has never heard of: `claude-opus-5-5` beside a resource that has
//! `claude-opus-5`. The resource is the only authority, the same way a local server is for what it
//! has loaded, and its answer is recorded as the provider's `served_models`.
//!
//! The answer comes from the data-plane `GET /openai/deployments`. Newer API versions dropped that
//! route and only the oldest still answers, on a Foundry resource too, where it lists the Claude and
//! partner deployments beside OpenAI's. It may go away. When it does, the list recorded last
//! stands, and `served_models` is still the way to write one by hand.
use std::collections::BTreeMap;
use super::catalog::ProviderDescriptor;
use super::source::RequestAuth;
/// The one API version the listing still answers at.
///
/// `2023-03-15-preview` answers too; everything after `2023-05-15` returns 404.
pub const API_VERSION: &str = "2022-12-01";
/// One deployment on a resource.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Deployment {
/// What a request names: the deployment, which is not always the model
pub name: String,
/// The model it runs, as Azure spells it (`DeepSeek-V4-Flash`, `claude-opus-5`)
pub model: String,
}
/// Why a resource did not say what it serves.
#[derive(Debug, thiserror::Error)]
pub enum DeploymentsError {
/// Nothing answered.
#[error("could not reach {url}: {message}")]
Network {
/// The listing URL
url: String,
/// What the transport said
message: String,
},
/// The resource answered, and refused the credential.
#[error("the resource refused the credential ({0})")]
Rejected(u16),
/// The resource answered with anything else: the route is gone, or this kind of resource
/// never had it.
#[error("the resource has no deployment listing ({0})")]
Unsupported(u16),
}
/// What one provider on a resource serves, out of everything deployed there.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Served {
/// Deployment names, in the order the picker should offer them
pub models: Vec<String>,
/// Deployment name → model, for the deployments named something else
pub deployments: BTreeMap<String, String>,
}
/// The listing URL for a resource, from any base URL configured under it.
///
/// Cut at the first `/openai` or `/anthropic` path segment, because that is where a resource's
/// APIs hang, whichever of them the base URL happens to be. `None` for something that is not a URL.
pub fn listing_url(base_url: &str) -> Option<String> {
let mut url = reqwest::Url::parse(base_url.trim()).ok()?;
let segments: Vec<String> =
url.path_segments().map(|parts| parts.map(str::to_string).collect()).unwrap_or_default();
let root = segments
.iter()
.position(|segment| matches!(segment.as_str(), "openai" | "anthropic"))
.unwrap_or(segments.len());
let prefix: Vec<&str> =
segments[..root].iter().map(String::as_str).filter(|part| !part.is_empty()).collect();
let path = match prefix.is_empty() {
true => "/openai/deployments".to_string(),
false => format!("/{}/openai/deployments", prefix.join("/")),
};
url.set_path(&path);
url.set_query(Some(&format!("api-version={API_VERSION}")));
url.set_fragment(None);
Some(url.to_string())
}
/// Ask a resource what it has deployed.
///
/// Times out with the shared client's own limits; a caller probing in the background races it
/// against something shorter.
pub async fn list(url: &str, auth: &RequestAuth) -> Result<Vec<Deployment>, DeploymentsError> {
let request = crate::http::shared_client().get(url).header("Accept", "application/json");
let response = auth.apply(request).send().await.map_err(|error| DeploymentsError::Network {
url: url.to_string(),
message: error.to_string(),
})?;
let status = response.status();
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
return Err(DeploymentsError::Rejected(status.as_u16()));
}
if !status.is_success() {
return Err(DeploymentsError::Unsupported(status.as_u16()));
}
let body = response.text().await.map_err(|error| DeploymentsError::Network {
url: url.to_string(),
message: error.to_string(),
})?;
Ok(parse(&body))
}
/// The usable deployments in a listing, sorted by name.
///
/// A deployment still creating, failed or being deleted cannot answer a request, so only
/// `succeeded` ones count. One with no status is kept: the field is the listing's, not the
/// deployment's, and its absence says nothing.
pub fn parse(body: &str) -> Vec<Deployment> {
let Ok(value) = serde_json::from_str::<serde_json::Value>(body) else { return Vec::new() };
let rows = value.get("data").and_then(serde_json::Value::as_array);
let mut found: Vec<Deployment> = rows
.into_iter()
.flatten()
.filter(|row| {
row.get("status")
.and_then(serde_json::Value::as_str)
.is_none_or(|status| status.eq_ignore_ascii_case("succeeded"))
})
.filter_map(|row| {
let name = row.get("id")?.as_str()?.trim();
let model = row.get("model").and_then(serde_json::Value::as_str).unwrap_or(name).trim();
(!name.is_empty()).then(|| Deployment { name: name.into(), model: model.into() })
})
.collect();
found.sort_by_key(|deployment| deployment.name.to_ascii_lowercase());
found
}
/// Model-name fragments of deployments that cannot hold a conversation.
///
/// A resource carries speech, image and embedding deployments beside its chat ones, and the
/// catalog does not know all of them (`gpt-realtime-2` is not in it at all), so the name is the
/// evidence that is always there.
const NOT_CHAT: &[&str] =
&["realtime", "transcribe", "tts", "whisper", "embedding", "dall-e", "sora", "-image", "audio"];
/// Whether a deployment of `model` can hold a conversation.
///
/// Judged by name first, then by the catalog where it knows the model and says it writes no text.
/// A model the catalog marks as unable to call tools is kept: somebody deployed it, and the
/// endpoint is a better judge of what it serves than a catalog flag.
pub fn is_chat(model: &str, models_dev: Option<&str>) -> bool {
let lower = model.to_ascii_lowercase();
if lower.starts_with("gpt-image") || NOT_CHAT.iter().any(|fragment| lower.contains(fragment)) {
return false;
}
let Some(known) = models_dev.and_then(|id| crate::catalog::snapshot().model(id, &lower)) else {
return true;
};
known.modalities.as_ref().is_none_or(|modalities| {
modalities.output.is_empty() || modalities.output.iter().any(|kind| kind == "text")
})
}
/// The providers one resource is reached through: `descriptor` and the siblings its login
/// configures, the ones that can list deployments.
pub fn group(descriptor: &ProviderDescriptor) -> Vec<&ProviderDescriptor> {
std::iter::once(descriptor)
.chain(descriptor.paired_with.iter().filter_map(|id| super::provider_descriptor(id)))
.filter(|member| member.lists_deployments)
.collect()
}
/// "22 deployments: 12 OpenAI, 7 Claude, 3 partner" — the line that says discovery worked.
pub fn describe(split: &[(&str, Served)]) -> Option<String> {
let total: usize = split.iter().map(|(_, served)| served.models.len()).sum();
if total == 0 {
return None;
}
let parts: Vec<String> = split
.iter()
.filter(|(_, served)| !served.models.is_empty())
.map(|(id, served)| format!("{} on {id}", served.models.len()))
.collect();
Some(format!(
"{total} chat deployment{} on this resource ({})",
if total == 1 { "" } else { "s" },
parts.join(", ")
))
}
/// Split a resource's deployments between the providers it is reached through.
///
/// Each deployment goes to the first member that serves its **model** — never its name, which
/// can be anything. Every member gets an entry, an empty one included: a resource with no Claude
/// deployment should offer none, not fall back to the catalog's idea of Claude.
pub fn partition<'a>(
group: &[&'a ProviderDescriptor],
found: &[Deployment],
) -> Vec<(&'a str, Served)> {
let mut served: Vec<(&'a str, Served)> =
group.iter().map(|member| (&*member.id, Served::default())).collect();
for deployment in found {
let models_dev = group.first().and_then(|member| member.models_dev);
if !is_chat(&deployment.model, models_dev) {
continue;
}
let Some(at) =
group.iter().position(|member| member.served_models.serves(&deployment.model))
else {
continue;
};
let entry = &mut served[at].1;
entry.models.push(deployment.name.clone());
if !deployment.name.eq_ignore_ascii_case(&deployment.model) {
entry.deployments.insert(deployment.name.clone(), deployment.model.clone());
}
}
served
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
use crate::auth::provider_descriptor;
/// Copied from a real Foundry resource's answer, trimmed to the rows that each make a point.
const LISTING: &str = r#"{
"data": [
{"scale_settings": {"scale_type": "standard"}, "model": "gpt-4.1", "owner": "organization-owner",
"id": "gpt-4.1", "status": "succeeded", "created_at": 1764578474, "updated_at": 1771687684,
"object": "deployment"},
{"model": "gpt-chat-latest", "id": "gpt-5.1-chat", "status": "succeeded", "object": "deployment"},
{"model": "gpt-realtime", "id": "gpt-realtime", "status": "succeeded", "object": "deployment"},
{"model": "gpt-4o-mini-transcribe", "id": "gpt-4o-mini-transcribe", "status": "succeeded", "object": "deployment"},
{"model": "gpt-4o-mini-tts", "id": "gpt-4o-mini-tts", "status": "succeeded", "object": "deployment"},
{"model": "gpt-image-2", "id": "gpt-image-2", "status": "succeeded", "object": "deployment"},
{"model": "Kimi-K2.5", "id": "Kimi-K2-Thinking", "status": "succeeded", "object": "deployment"},
{"model": "claude-opus-5", "id": "claude-opus-5", "status": "succeeded", "object": "deployment"},
{"model": "claude-sonnet-5", "id": "claude-sonnet-5", "status": "creating", "object": "deployment"},
{"model": "gpt-5.6-sol", "id": "gpt-5.6-sol", "status": "succeeded", "object": "deployment"},
{"model": "DeepSeek-V4-Flash", "id": "DeepSeek-V4-Flash", "status": "succeeded", "object": "deployment"}
],
"object": "list"
}"#;
fn foundry() -> Vec<&'static ProviderDescriptor> {
["foundry-openai", "foundry-anthropic", "foundry-completions"]
.iter()
.map(|id| provider_descriptor(id).unwrap())
.collect()
}
fn served<'a>(split: &'a [(&str, Served)], id: &str) -> &'a Served {
&split.iter().find(|(provider, _)| *provider == id).unwrap().1
}
#[test]
fn the_listing_hangs_off_the_resource_root_whatever_the_base_url() {
let expected = format!(
"https://acme.services.ai.azure.com/openai/deployments?api-version={API_VERSION}"
);
for base in [
"https://acme.services.ai.azure.com/openai/v1",
"https://acme.services.ai.azure.com/anthropic/v1",
"https://acme.services.ai.azure.com/openai/v1/",
"https://acme.services.ai.azure.com",
] {
assert_eq!(listing_url(base).as_deref(), Some(expected.as_str()), "{base}");
}
// A resource named after an API keeps its name: the cut is a path segment, not a substring
assert_eq!(
listing_url("https://openai-eastus.openai.azure.com/openai/v1").unwrap(),
format!("https://openai-eastus.openai.azure.com/openai/deployments?api-version={API_VERSION}")
);
// A gateway in front of the resource keeps its own path prefix
assert_eq!(
listing_url("https://gw.example/azure/openai/v1").unwrap(),
format!("https://gw.example/azure/openai/deployments?api-version={API_VERSION}")
);
assert_eq!(listing_url("not a url"), None);
}
#[test]
fn only_deployments_that_can_answer_are_listed() {
let found = parse(LISTING);
let names: Vec<&str> = found.iter().map(|d| d.name.as_str()).collect();
assert!(!names.contains(&"claude-sonnet-5"), "still creating");
assert!(names.contains(&"Kimi-K2-Thinking"));
let kimi = found.iter().find(|d| d.name == "Kimi-K2-Thinking").unwrap();
assert_eq!(kimi.model, "Kimi-K2.5", "the model, not the name");
assert!(parse("<html>").is_empty());
assert!(parse(r#"{"error": {"code": "404"}}"#).is_empty());
}
#[test]
fn speech_image_and_embedding_deployments_are_not_offered() {
for model in [
"gpt-realtime",
"gpt-realtime-2",
"gpt-4o-mini-transcribe",
"gpt-4o-mini-tts",
"gpt-image-2",
"text-embedding-3-large",
"dall-e-3",
] {
assert!(!is_chat(model, Some("azure")), "{model}");
}
for model in ["gpt-4.1", "claude-opus-5", "DeepSeek-V4-Flash", "FW-Kimi-K3", "my-model"] {
assert!(is_chat(model, Some("azure")), "{model}");
}
}
#[test]
fn each_deployment_goes_to_the_surface_that_serves_its_model() {
let split = partition(&foundry(), &parse(LISTING));
assert_eq!(
served(&split, "foundry-openai").models,
["gpt-4.1", "gpt-5.1-chat", "gpt-5.6-sol"]
);
assert_eq!(served(&split, "foundry-anthropic").models, ["claude-opus-5"]);
assert_eq!(
served(&split, "foundry-completions").models,
["DeepSeek-V4-Flash", "Kimi-K2-Thinking"],
"the model decides, in any case: Kimi-K2-Thinking runs Kimi-K2.5"
);
assert_eq!(
served(&split, "foundry-openai").deployments,
BTreeMap::from([("gpt-5.1-chat".to_string(), "gpt-chat-latest".to_string())])
);
assert_eq!(
served(&split, "foundry-completions").deployments,
BTreeMap::from([("Kimi-K2-Thinking".to_string(), "Kimi-K2.5".to_string())]),
"a deployment named for its model needs no entry"
);
}
#[test]
fn a_surface_with_nothing_deployed_offers_nothing() {
let only_gpt = parse(r#"{"data": [{"id": "gpt-4.1", "model": "gpt-4.1"}]}"#);
let split = partition(&foundry(), &only_gpt);
assert_eq!(split.len(), 3, "every member is answered for");
assert!(served(&split, "foundry-anthropic").models.is_empty());
}
}

View File

@@ -0,0 +1,403 @@
//! OAuth — PKCE, the loopback callback, device-code polling, and the subscription flows.
//!
//! Three flows ship:
//! [`openai_codex`] for a ChatGPT Plus/Pro plan, [`github_copilot`] for a Copilot subscription, and
//! [`openrouter`], whose published flow mints an API key the user owns. Everything they share —
//! PKCE and a localhost callback that also works over SSH (from [`luxe_core::oauth_loopback`],
//! which MCP shares too), and an RFC 8628 poller — lives here. Anthropic and Google stay API-key-only
//! because their subscription terms prohibit these third-party flows.
//!
//! Every flow is cancellable by dropping its future: the callback listener closes with the server
//! value, and the poller checks for cancellation between attempts.
pub mod github_copilot;
pub mod openai_codex;
pub mod openrouter;
use std::time::Duration;
// The poller's deadline rides tokio's clock, not `std::time::Instant`: `tokio::time::pause()` moves
// one and not the other, and a test that has to sleep through a 15-minute device-code window in
// real time is a test nobody runs.
use tokio::time::Instant;
use base64::Engine as _;
use luxe_core::auth::{AuthError, AuthInteraction, AuthPrompt};
use luxe_core::oauth_loopback::{LoopbackCallback, LoopbackError};
use serde_json::Value;
use super::catalog::OauthFlow;
use super::credential::{Credential, OAuthCredential};
/// Run a subscription login and return the credential to store.
pub async fn login(
flow: OauthFlow,
interaction: &dyn AuthInteraction,
) -> Result<Credential, AuthError> {
match flow {
OauthFlow::OpenaiCodex => openai_codex::login(interaction).await.map(Credential::OAuth),
OauthFlow::GithubCopilot => github_copilot::login(interaction).await.map(Credential::OAuth),
// OpenRouter hands back a durable key, not a token pair, so it is stored as an api key.
OauthFlow::OpenRouter => openrouter::login(interaction).await,
}
}
/// Exchange a refresh token for a fresh access token.
pub async fn refresh(
flow: OauthFlow,
credential: &OAuthCredential,
) -> Result<OAuthCredential, AuthError> {
match flow {
OauthFlow::OpenaiCodex => openai_codex::refresh(credential).await,
OauthFlow::GithubCopilot => github_copilot::refresh(credential).await,
OauthFlow::OpenRouter => Err(AuthError::Protocol(
"OpenRouter credentials are API keys and don't refresh".to_string(),
)),
}
}
// === PKCE, state and the loopback callback ===
pub use luxe_core::oauth_loopback::{pkce, random_state, Pkce};
/// What the provider sent back to the loopback listener.
#[derive(Debug, Clone)]
pub struct Callback {
/// The authorization code.
pub code: String,
/// The `state` value the provider echoed, when it sent one.
pub state: Option<String>,
}
/// A one-shot localhost listener for an OAuth redirect, over [`luxe_core::oauth_loopback`].
///
/// Dropping it closes the socket, which is how a cancelled login stops listening.
pub struct CallbackServer {
redirect_uri: String,
receiver: tokio::sync::oneshot::Receiver<Result<Callback, String>>,
task: tokio::task::JoinHandle<()>,
}
impl CallbackServer {
/// Listen on `localhost:port` (`0` for any free port) for one redirect on `path`.
///
/// `localhost`, not `127.0.0.1`: providers register the literal string, and OpenAI's registered
/// Codex redirect is `http://localhost:1455/auth/callback`. With `expected_state`, a redirect
/// carrying any other state is someone else's and is ignored; the code is never exchanged.
pub async fn bind(
port: u16,
path: &str,
expected_state: Option<String>,
) -> Result<Self, LoopbackError> {
let callback = LoopbackCallback::bind(&format!("http://localhost:{port}{path}")).await?;
let redirect_uri = callback.redirect_uri().to_string();
let (sender, receiver) = tokio::sync::oneshot::channel();
let task = tokio::spawn(async move {
let Ok(arrival) = callback.wait(expected_state.as_deref()).await else { return };
let result = match (arrival.error().map(str::to_string), arrival.param("code")) {
(Some(message), _) => Err(message),
(None, Some(code)) => {
let state = arrival.param("state").map(str::to_string);
Ok(Callback { code: code.to_string(), state })
}
(None, None) => Err("the redirect carried no authorization code".to_string()),
};
match &result {
Ok(_) => {
let message = "You can close this tab and return to the terminal.";
arrival.answer(200, "Signed in to Luxe", message).await;
}
Err(message) => {
let message = format!("Authorization failed: {message}");
arrival.answer(400, "Luxe couldn't finish the sign-in", &message).await;
}
}
let _ = sender.send(result);
});
Ok(Self { redirect_uri, receiver, task })
}
/// The redirect URI to send the provider.
pub fn redirect_uri(&self) -> String {
self.redirect_uri.clone()
}
/// Wait for the redirect. `None` means the listener stopped without one.
pub async fn wait(&mut self) -> Option<Result<Callback, String>> {
(&mut self.receiver).await.ok()
}
}
impl Drop for CallbackServer {
fn drop(&mut self) {
self.task.abort();
}
}
/// Parse whatever the user pasted when the browser couldn't reach the loopback.
///
/// Accepts the full redirect URL, a bare code, `code#state` (some providers render it that way), or
/// a raw query string. Returning the state lets the caller reject a mismatch.
pub fn parse_pasted_code(input: &str) -> Option<Callback> {
let value = input.trim();
if value.is_empty() {
return None;
}
if let Ok(url) = reqwest::Url::parse(value) {
if url.scheme().starts_with("http") {
let mut code = None;
let mut state = None;
for (key, item) in url.query_pairs() {
match key.as_ref() {
"code" => code = Some(item.into_owned()),
"state" => state = Some(item.into_owned()),
_ => {}
}
}
return code.map(|code| Callback { code, state });
}
}
if value.contains("code=") {
let query = value.split_once('?').map(|(_, query)| query).unwrap_or(value);
let mut code = None;
let mut state = None;
for pair in query.split('&') {
match pair.split_once('=') {
Some(("code", value)) => code = Some(value.to_string()),
Some(("state", value)) => state = Some(value.to_string()),
_ => {}
}
}
return code.map(|code| Callback { code, state });
}
match value.split_once('#') {
Some((code, state)) if !code.is_empty() => {
Some(Callback { code: code.to_string(), state: Some(state.to_string()) })
}
_ => Some(Callback { code: value.to_string(), state: None }),
}
}
/// Race the loopback listener against a paste prompt, so a login works whether or not the browser
/// can reach this machine.
///
/// Whichever arrives first wins; the loser's future is dropped. A front-end treats the next
/// [`luxe_core::auth::AuthEvent`] as superseding the prompt it was showing, which is why the caller
/// emits a progress event straight after this returns.
pub async fn await_code(
server: &mut CallbackServer,
interaction: &dyn AuthInteraction,
expected_state: Option<&str>,
) -> Result<Callback, AuthError> {
let prompt = AuthPrompt::text(
"Finish in the browser, or paste the redirect URL / code here:",
Some(server.redirect_uri()),
);
let callback = tokio::select! {
received = server.wait() => match received {
Some(Ok(callback)) => callback,
Some(Err(message)) => return Err(AuthError::Rejected(message)),
None => return Err(AuthError::Timeout(
"the browser redirect never arrived".to_string(),
)),
},
pasted = interaction.prompt(prompt) => {
let answer = pasted?;
parse_pasted_code(secrecy::ExposeSecret::expose_secret(&answer)).ok_or_else(|| {
AuthError::Input("that doesn't contain an authorization code".to_string())
})?
}
};
if let (Some(expected), Some(actual)) = (expected_state, callback.state.as_deref()) {
if expected != actual {
return Err(AuthError::Rejected(
"OAuth state mismatch — start the sign-in again".to_string(),
));
}
}
Ok(callback)
}
// === Device code polling ===
/// One poll's outcome.
#[derive(Debug)]
pub enum Poll<T> {
/// Authorized.
Done(T),
/// Still waiting on the user.
Pending,
/// The server asked us to back off; carries a new interval when it supplied one.
SlowDown(Option<u64>),
/// Terminal failure.
Failed(String),
}
/// How a device-code flow is paced.
#[derive(Debug, Clone, Copy)]
pub struct DevicePacing {
/// Seconds between polls, as the server asked.
pub interval_secs: u64,
/// Seconds until the user code expires.
pub expires_in_secs: u64,
/// Whether to wait one interval before the first poll (GitHub rejects an immediate one).
pub wait_first: bool,
}
/// RFC 8628 minimum: a server that omits `interval` means five seconds.
const DEFAULT_INTERVAL_SECS: u64 = 5;
/// RFC 8628 §3.5: `slow_down` means add five seconds.
const SLOW_DOWN_STEP_SECS: u64 = 5;
/// Poll until the user authorizes, the code expires, or the server refuses.
///
/// `poll` is called on each attempt. Honors a server-supplied `slow_down` interval in preference to
/// our own bookkeeping — a VM with a drifting clock otherwise polls early forever and never
/// finishes.
pub async fn poll_device_code<T, F, Fut>(pacing: DevicePacing, mut poll: F) -> Result<T, AuthError>
where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = Poll<T>>,
{
let deadline = Instant::now() + Duration::from_secs(pacing.expires_in_secs.max(1));
let mut interval = Duration::from_secs(pacing.interval_secs.max(1).max(DEFAULT_INTERVAL_SECS));
let mut slowed = false;
if pacing.wait_first {
tokio::time::sleep(interval.min(deadline.saturating_duration_since(Instant::now()))).await;
}
while Instant::now() < deadline {
match poll().await {
Poll::Done(value) => return Ok(value),
Poll::Failed(message) => return Err(AuthError::Rejected(message)),
Poll::SlowDown(server_interval) => {
slowed = true;
interval = match server_interval {
Some(secs) if secs > 0 => Duration::from_secs(secs),
_ => interval + Duration::from_secs(SLOW_DOWN_STEP_SECS),
};
}
Poll::Pending => {}
}
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
break;
}
tokio::time::sleep(interval.min(remaining)).await;
}
Err(AuthError::Timeout(if slowed {
"the sign-in timed out after the server asked us to slow down — if this machine's clock is \
off (common in VMs and WSL), sync it and try again"
.to_string()
} else {
"the sign-in code expired before it was authorized".to_string()
}))
}
// === HTTP helpers ===
/// POST a JSON body and parse a JSON response, with the status folded into the error.
pub async fn post_json(url: &str, body: Value) -> Result<Value, AuthError> {
let response = crate::http::shared_client()
.post(url)
.header("Accept", "application/json")
.json(&body)
.send()
.await
.map_err(|error| AuthError::Network(format!("{url}: {error}")))?;
read_json(url, response).await
}
/// POST a form body and parse a JSON response.
pub async fn post_form(url: &str, form: &[(&str, &str)]) -> Result<Value, AuthError> {
let response = crate::http::shared_client()
.post(url)
.header("Accept", "application/json")
.form(form)
.send()
.await
.map_err(|error| AuthError::Network(format!("{url}: {error}")))?;
read_json(url, response).await
}
/// Read a JSON body, treating a non-2xx as an error that names the provider's own message.
pub async fn read_json(url: &str, response: reqwest::Response) -> Result<Value, AuthError> {
let status = response.status();
let text = response
.text()
.await
.map_err(|error| AuthError::Network(format!("{url}: reading the response: {error}")))?;
let parsed: Option<Value> = serde_json::from_str(&text).ok();
if !status.is_success() {
let detail = parsed
.as_ref()
.and_then(provider_error_message)
.unwrap_or_else(|| truncate(&text, 300));
return Err(AuthError::Rejected(format!("{url} returned {status}: {detail}")));
}
parsed.ok_or_else(|| {
AuthError::Protocol(format!("{url} did not return JSON: {}", truncate(&text, 300)))
})
}
/// Pull the human-readable part out of an OAuth error body.
pub fn provider_error_message(body: &Value) -> Option<String> {
let field = |key: &str| body.get(key).and_then(Value::as_str).map(str::to_string);
field("error_description")
.or_else(|| body.get("error").and_then(Value::as_str).map(str::to_string))
.or_else(|| {
body.get("error")
.and_then(|error| error.get("message"))
.and_then(Value::as_str)
.map(str::to_string)
})
.or_else(|| field("message"))
}
/// The machine-readable OAuth error code, when the body has one.
pub fn provider_error_code(body: &Value) -> Option<String> {
body.get("error")
.and_then(|error| {
error
.as_str()
.map(str::to_string)
.or_else(|| error.get("code").and_then(Value::as_str).map(str::to_string))
})
.map(|code| code.trim().to_string())
}
fn truncate(text: &str, max: usize) -> String {
let trimmed = text.trim();
if trimmed.chars().count() <= max {
return trimmed.to_string();
}
let cut: String = trimmed.chars().take(max).collect();
format!("{cut}…")
}
/// Decode a JWT payload without verifying it.
///
/// Only ever used to read a claim the provider put there for us (the ChatGPT account id). The token
/// is opaque to Luxe otherwise; we are not making a trust decision on it.
pub fn decode_jwt_payload(token: &str) -> Option<Value> {
let payload = token.split('.').nth(1)?;
let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(payload)
.or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(payload))
.ok()?;
serde_json::from_slice(&bytes).ok()
}
/// Milliseconds since the epoch for a token that expires in `expires_in` seconds, minus a safety
/// margin so a token can't die between the check and the request.
pub fn expiry_from_expires_in(expires_in_secs: u64) -> u64 {
const MARGIN_MS: u64 = 5 * 60 * 1000;
let lifetime_ms = expires_in_secs.saturating_mul(1000);
super::credential::now_ms() + lifetime_ms.saturating_sub(MARGIN_MS.min(lifetime_ms / 2))
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,349 @@
//! GitHub Copilot — device flow, then a Copilot token exchange.
//!
//! Two tokens are in play. The device flow yields a long-lived **GitHub** token, which is what gets
//! stored as the refresh token; exchanging it at `copilot_internal/v2/token` yields a short-lived
//! **Copilot** token that requests actually carry. "Refresh" is therefore a re-exchange, not an
//! OAuth refresh grant.
//!
//! The Copilot token also encodes the endpoint this account must use (`proxy-ep=…`), which is why
//! `crate::auth::source` lets a credential override the adapter's base URL. Enterprise accounts go
//! through their own domain end to end.
use std::collections::BTreeMap;
mod models;
mod usage;
use luxe_core::auth::{AuthChoice, AuthError, AuthEvent, AuthInteraction, AuthPrompt};
use secrecy::ExposeSecret;
use serde_json::Value;
use super::super::credential::OAuthCredential;
use super::{post_form, provider_error_code, provider_error_message, DevicePacing, Poll};
use crate::config::ApiKey;
use models::{enable_and_list_models, fetch_models};
#[cfg(test)]
pub(crate) use usage::parse_plan_usage;
pub use usage::plan_usage;
/// GitHub's own editor-integration client id (public; a device-flow client has no secret).
const CLIENT_ID: &str = "Iv1.b507a08c87ecfe98";
/// Scope the editor integrations request.
const SCOPE: &str = "read:user";
/// Copilot's `/models` API version.
const API_VERSION: &str = "2026-06-01";
/// Identity headers Copilot's endpoint requires. Sent on every request, not just at login.
pub const EDITOR_HEADERS: &[(&str, &str)] = &[
("Editor-Version", "vscode/1.107.0"),
("Editor-Plugin-Version", "copilot-chat/0.35.0"),
("Copilot-Integration-Id", "vscode-chat"),
];
/// Endpoint used when a token doesn't name one and the account isn't on Enterprise.
const DEFAULT_API_BASE: &str = "https://api.individual.githubcopilot.com";
/// The GitHub everyone means.
const GITHUB_COM: &str = "github.com";
/// Where the flow talks to GitHub.
///
/// A struct rather than formatted constants so tests can drive the real code against a local
/// server, and so GitHub Enterprise is the same code path as github.com.
#[derive(Debug, Clone)]
pub struct Endpoints {
/// Device-code issuance.
pub device_code: String,
/// Device-code polling.
pub access_token: String,
/// GitHub token → Copilot token exchange.
pub copilot_token: String,
}
impl Endpoints {
/// The endpoints for a GitHub domain (`github.com`, or an Enterprise host).
pub fn for_domain(domain: &str) -> Self {
Self {
device_code: format!("https://{domain}/login/device/code"),
access_token: format!("https://{domain}/login/oauth/access_token"),
copilot_token: format!("https://api.{domain}/copilot_internal/v2/token"),
}
}
}
/// Run the device flow and exchange for a Copilot token.
pub async fn login(interaction: &dyn AuthInteraction) -> Result<OAuthCredential, AuthError> {
let enterprise = choose_domain(interaction).await?;
let domain = enterprise.clone().unwrap_or_else(|| GITHUB_COM.to_string());
run_device_flow(&Endpoints::for_domain(&domain), enterprise.as_deref(), interaction).await
}
/// Ask which GitHub the subscription lives on, returning the Enterprise domain if there is one.
///
/// A question rather than a blank-for-default text box: almost everyone wants github.com, and
/// "leave it blank" is a worse way to say "yes, the normal one". Separated from the flow so the
/// question order is testable without a socket.
pub async fn choose_domain(interaction: &dyn AuthInteraction) -> Result<Option<String>, AuthError> {
let choice = interaction
.prompt(AuthPrompt::select(
"Which GitHub account is your Copilot subscription on?",
vec![
AuthChoice {
id: "github".into(),
label: "GitHub".into(),
detail: Some("github.com — the usual choice".into()),
},
AuthChoice {
id: "enterprise".into(),
label: "GitHub Enterprise".into(),
detail: Some("A GitHub Enterprise Server at your own domain".into()),
},
],
))
.await?;
if choice.expose_secret() != "enterprise" {
return Ok(None);
}
let answer = interaction
.prompt(AuthPrompt::text("GitHub Enterprise domain:", Some("company.ghe.com".to_string())))
.await?;
// Having chosen Enterprise, an empty domain is a mistake, not a default: silently falling back
// to github.com would send the credential to the wrong host.
normalize_domain(answer.expose_secret())?
.map(Some)
.ok_or_else(|| AuthError::Input("no domain entered".to_string()))
}
/// Run the device flow against `endpoints` and exchange the result for a Copilot credential.
pub async fn run_device_flow(
endpoints: &Endpoints,
enterprise: Option<&str>,
interaction: &dyn AuthInteraction,
) -> Result<OAuthCredential, AuthError> {
let device = start_device_flow(endpoints).await?;
interaction.notify(AuthEvent::DeviceCode {
user_code: device.user_code.clone(),
verification_uri: device.verification_uri.clone(),
interval_secs: device.interval_secs,
expires_in_secs: device.expires_in_secs,
});
let github_token = poll_for_github_token(endpoints, &device).await?;
interaction
.notify(AuthEvent::Progress { message: "Requesting a Copilot token…".to_string() });
let mut credential = exchange_copilot_token(endpoints, &github_token, enterprise).await?;
interaction.notify(AuthEvent::Progress { message: "Checking available models…".to_string() });
credential.available_models = enable_and_list_models(&credential).await;
Ok(credential)
}
/// Re-exchange the stored GitHub token for a fresh Copilot token.
pub async fn refresh(credential: &OAuthCredential) -> Result<OAuthCredential, AuthError> {
let domain = credential.enterprise_domain.as_deref().unwrap_or(GITHUB_COM);
let mut refreshed = exchange_copilot_token(
&Endpoints::for_domain(domain),
credential.refresh.expose(),
credential.enterprise_domain.as_deref(),
)
.await?;
// A plan's models change under it, and a list kept from login went stale both ways: it offered
// models the account had lost and hid ones it had gained. One request per token is the price.
// Listing only: accepting a model's policy stays a step the user takes, at `/login`.
refreshed.available_models =
list_models(&refreshed).await.unwrap_or_else(|| credential.available_models.clone());
Ok(refreshed)
}
/// The models this account may use now, or `None` when the list cannot be had.
async fn list_models(credential: &OAuthCredential) -> Option<Vec<String>> {
let base = credential.endpoint.clone().unwrap_or_else(|| DEFAULT_API_BASE.to_string());
let models = fetch_models(&base, credential.access.expose()).await?;
Some(models.into_iter().filter(|model| model.selectable).map(|model| model.id).collect())
}
/// One device-flow authorization request.
#[derive(Debug)]
struct DeviceFlow {
device_code: String,
user_code: String,
verification_uri: String,
interval_secs: u64,
expires_in_secs: u64,
}
async fn start_device_flow(endpoints: &Endpoints) -> Result<DeviceFlow, AuthError> {
let body =
post_form(&endpoints.device_code, &[("client_id", CLIENT_ID), ("scope", SCOPE)]).await?;
let field = |key: &str| body.get(key).and_then(Value::as_str).map(str::to_string);
let device_code = field("device_code").ok_or_else(|| missing("device_code"))?;
let user_code = field("user_code").ok_or_else(|| missing("user_code"))?;
let verification_uri = field("verification_uri").ok_or_else(|| missing("verification_uri"))?;
// The URI is handed to a browser launcher, so it has to be a real http(s) URL and not, say, a
// path to something executable.
let parsed = reqwest::Url::parse(&verification_uri)
.map_err(|_| AuthError::Protocol("GitHub returned an unusable verification URL".into()))?;
if !matches!(parsed.scheme(), "http" | "https") {
return Err(AuthError::Protocol(
"GitHub returned a verification URL that isn't http(s)".to_string(),
));
}
Ok(DeviceFlow {
device_code,
user_code,
verification_uri: parsed.to_string(),
interval_secs: body.get("interval").and_then(Value::as_u64).unwrap_or(5),
expires_in_secs: body.get("expires_in").and_then(Value::as_u64).unwrap_or(900),
})
}
async fn poll_for_github_token(
endpoints: &Endpoints,
device: &DeviceFlow,
) -> Result<String, AuthError> {
let url = endpoints.access_token.clone();
let pacing = DevicePacing {
interval_secs: device.interval_secs,
expires_in_secs: device.expires_in_secs,
// GitHub rejects a poll that arrives before the first interval has elapsed.
wait_first: true,
};
super::poll_device_code(pacing, || {
let url = url.clone();
let device_code = device.device_code.clone();
async move {
let form = [
("client_id", CLIENT_ID),
("device_code", device_code.as_str()),
("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
];
match post_form(&url, &form).await {
Ok(body) => match body.get("access_token").and_then(Value::as_str) {
Some(token) if !token.is_empty() => Poll::Done(token.to_string()),
_ => classify(&body),
},
Err(AuthError::Rejected(message)) => Poll::Failed(message),
Err(error) => Poll::Failed(error.to_string()),
}
}
})
.await
}
/// GitHub answers a pending device poll with HTTP 200 and an `error` field.
fn classify(body: &Value) -> Poll<String> {
match provider_error_code(body).as_deref() {
Some("authorization_pending") => Poll::Pending,
Some("slow_down") => Poll::SlowDown(body.get("interval").and_then(Value::as_u64)),
Some(code) => Poll::Failed(
provider_error_message(body).unwrap_or_else(|| format!("device flow failed: {code}")),
),
None => Poll::Failed("GitHub returned no token and no error".to_string()),
}
}
/// Trade a GitHub token for a Copilot token.
pub async fn exchange_copilot_token(
endpoints: &Endpoints,
github_token: &str,
enterprise_domain: Option<&str>,
) -> Result<OAuthCredential, AuthError> {
let domain = enterprise_domain.unwrap_or(GITHUB_COM);
let url = endpoints.copilot_token.clone();
let mut request = crate::http::shared_client()
.get(&url)
.header("Accept", "application/json")
.header("Authorization", format!("Bearer {github_token}"));
for (name, value) in EDITOR_HEADERS {
request = request.header(*name, *value);
}
let response =
request.send().await.map_err(|error| AuthError::Network(format!("{url}: {error}")))?;
let body = super::read_json(&url, response).await.map_err(|error| match error {
AuthError::Rejected(message) if message.contains("403") => AuthError::Rejected(format!(
"{message} — this GitHub account doesn't have an active Copilot subscription"
)),
other => other,
})?;
let token = body
.get("token")
.and_then(Value::as_str)
.filter(|token| !token.is_empty())
.ok_or_else(|| missing("token"))?;
// `expires_at` is unix *seconds*.
let expires_at_secs = body.get("expires_at").and_then(Value::as_u64).unwrap_or(0);
let expires_at_ms = match expires_at_secs {
0 => super::expiry_from_expires_in(25 * 60),
secs => secs.saturating_mul(1000).saturating_sub(5 * 60 * 1000),
};
Ok(OAuthCredential {
access: ApiKey::new(token),
refresh: ApiKey::new(github_token),
expires_at_ms,
account: token_field(token, "tid").or_else(|| Some(domain.to_string())),
endpoint: Some(api_base_url(token, enterprise_domain)),
enterprise_domain: enterprise_domain.map(str::to_string),
available_models: Vec::new(),
})
}
/// The API base this credential must use.
///
/// The Copilot token carries `proxy-ep=proxy.<tenant>.githubcopilot.com`; the REST base is the same
/// host with `api.` in place of `proxy.`. Individual, Business, and Enterprise accounts all land on
/// different hosts, and using the wrong one 401s.
pub fn api_base_url(copilot_token: &str, enterprise_domain: Option<&str>) -> String {
if let Some(proxy) = token_field(copilot_token, "proxy-ep") {
let host = proxy.strip_prefix("proxy.").map(|rest| format!("api.{rest}")).unwrap_or(proxy);
return format!("https://{host}");
}
match enterprise_domain {
Some(domain) => format!("https://copilot-api.{domain}"),
None => DEFAULT_API_BASE.to_string(),
}
}
/// Read one `key=value;` field out of a Copilot token.
fn token_field(token: &str, key: &str) -> Option<String> {
parse_token_fields(token).get(key).cloned()
}
fn parse_token_fields(token: &str) -> BTreeMap<String, String> {
token
.split(';')
.filter_map(|part| part.split_once('='))
.map(|(key, value)| (key.trim().to_string(), value.trim().to_string()))
.collect()
}
/// Normalize whatever the user typed into a bare hostname. Empty means github.com.
fn normalize_domain(input: &str) -> Result<Option<String>, AuthError> {
let trimmed = input.trim();
if trimmed.is_empty() {
return Ok(None);
}
let candidate =
if trimmed.contains("://") { trimmed.to_string() } else { format!("https://{trimmed}") };
let host = reqwest::Url::parse(&candidate)
.ok()
.and_then(|url| url.host_str().map(str::to_string))
.filter(|host| host.contains('.'));
match host {
Some(host) => Ok(Some(host)),
None => Err(AuthError::Input(format!("'{trimmed}' is not a GitHub Enterprise domain"))),
}
}
fn missing(field: &str) -> AuthError {
AuthError::Protocol(format!("GitHub's response carried no {field}"))
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,106 @@
//! Copilot models — what the account may use, and enabling the ones that are off.
use serde_json::Value;
use super::super::super::credential::OAuthCredential;
use super::{API_VERSION, DEFAULT_API_BASE, EDITOR_HEADERS};
/// List the models this account may use, enabling any that are merely unconfigured.
///
/// Copilot gates some models (Claude, Gemini) behind a per-account policy acceptance that a user
/// would otherwise have to click through in VS Code. Enabling only the ones the API reports as
/// *not yet configured* keeps this honest: nothing already disabled on purpose is re-enabled.
/// Best-effort throughout — a failure here means a shorter model list, not a failed login.
pub(super) async fn enable_and_list_models(credential: &OAuthCredential) -> Vec<String> {
let base = credential.endpoint.clone().unwrap_or_else(|| DEFAULT_API_BASE.to_string());
let Some(models) = fetch_models(&base, credential.access.expose()).await else {
return Vec::new();
};
let pending: Vec<String> =
models.iter().filter(|model| model.needs_enabling).map(|model| model.id.clone()).collect();
if !pending.is_empty() {
for id in &pending {
let enabled = enable_model(&base, credential.access.expose(), id).await;
tracing::debug!(model = %id, enabled, "copilot model policy");
}
if let Some(refreshed) = fetch_models(&base, credential.access.expose()).await {
return refreshed.into_iter().filter(|model| model.selectable).map(|m| m.id).collect();
}
}
models.into_iter().filter(|model| model.selectable).map(|model| model.id).collect()
}
/// One row of Copilot's `/models`.
#[derive(Debug, Clone)]
pub(super) struct CopilotModel {
pub(super) id: String,
/// Usable from a chat client right now.
pub(super) selectable: bool,
/// Gated behind a policy the user hasn't accepted or rejected yet.
pub(super) needs_enabling: bool,
}
pub(super) async fn fetch_models(base: &str, token: &str) -> Option<Vec<CopilotModel>> {
let url = format!("{}/models", base.trim_end_matches('/'));
let mut request = crate::http::shared_client()
.get(&url)
.header("Accept", "application/json")
.header("Authorization", format!("Bearer {token}"))
.header("X-GitHub-Api-Version", API_VERSION);
for (name, value) in EDITOR_HEADERS {
request = request.header(*name, *value);
}
let response = request.send().await.ok()?;
let body: Value = super::super::read_json(&url, response).await.ok()?;
Some(parse_models(&body))
}
pub(super) fn parse_models(body: &Value) -> Vec<CopilotModel> {
body.get("data")
.and_then(Value::as_array)
.map(|rows| rows.iter().filter_map(parse_model).collect())
.unwrap_or_default()
}
fn parse_model(row: &Value) -> Option<CopilotModel> {
let id = row.get("id").and_then(Value::as_str)?.to_string();
let picker = row.get("model_picker_enabled").and_then(Value::as_bool).unwrap_or(false);
let policy_state =
row.get("policy").and_then(|policy| policy.get("state")).and_then(Value::as_str);
let tool_calls = row
.get("capabilities")
.and_then(|caps| caps.get("supports"))
.and_then(|supports| supports.get("tool_calls"))
.and_then(Value::as_bool)
.unwrap_or(true);
let enabled = policy_state.is_none_or(|state| state == "enabled");
Some(CopilotModel {
// An agent harness can't use a model that won't call tools.
selectable: picker && enabled && tool_calls,
needs_enabling: picker
&& tool_calls
&& matches!(policy_state, Some(state) if state != "enabled" && state != "disabled"),
id,
})
}
async fn enable_model(base: &str, token: &str, model_id: &str) -> bool {
let url = format!("{}/models/{model_id}/policy", base.trim_end_matches('/'));
let mut request = crate::http::shared_client()
.post(&url)
.header("Content-Type", "application/json")
.header("Authorization", format!("Bearer {token}"))
.header("openai-intent", "chat-policy")
.header("x-interaction-type", "chat-policy");
for (name, value) in EDITOR_HEADERS {
request = request.header(*name, *value);
}
request
.json(&serde_json::json!({ "state": "enabled" }))
.send()
.await
.map(|response| response.status().is_success())
.unwrap_or(false)
}

View File

@@ -0,0 +1,139 @@
#![allow(clippy::unwrap_used)]
use super::models::parse_models;
use super::usage::unix_seconds;
use super::*;
#[test]
fn the_api_base_follows_the_tokens_proxy_endpoint() {
assert_eq!(
api_base_url("tid=1;proxy-ep=proxy.individual.githubcopilot.com;exp=2", None),
"https://api.individual.githubcopilot.com"
);
assert_eq!(
api_base_url("proxy-ep=proxy.business.githubcopilot.com", None),
"https://api.business.githubcopilot.com"
);
// A host that isn't prefixed `proxy.` is used verbatim rather than mangled.
assert_eq!(api_base_url("proxy-ep=gateway.example.com", None), "https://gateway.example.com");
// No proxy-ep: fall back per account type.
assert_eq!(api_base_url("tid=1", None), DEFAULT_API_BASE);
assert_eq!(api_base_url("tid=1", Some("ghe.acme.com")), "https://copilot-api.ghe.acme.com");
}
#[test]
fn token_fields_are_parsed_out_of_the_semicolon_soup() {
let token = "tid=abc; exp=1785964482;proxy-ep=proxy.x.githubcopilot.com ";
assert_eq!(token_field(token, "tid").as_deref(), Some("abc"));
assert_eq!(token_field(token, "exp").as_deref(), Some("1785964482"));
assert!(token_field(token, "missing").is_none());
}
#[test]
fn enterprise_domains_are_normalized_and_bad_input_is_rejected() {
assert_eq!(normalize_domain("").unwrap(), None);
assert_eq!(normalize_domain(" ").unwrap(), None);
assert_eq!(normalize_domain("company.ghe.com").unwrap().as_deref(), Some("company.ghe.com"));
assert_eq!(
normalize_domain("https://company.ghe.com/path").unwrap().as_deref(),
Some("company.ghe.com")
);
assert!(normalize_domain("not a domain").is_err());
assert!(normalize_domain("localhost").is_err(), "a bare word is a typo, not a domain");
}
#[test]
fn a_pending_device_poll_is_not_a_failure() {
assert!(matches!(
classify(&serde_json::json!({ "error": "authorization_pending" })),
Poll::Pending
));
assert!(matches!(
classify(&serde_json::json!({ "error": "slow_down", "interval": 10 })),
Poll::SlowDown(Some(10))
));
assert!(matches!(
classify(&serde_json::json!({ "error": "expired_token", "error_description": "gone" })),
Poll::Failed(message) if message == "gone"
));
assert!(matches!(classify(&serde_json::json!({})), Poll::Failed(_)));
}
#[test]
fn model_rows_are_filtered_the_way_an_agent_needs() {
let body = serde_json::json!({ "data": [
{ "id": "gpt-5.6-sol", "model_picker_enabled": true },
{ "id": "claude-sonnet-5", "model_picker_enabled": true,
"policy": { "state": "unconfigured" } },
{ "id": "banned", "model_picker_enabled": true, "policy": { "state": "disabled" } },
{ "id": "embeddings", "model_picker_enabled": false },
{ "id": "no-tools", "model_picker_enabled": true,
"capabilities": { "supports": { "tool_calls": false } } },
]});
let models = parse_models(&body);
let selectable: Vec<&str> =
models.iter().filter(|m| m.selectable).map(|m| m.id.as_str()).collect();
assert_eq!(selectable, vec!["gpt-5.6-sol"], "only usable models are offered");
let pending: Vec<&str> =
models.iter().filter(|m| m.needs_enabling).map(|m| m.id.as_str()).collect();
assert_eq!(pending, vec!["claude-sonnet-5"], "unconfigured models get enabled");
assert!(
!models.iter().any(|m| m.id == "banned" && m.needs_enabling),
"a model the user disabled on purpose must stay disabled"
);
}
#[test]
fn no_models_payload_yields_no_models_rather_than_a_panic() {
assert!(parse_models(&serde_json::json!({})).is_empty());
assert!(parse_models(&serde_json::json!({ "data": "nope" })).is_empty());
assert!(parse_models(&serde_json::json!({ "data": [{}] })).is_empty());
}
#[test]
fn editor_headers_include_the_integration_id_copilot_requires() {
let names: Vec<&str> = EDITOR_HEADERS.iter().map(|(name, _)| *name).collect();
assert!(names.contains(&"Copilot-Integration-Id"));
assert!(names.contains(&"Editor-Version"));
}
/// The record of a Copilot Pro account billed by the token, copied from a live one with its
/// ids taken out: 18.6% of the month's allowance spent, renewing on the first.
#[test]
fn the_months_allowance_is_read_off_the_account_record() {
let record = serde_json::json!({
"copilot_plan": "individual",
"quota_reset_date_utc": "2026-11-01T00:00:00.000Z",
"token_based_billing": true,
"quota_snapshots": {
"chat": { "unlimited": true, "percent_remaining": 100.0 },
"premium_interactions": {
"entitlement": 1500, "remaining": 1221, "percent_remaining": 81.4,
"overage_permitted": false, "unlimited": false, "token_based_billing": true
}
}
});
let october_8th = unix_seconds("2026-10-08T17:45:50.393Z").expect("a time");
let plan = parse_plan_usage(&record, october_8th).expect("a plan");
let window = plan.primary.expect("the monthly window");
assert!((window.used_percent - 18.6).abs() < 0.01, "{}", window.used_percent);
assert_eq!(window.window_label(), "monthly");
assert_eq!(window.reset_label().as_deref(), Some("23d 6h"));
assert_eq!(plan.plan.as_deref(), Some("individual"));
let unlimited = serde_json::json!({ "quota_snapshots": {
"premium_interactions": { "unlimited": true, "percent_remaining": 100.0 } } });
assert!(parse_plan_usage(&unlimited, october_8th).is_none(), "no limit, no meter");
assert!(parse_plan_usage(&serde_json::json!({}), october_8th).is_none());
}
#[test]
fn a_utc_timestamp_reads_as_unix_seconds() {
assert_eq!(unix_seconds("1970-01-01T00:00:00Z"), Some(0));
assert_eq!(unix_seconds("2026-11-01T00:00:00.000Z"), Some(1_793_491_200));
assert_eq!(unix_seconds("2000-03-01T12:30:15Z"), Some(951_913_815));
assert_eq!(unix_seconds("not a date"), None);
}

View File

@@ -0,0 +1,78 @@
//! Copilot plan usage — how much of the subscription is left, as GitHub reports it.
use luxe_core::provider::{PlanUsage, PlanWindow};
use serde_json::Value;
use super::{EDITOR_HEADERS, GITHUB_COM};
/// How much of the plan's monthly allowance this account has used, from GitHub's own account
/// record. `None` when the record cannot be had, or the plan has no limit to report against.
///
/// Read with the GitHub token, the same one the sign-in exchanges for Copilot tokens, from the
/// same host. Nothing about the machine goes with it.
pub async fn plan_usage(github_token: &str, enterprise_domain: Option<&str>) -> Option<PlanUsage> {
let domain = enterprise_domain.unwrap_or(GITHUB_COM);
let url = format!("https://api.{domain}/copilot_internal/user");
let mut request = crate::http::shared_client()
.get(&url)
.timeout(std::time::Duration::from_secs(5))
.header("Accept", "application/json")
.header("Authorization", format!("Bearer {github_token}"));
for (name, value) in EDITOR_HEADERS {
request = request.header(*name, *value);
}
let response = request.send().await.ok()?;
if !response.status().is_success() {
tracing::debug!(status = %response.status(), "copilot plan usage refused");
return None;
}
let body: Value = response.json().await.ok()?;
parse_plan_usage(&body, super::super::super::credential::now_ms() / 1000)
}
/// The plan usage in an account record, as of `now_secs`.
///
/// The allowance is `premium_interactions`, which on a plan billed by the token is drawn down by
/// every metered request's cost; `chat` and `completions` are unlimited on paid plans and say
/// nothing. An unlimited allowance reports no window rather than a meaningless 0%.
pub(crate) fn parse_plan_usage(body: &Value, now_secs: u64) -> Option<PlanUsage> {
let allowance = body.pointer("/quota_snapshots/premium_interactions")?;
if allowance.get("unlimited").and_then(Value::as_bool).unwrap_or(false) {
return None;
}
let remaining = allowance.get("percent_remaining").and_then(Value::as_f64)?;
let resets_in_secs = body
.get("quota_reset_date_utc")
.and_then(Value::as_str)
.and_then(unix_seconds)
.map(|reset| reset.saturating_sub(now_secs));
let window = PlanWindow {
used_percent: (100.0 - remaining).clamp(0.0, 100.0) as f32,
window_minutes: luxe_core::provider::MONTH_MINUTES,
resets_in_secs,
};
Some(PlanUsage {
plan: body.get("copilot_plan").and_then(Value::as_str).map(str::to_string),
primary: Some(window),
..PlanUsage::default()
})
}
/// Unix seconds of an RFC 3339 UTC timestamp (`2026-11-01T00:00:00.000Z`), to the second.
pub(super) fn unix_seconds(timestamp: &str) -> Option<u64> {
let (date, time) = timestamp.split_once('T')?;
let mut date = date.splitn(3, '-').map(str::parse::<i64>);
let (year, month, day) = (date.next()?.ok()?, date.next()?.ok()?, date.next()?.ok()?);
let mut clock = time.trim_end_matches('Z').splitn(3, ':');
let hour: i64 = clock.next()?.parse().ok()?;
let minute: i64 = clock.next()?.parse().ok()?;
let second: i64 = clock.next()?.split('.').next()?.parse().ok()?;
// Howard Hinnant's days-from-civil, so a date needs no calendar library
let year = if month <= 2 { year - 1 } else { year };
let era = year.div_euclid(400);
let year_of_era = year - era * 400;
let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + day - 1;
let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
let days = era * 146_097 + day_of_era - 719_468;
u64::try_from(days * 86_400 + hour * 3_600 + minute * 60 + second).ok()
}

View File

@@ -0,0 +1,487 @@
//! OpenAI Codex — signing in with a ChatGPT Plus/Pro plan.
//!
//! Two ways in, because one of them has to work on a machine with no browser:
//!
//! - **Browser** — PKCE authorization code with a loopback listener on the port OpenAI's client is
//! registered for (`1455`), raced against a paste-the-URL prompt so it also works over SSH.
//! - **Device code** — OpenAI's own device-authorization endpoints (not RFC 8628: the poll returns
//! an *authorization code plus verifier*, which then goes through the normal exchange).
//!
//! Requests afterwards go to the ChatGPT backend, not `api.openai.com`, and carry the account id
//! from the access token's claims — see `crate::auth::source` for the header derivation.
use luxe_core::auth::{AuthChoice, AuthError, AuthEvent, AuthInteraction, AuthPrompt};
use secrecy::ExposeSecret;
use serde_json::Value;
use super::super::credential::OAuthCredential;
use luxe_core::oauth_loopback::LoopbackError;
use super::{
await_code, expiry_from_expires_in, post_form, post_json, CallbackServer, DevicePacing, Poll,
};
use crate::config::ApiKey;
/// The Codex client id. Public by construction — a PKCE client has no secret.
const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
const AUTH_BASE: &str = "https://auth.openai.com";
/// Where the flow talks to OpenAI.
///
/// A struct rather than constants so the tests can drive the real code against a local server; the
/// public entry points always use [`Endpoints::default`].
#[derive(Debug, Clone)]
pub struct Endpoints {
/// Authorization page the browser opens.
pub authorize: String,
/// Token exchange and refresh.
pub token: String,
/// Device-code issuance.
pub device_usercode: String,
/// Device-code polling.
pub device_token: String,
/// Page the user types the device code into.
pub device_verification: String,
/// Redirect URI the device flow's authorization code was issued against.
pub device_redirect: String,
}
impl Default for Endpoints {
fn default() -> Self {
Self::at(AUTH_BASE)
}
}
impl Endpoints {
/// Every endpoint under one base URL.
pub fn at(base: &str) -> Self {
let base = base.trim_end_matches('/');
Self {
authorize: format!("{base}/oauth/authorize"),
token: format!("{base}/oauth/token"),
device_usercode: format!("{base}/api/accounts/deviceauth/usercode"),
device_token: format!("{base}/api/accounts/deviceauth/token"),
device_verification: format!("{base}/codex/device"),
device_redirect: format!("{base}/deviceauth/callback"),
}
}
}
/// The loopback port OpenAI's registered redirect URI uses. Not negotiable.
const CALLBACK_PORT: u16 = 1455;
const CALLBACK_PATH: &str = "/auth/callback";
const SCOPE: &str = "openid profile email offline_access";
/// Claim namespace OpenAI puts the account id under.
const AUTH_CLAIM: &str = "https://api.openai.com/auth";
/// How Luxe identifies itself to the Codex backend, unless `LUXE_CODEX_ORIGINATOR` says otherwise.
///
/// Sent on the authorize request and on every Codex call. Honest by default — Luxe says it is
/// Luxe. The override exists because this is the one value in the flow taken from another client's
/// behavior rather than from documentation: if the backend ever refuses an unknown originator, a
/// user can get working again without waiting for a release.
const DEFAULT_ORIGINATOR: &str = "luxe";
/// The originator to send.
pub fn originator() -> String {
std::env::var("LUXE_CODEX_ORIGINATOR")
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
.unwrap_or_else(|| DEFAULT_ORIGINATOR.to_string())
}
/// A device code stays valid for fifteen minutes.
const DEVICE_TIMEOUT_SECS: u64 = 15 * 60;
/// Run the login, asking which method to use.
pub async fn login(interaction: &dyn AuthInteraction) -> Result<OAuthCredential, AuthError> {
login_with(&Endpoints::default(), interaction).await
}
/// Run the login against specific endpoints.
pub async fn login_with(
endpoints: &Endpoints,
interaction: &dyn AuthInteraction,
) -> Result<OAuthCredential, AuthError> {
let choice = interaction
.prompt(AuthPrompt::select(
"How do you want to sign in?",
vec![
AuthChoice {
id: "browser".into(),
label: "Open a browser".into(),
detail: Some("Best on a desktop; you can also paste the redirect URL".into()),
},
AuthChoice {
id: "device".into(),
label: "Enter a code on another device".into(),
detail: Some("For a headless machine or an SSH session".into()),
},
],
))
.await?;
match choice.expose_secret() {
"device" => login_device_code(endpoints, interaction).await,
_ => login_browser(endpoints, interaction).await,
}
}
/// PKCE authorization-code login through a loopback listener.
async fn login_browser(
endpoints: &Endpoints,
interaction: &dyn AuthInteraction,
) -> Result<OAuthCredential, AuthError> {
let pkce = super::pkce();
let state = super::random_state();
let mut server = CallbackServer::bind(CALLBACK_PORT, CALLBACK_PATH, Some(state.clone()))
.await
.map_err(|error| match error {
LoopbackError::InUse { .. } => AuthError::Network(format!(
"{error} — OpenAI requires this exact port, so close whatever is using it (often \
the Codex CLI mid-login) and try again, or choose the device-code method"
)),
other => other.into(),
})?;
let redirect_uri = server.redirect_uri();
let url = authorize_url(endpoints, &pkce.challenge, &state, &redirect_uri);
interaction.notify(AuthEvent::OpenUrl {
url,
instructions: Some(
"Sign in with the ChatGPT account that has your Plus or Pro plan.".to_string(),
),
});
let callback = await_code(&mut server, interaction, Some(&state)).await?;
interaction
.notify(AuthEvent::Progress { message: "Exchanging the authorization code…".into() });
exchange_code(endpoints, &callback.code, &pkce.verifier, &redirect_uri).await
}
/// OpenAI's device-authorization login.
async fn login_device_code(
endpoints: &Endpoints,
interaction: &dyn AuthInteraction,
) -> Result<OAuthCredential, AuthError> {
let start =
post_json(&endpoints.device_usercode, serde_json::json!({ "client_id": CLIENT_ID }))
.await
.map_err(|error| {
match error {
AuthError::Rejected(message) if message.contains("404") => AuthError::Rejected(
"OpenAI's device-code sign-in isn't available for this account; use the browser \
method instead"
.to_string(),
),
other => other,
}
})?;
let device_auth_id = string_field(&start, "device_auth_id").ok_or_else(|| {
AuthError::Protocol("the device-code response carried no device_auth_id".to_string())
})?;
let user_code = string_field(&start, "user_code").ok_or_else(|| {
AuthError::Protocol("the device-code response carried no user_code".to_string())
})?;
let interval_secs = number_field(&start, "interval").unwrap_or(5);
interaction.notify(AuthEvent::DeviceCode {
user_code: user_code.clone(),
verification_uri: endpoints.device_verification.clone(),
interval_secs,
expires_in_secs: DEVICE_TIMEOUT_SECS,
});
let pacing =
DevicePacing { interval_secs, expires_in_secs: DEVICE_TIMEOUT_SECS, wait_first: false };
let authorized = super::poll_device_code(pacing, || {
let body = serde_json::json!({
"device_auth_id": device_auth_id,
"user_code": user_code,
});
let url = endpoints.device_token.clone();
async move {
match post_json(&url, body).await {
Ok(value) => match (
string_field(&value, "authorization_code"),
string_field(&value, "code_verifier"),
) {
(Some(code), Some(verifier)) => Poll::Done((code, verifier)),
_ => Poll::Failed(
"the device-code response carried no authorization code".to_string(),
),
},
Err(AuthError::Rejected(message)) => classify_device_error(&message),
Err(error) => Poll::Failed(error.to_string()),
}
}
})
.await?;
interaction
.notify(AuthEvent::Progress { message: "Exchanging the authorization code…".into() });
exchange_code(endpoints, &authorized.0, &authorized.1, &endpoints.device_redirect).await
}
/// Pending-vs-fatal for a device poll. OpenAI answers a not-yet-authorized poll with 403/404 as
/// often as with a proper `authorization_pending`, so both are "keep waiting".
fn classify_device_error<T>(message: &str) -> Poll<T> {
let lower = message.to_ascii_lowercase();
if lower.contains("authorization_pending")
|| lower.contains("deviceauth_authorization_pending")
|| lower.contains(" 403")
|| lower.contains(" 404")
{
return Poll::Pending;
}
if lower.contains("slow_down") {
return Poll::SlowDown(None);
}
Poll::Failed(message.to_string())
}
/// The authorization URL, with the parameters the Codex client sends.
fn authorize_url(
endpoints: &Endpoints,
challenge: &str,
state: &str,
redirect_uri: &str,
) -> String {
let Ok(mut url) = reqwest::Url::parse(&endpoints.authorize) else {
return endpoints.authorize.clone();
};
url.query_pairs_mut()
.append_pair("response_type", "code")
.append_pair("client_id", CLIENT_ID)
.append_pair("redirect_uri", redirect_uri)
.append_pair("scope", SCOPE)
.append_pair("code_challenge", challenge)
.append_pair("code_challenge_method", "S256")
.append_pair("state", state)
.append_pair("id_token_add_organizations", "true")
.append_pair("codex_cli_simplified_flow", "true")
.append_pair("originator", &originator());
url.to_string()
}
/// Trade an authorization code for tokens against specific endpoints.
pub async fn exchange_code(
endpoints: &Endpoints,
code: &str,
verifier: &str,
redirect_uri: &str,
) -> Result<OAuthCredential, AuthError> {
let body = post_form(
&endpoints.token,
&[
("grant_type", "authorization_code"),
("client_id", CLIENT_ID),
("code", code),
("code_verifier", verifier),
("redirect_uri", redirect_uri),
],
)
.await?;
credential_from_tokens(&body)
}
/// Exchange a refresh token for a new access token.
pub async fn refresh(credential: &OAuthCredential) -> Result<OAuthCredential, AuthError> {
refresh_with(&Endpoints::default(), credential).await
}
/// Refresh against specific endpoints.
pub async fn refresh_with(
endpoints: &Endpoints,
credential: &OAuthCredential,
) -> Result<OAuthCredential, AuthError> {
let body = post_form(
&endpoints.token,
&[
("grant_type", "refresh_token"),
("client_id", CLIENT_ID),
("refresh_token", credential.refresh.expose()),
],
)
.await?;
let mut refreshed = credential_from_tokens(&body)?;
// OpenAI usually rotates the refresh token; when it doesn't, keep the one we have.
if refreshed.refresh.is_empty() {
refreshed.refresh = credential.refresh.clone();
}
Ok(refreshed)
}
/// Build a credential from a token response, reading the account id out of the access token.
pub fn credential_from_tokens(body: &Value) -> Result<OAuthCredential, AuthError> {
let access = string_field(body, "access_token").ok_or_else(|| {
AuthError::Protocol("the token response carried no access_token".to_string())
})?;
let account = account_id(&access).ok_or_else(|| {
AuthError::Protocol(
"the ChatGPT token carries no account id — is this account on a Plus or Pro plan?"
.to_string(),
)
})?;
let expires_in = number_field(body, "expires_in").unwrap_or(3600);
Ok(OAuthCredential {
access: ApiKey::new(access),
refresh: ApiKey::new(string_field(body, "refresh_token").unwrap_or_default()),
expires_at_ms: expiry_from_expires_in(expires_in),
account: Some(account),
endpoint: None,
enterprise_domain: None,
available_models: Vec::new(),
})
}
/// The ChatGPT account id from an access token's claims.
pub fn account_id(access_token: &str) -> Option<String> {
let claims = super::decode_jwt_payload(access_token)?;
claims
.get(AUTH_CLAIM)?
.get("chatgpt_account_id")?
.as_str()
.filter(|id| !id.is_empty())
.map(str::to_string)
}
fn string_field(body: &Value, key: &str) -> Option<String> {
body.get(key).and_then(Value::as_str).filter(|value| !value.is_empty()).map(str::to_string)
}
/// Read a number that a provider may have encoded as a string (OpenAI's device endpoint does).
fn number_field(body: &Value, key: &str) -> Option<u64> {
let value = body.get(key)?;
value.as_u64().or_else(|| value.as_str()?.trim().parse().ok())
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
use base64::Engine as _;
/// Serializes the tests that read or write `LUXE_CODEX_ORIGINATOR`.
///
/// It is a process-global and `cargo test` runs tests as threads, so "restore it at the end of my
/// own body" is not isolation: a sibling reading `originator()` mid-flight sees whatever this test
/// last set, and the failure reads as a wrong authorize URL.
static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn jwt_with_account(account: &str) -> String {
let claims = serde_json::json!({ AUTH_CLAIM: { "chatgpt_account_id": account } });
let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
.encode(serde_json::to_vec(&claims).unwrap());
format!("header.{payload}.signature")
}
#[test]
fn the_authorize_url_carries_every_parameter_the_backend_requires() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let url = authorize_url(
&Endpoints::default(),
"chal",
"st",
"http://localhost:1455/auth/callback",
);
let parsed = reqwest::Url::parse(&url).unwrap();
let pairs: std::collections::HashMap<_, _> = parsed.query_pairs().into_owned().collect();
assert_eq!(pairs["client_id"], CLIENT_ID);
assert_eq!(pairs["response_type"], "code");
assert_eq!(pairs["code_challenge_method"], "S256");
assert_eq!(pairs["code_challenge"], "chal");
assert_eq!(pairs["state"], "st");
assert_eq!(pairs["redirect_uri"], "http://localhost:1455/auth/callback");
assert_eq!(pairs["scope"], SCOPE);
assert_eq!(pairs["originator"], originator());
assert_eq!(pairs["codex_cli_simplified_flow"], "true");
assert!(parsed.as_str().starts_with("https://auth.openai.com/oauth/authorize?"));
}
#[test]
fn the_originator_defaults_to_luxe_and_is_overridable() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let previous = std::env::var("LUXE_CODEX_ORIGINATOR").ok();
std::env::remove_var("LUXE_CODEX_ORIGINATOR");
assert_eq!(originator(), "luxe", "Luxe identifies itself honestly by default");
std::env::set_var("LUXE_CODEX_ORIGINATOR", "codex_cli_rs");
assert_eq!(originator(), "codex_cli_rs");
let url = authorize_url(&Endpoints::default(), "c", "s", "http://localhost:1455/cb");
assert!(url.contains("originator=codex_cli_rs"), "{url}");
// Blank or whitespace falls back rather than sending an empty originator.
std::env::set_var("LUXE_CODEX_ORIGINATOR", " ");
assert_eq!(originator(), "luxe");
match previous {
Some(value) => std::env::set_var("LUXE_CODEX_ORIGINATOR", value),
None => std::env::remove_var("LUXE_CODEX_ORIGINATOR"),
}
}
#[test]
fn a_token_response_becomes_a_credential_with_the_account_id() {
let body = serde_json::json!({
"access_token": jwt_with_account("acct-9"),
"refresh_token": "refresh-1",
"expires_in": 3600,
});
let credential = credential_from_tokens(&body).expect("valid");
assert_eq!(credential.account.as_deref(), Some("acct-9"));
assert_eq!(credential.refresh.expose(), "refresh-1");
assert!(credential.expires_at_ms > super::super::super::credential::now_ms());
}
/// A ChatGPT token with no account claim can't address the Codex backend, and the failure has to
/// say that rather than 400 later.
#[test]
fn a_token_without_an_account_claim_is_rejected_up_front() {
let body = serde_json::json!({ "access_token": "header.e30.sig", "expires_in": 60 });
let error = credential_from_tokens(&body).expect_err("must reject");
assert!(error.to_string().contains("account id"), "unhelpful: {error}");
}
#[test]
fn a_missing_access_token_is_a_protocol_error() {
let error = credential_from_tokens(&serde_json::json!({})).expect_err("must reject");
assert!(matches!(error, AuthError::Protocol(_)));
}
#[test]
fn account_id_is_read_from_the_claim_namespace() {
assert_eq!(account_id(&jwt_with_account("a1")).as_deref(), Some("a1"));
assert!(account_id("garbage").is_none());
assert!(account_id(&jwt_with_account("")).is_none(), "an empty id is no id");
}
/// OpenAI answers an unauthorized device poll with 403/404 as often as with a proper error code;
/// treating those as failures would abort every device login immediately.
#[test]
fn device_poll_errors_are_classified_conservatively() {
assert!(matches!(
classify_device_error::<()>("https://… returned 403 Forbidden: {}"),
Poll::Pending
));
assert!(matches!(classify_device_error::<()>("returned 404: not found"), Poll::Pending));
assert!(matches!(
classify_device_error::<()>("error: deviceauth_authorization_pending"),
Poll::Pending
));
assert!(matches!(classify_device_error::<()>("error: slow_down"), Poll::SlowDown(None)));
assert!(matches!(classify_device_error::<()>("returned 400: bad_client"), Poll::Failed(_)));
}
#[test]
fn numeric_fields_tolerate_string_encoding() {
assert_eq!(number_field(&serde_json::json!({ "interval": 7 }), "interval"), Some(7));
assert_eq!(number_field(&serde_json::json!({ "interval": " 7 " }), "interval"), Some(7));
assert_eq!(number_field(&serde_json::json!({ "interval": "x" }), "interval"), None);
assert_eq!(number_field(&serde_json::json!({}), "interval"), None);
}
}

View File

@@ -0,0 +1,112 @@
//! OpenRouter — the one subscription-style flow a provider actually publishes for this purpose.
//!
//! OpenRouter's documented PKCE flow exists so a third-party app can mint an API key **the user
//! owns**, billed from their OpenRouter credits and revocable from their dashboard. The result is a
//! durable key, so it is stored as an api-key credential rather than a token pair — there is nothing
//! to refresh.
use luxe_core::auth::{AuthError, AuthEvent, AuthInteraction};
use serde_json::Value;
use super::super::credential::Credential;
use super::{await_code, post_json, CallbackServer};
const AUTHORIZE_URL: &str = "https://openrouter.ai/auth";
const KEYS_URL: &str = "https://openrouter.ai/api/v1/auth/keys";
const CALLBACK_PATH: &str = "/openrouter/callback";
/// Where the flow talks to OpenRouter. Split out so tests can drive the real code locally.
#[derive(Debug, Clone)]
pub struct Endpoints {
/// Authorization page the browser opens.
pub authorize: String,
/// Exchanges the code for a user-owned API key.
pub keys: String,
}
impl Default for Endpoints {
fn default() -> Self {
Self { authorize: AUTHORIZE_URL.to_string(), keys: KEYS_URL.to_string() }
}
}
/// Run the flow and return the minted key.
pub async fn login(interaction: &dyn AuthInteraction) -> Result<Credential, AuthError> {
login_with(&Endpoints::default(), interaction).await
}
/// Run the flow against specific endpoints.
pub async fn login_with(
endpoints: &Endpoints,
interaction: &dyn AuthInteraction,
) -> Result<Credential, AuthError> {
let pkce = super::pkce();
// OpenRouter accepts any callback URL, so take a free port, and a path no page can guess: with
// no `state` in this flow, the path is what keeps a forged answer from ending it.
let path = format!("{CALLBACK_PATH}/{}", super::random_state());
let mut server = CallbackServer::bind(0, &path, None).await?;
let redirect_uri = server.redirect_uri();
let mut url = reqwest::Url::parse(&endpoints.authorize)
.map_err(|error| AuthError::Protocol(format!("bad authorize URL: {error}")))?;
url.query_pairs_mut()
.append_pair("callback_url", &redirect_uri)
.append_pair("code_challenge", &pkce.challenge)
.append_pair("code_challenge_method", "S256");
interaction.notify(AuthEvent::OpenUrl {
url: url.to_string(),
instructions: Some(
"Approve the request to create an API key. It stays yours — revoke it any time at \
openrouter.ai/keys."
.to_string(),
),
});
let callback = await_code(&mut server, interaction, None).await?;
interaction.notify(AuthEvent::Progress { message: "Creating the API key…".to_string() });
let body = post_json(
&endpoints.keys,
serde_json::json!({
"code": callback.code,
"code_verifier": pkce.verifier,
"code_challenge_method": "S256",
}),
)
.await?;
let key = body
.get("key")
.and_then(Value::as_str)
.filter(|key| !key.is_empty())
.ok_or_else(|| AuthError::Protocol("OpenRouter returned no API key".to_string()))?;
Ok(Credential::api_key(key))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_authorize_url_matches_openrouters_documented_parameters() {
let mut url = reqwest::Url::parse(AUTHORIZE_URL).expect("constant");
url.query_pairs_mut()
.append_pair("callback_url", "http://localhost:5000/openrouter/callback")
.append_pair("code_challenge", "chal")
.append_pair("code_challenge_method", "S256");
let pairs: std::collections::HashMap<_, _> = url.query_pairs().into_owned().collect();
assert_eq!(pairs["callback_url"], "http://localhost:5000/openrouter/callback");
assert_eq!(pairs["code_challenge_method"], "S256");
assert!(url.as_str().starts_with("https://openrouter.ai/auth?"));
}
/// The point of this flow is a durable, user-owned key — storing it as an OAuth token pair would
/// make the runtime try (and fail) to refresh it.
#[test]
fn the_minted_credential_is_an_api_key_not_a_token_pair() {
let credential = Credential::api_key("sk-or-v1-minted");
assert_eq!(credential.kind(), luxe_core::auth::CredentialKind::ApiKey);
assert!(credential.as_oauth().is_none());
}
}

View File

@@ -0,0 +1,165 @@
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn pasted_input_is_accepted_in_every_shape_a_provider_produces() {
let full = parse_pasted_code("http://localhost:1455/auth/callback?code=abc&state=xyz")
.expect("full URL");
assert_eq!((full.code.as_str(), full.state.as_deref()), ("abc", Some("xyz")));
let query = parse_pasted_code("code=abc&state=xyz").expect("bare query");
assert_eq!((query.code.as_str(), query.state.as_deref()), ("abc", Some("xyz")));
let hashed = parse_pasted_code("abc#xyz").expect("code#state");
assert_eq!((hashed.code.as_str(), hashed.state.as_deref()), ("abc", Some("xyz")));
let bare = parse_pasted_code(" abc ").expect("bare code");
assert_eq!((bare.code.as_str(), bare.state), ("abc", None));
assert!(parse_pasted_code(" ").is_none());
}
#[tokio::test]
async fn the_loopback_server_receives_a_real_redirect() {
let mut server = CallbackServer::bind(0, "/auth/callback", Some("state-1".into()))
.await
.expect("binds an ephemeral port");
let uri = server.redirect_uri();
assert!(uri.starts_with("http://localhost:"), "providers register localhost: {uri}");
let url = format!("{uri}?code=the-code&state=state-1");
let request = tokio::spawn(async move { crate::http::shared_client().get(&url).send().await });
let callback = server.wait().await.expect("delivered").expect("accepted");
assert_eq!(callback.code, "the-code");
let response = request.await.expect("join").expect("http ok");
assert!(response.status().is_success());
assert!(response.text().await.unwrap_or_default().contains("Signed in"));
}
/// Any page the browser has open can make it request `localhost`, so a forged error or another
/// sign-in's answer must not end this one; and a connection that says nothing must not hold the
/// real redirect behind it.
#[tokio::test]
async fn only_this_sign_ins_answer_ends_it() {
let mut server =
CallbackServer::bind(0, "/auth/callback", Some("state-1".into())).await.unwrap();
let uri = server.redirect_uri();
let port = reqwest::Url::parse(&uri).unwrap().port().unwrap();
let _silent = tokio::net::TcpStream::connect(("127.0.0.1", port)).await.unwrap();
let browser = tokio::spawn(async move {
let client = crate::http::shared_client();
for forged in ["?error=access_denied", "?code=evil&state=other"] {
let response = client.get(format!("{uri}{forged}")).send().await.unwrap();
assert_eq!(response.status().as_u16(), 400, "{forged}");
}
client.get(format!("{uri}?code=the-code&state=state-1")).send().await.unwrap()
});
let callback = tokio::time::timeout(std::time::Duration::from_secs(10), server.wait())
.await
.expect("not stalled")
.expect("delivered")
.expect("accepted");
assert_eq!(callback.code, "the-code");
assert!(browser.await.unwrap().status().is_success());
}
/// The provider's own words are repeated on the page, escaped.
#[tokio::test]
async fn a_providers_error_is_escaped_on_the_page() {
let mut server = CallbackServer::bind(0, "/cb", None).await.unwrap();
let url = format!("{}?error=x&error_description=%3Cb%3Eno%3C/b%3E", server.redirect_uri());
let request = tokio::spawn(async move { crate::http::shared_client().get(&url).send().await });
let refused = server.wait().await.expect("delivered").expect_err("refused");
assert_eq!(refused, "<b>no</b>");
let page = request.await.unwrap().unwrap().text().await.unwrap();
assert!(page.contains("&lt;b&gt;no&lt;/b&gt;") && !page.contains("<b>no"), "{page}");
}
#[tokio::test]
async fn the_poller_stops_on_success_and_honors_slow_down() {
tokio::time::pause();
let attempts = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
let counter = attempts.clone();
let pacing = DevicePacing { interval_secs: 1, expires_in_secs: 900, wait_first: false };
let value = poll_device_code(pacing, || {
let counter = counter.clone();
async move {
let seen = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
match seen {
0 => Poll::Pending,
1 => Poll::SlowDown(Some(2)),
_ => Poll::Done("token"),
}
}
})
.await
.expect("authorized");
assert_eq!(value, "token");
assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 3);
}
#[tokio::test]
async fn the_poller_gives_up_when_the_code_expires() {
tokio::time::pause();
let pacing = DevicePacing { interval_secs: 5, expires_in_secs: 10, wait_first: true };
let error = poll_device_code(pacing, || async { Poll::Pending::<()> })
.await
.expect_err("must time out");
assert!(matches!(error, AuthError::Timeout(_)), "got {error:?}");
assert!(error.to_string().contains("expired"));
}
#[tokio::test]
async fn a_slow_down_timeout_names_the_usual_culprit() {
tokio::time::pause();
let pacing = DevicePacing { interval_secs: 5, expires_in_secs: 12, wait_first: false };
let error = poll_device_code(pacing, || async { Poll::SlowDown::<()>(None) })
.await
.expect_err("must time out");
assert!(error.to_string().contains("clock"), "unhelpful: {error}");
}
#[tokio::test]
async fn a_terminal_poll_failure_surfaces_the_providers_message() {
let pacing = DevicePacing { interval_secs: 1, expires_in_secs: 60, wait_first: false };
let error = poll_device_code(pacing, || async { Poll::Failed::<()>("access_denied".into()) })
.await
.expect_err("must fail");
assert!(matches!(error, AuthError::Rejected(message) if message == "access_denied"));
}
#[test]
fn jwt_payloads_decode_without_verification() {
let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
.encode(br#"{"sub":"u1","https://api.openai.com/auth":{"chatgpt_account_id":"acct"}}"#);
let token = format!("header.{payload}.signature");
let claims = decode_jwt_payload(&token).expect("decodes");
assert_eq!(claims["https://api.openai.com/auth"]["chatgpt_account_id"], "acct");
assert!(decode_jwt_payload("not-a-jwt").is_none());
assert!(decode_jwt_payload("a.!!!.c").is_none());
}
#[test]
fn error_bodies_yield_the_most_useful_message() {
let described = serde_json::json!({"error": "invalid_grant", "error_description": "expired"});
assert_eq!(provider_error_message(&described).as_deref(), Some("expired"));
assert_eq!(provider_error_code(&described).as_deref(), Some("invalid_grant"));
let nested = serde_json::json!({"error": {"code": "slow_down", "message": "back off"}});
assert_eq!(provider_error_message(&nested).as_deref(), Some("back off"));
assert_eq!(provider_error_code(&nested).as_deref(), Some("slow_down"));
assert!(provider_error_message(&serde_json::json!({})).is_none());
}
#[test]
fn expiry_keeps_a_margin_but_never_lands_in_the_past() {
let now = super::super::credential::now_ms();
let hour = expiry_from_expires_in(3600);
assert!(hour > now, "must be in the future");
assert!(hour < now + 3600 * 1000, "must reserve a refresh margin");
// A very short-lived token still expires in the future rather than immediately.
assert!(expiry_from_expires_in(10) > now);
}

View File

@@ -0,0 +1,493 @@
//! The login engine — [`ProviderAuth`], Luxe's [`AuthService`].
//!
//! One implementation drives every surface: `luxe auth login`, the TUI's `/login` wizard, and the
//! credential-less first-run path all call the same three methods. The front-end only supplies an
//! [`AuthInteraction`] (how to ask a question and show progress); everything about *what* to ask,
//! which endpoint to call, and what to persist lives here.
//!
//! A login always ends in one of three states: a credential in the store, a typed
//! [`AuthError`], or [`AuthError::Cancelled`] because the user backed out. Nothing is written
//! before the credential is known-good.
//!
//! The login flows live here; `status` resolves what each provider has, `models` talks to an
//! endpoint's model list, `refresh` re-asks local servers and Azure resources in the background,
//! and `custom` turns the wizard's custom entry into a provider.
use std::sync::Arc;
use luxe_core::auth::{
AuthError, AuthEvent, AuthInteraction, AuthLink, AuthPrompt, AuthService, CredentialKind,
LoginOutcome, ProviderOption,
};
use secrecy::ExposeSecret;
use super::catalog::{canonical_id, provider_descriptor, ProviderDescriptor};
use super::config_file::ConfigFile;
use super::credential::Credential;
use super::deployments;
use super::source::RequestAuth;
use super::store::AuthStore;
use crate::config::{resolve_key, ApiKey};
use models::{
describe_models, normalize_base_url, pick_model, verify_credential, warn_if_sent_in_the_clear,
};
use refresh::discover_with_key;
mod custom;
mod models;
mod refresh;
mod status;
/// The key a user typed, as stored and as it resolves right now.
struct Key {
/// Verbatim — a `$ENV` or `!command` spec stays one, which is the point of it.
spec: String,
resolved: String,
}
/// What verification learned: a default to suggest, what to tell the user, and what the resource
/// has deployed when it said.
#[derive(Default)]
struct Checked<'a> {
suggested_model: Option<String>,
notes: Vec<String>,
discovered: Option<Vec<(&'a str, deployments::Served)>>,
}
/// Luxe's [`AuthService`]: catalog + credential store + the OAuth flows.
#[derive(Debug, Clone)]
pub struct ProviderAuth {
store: AuthStore,
config: ConfigFile,
/// Whether to make a verification request after storing an API key.
verify: bool,
}
impl Default for ProviderAuth {
fn default() -> Self {
Self::new()
}
}
impl ProviderAuth {
/// Use the default config locations.
pub fn new() -> Self {
Self { store: AuthStore::default_path(), config: ConfigFile::default_path(), verify: true }
}
/// Point at explicit files (tests, alternate profiles).
pub fn with_paths(store: AuthStore, config: ConfigFile) -> Self {
Self { store, config, verify: true }
}
/// Skip the post-login verification request (`--no-verify`, air-gapped setups).
pub fn without_verification(mut self) -> Self {
self.verify = false;
self
}
/// The credential store behind this service.
pub fn store(&self) -> &AuthStore {
&self.store
}
/// Store a credential, reporting a storage failure as such rather than as a login failure.
fn persist(&self, provider_id: &str, credential: &Credential) -> Result<(), AuthError> {
self.store
.put(provider_id, credential)
.map_err(|error| AuthError::Storage(error.to_string()))
}
/// Ask for a key, verify it, store it.
///
/// `resource_root` is the endpoint a provider that needs one was given, already reduced to the
/// root each of its APIs hangs off — for a lone provider that is simply its base URL.
async fn login_api_key(
&self,
descriptor: &ProviderDescriptor,
resource_root: Option<String>,
interaction: &dyn AuthInteraction,
) -> Result<LoginOutcome, AuthError> {
// Before the key is asked for, so a user who would rather not can still back out
if let Some(root) = resource_root.as_deref() {
warn_if_sent_in_the_clear(root, interaction);
}
let key = ask_for_key(descriptor, interaction).await?;
let mut checked = self
.verify_or_discover(descriptor, resource_root.as_deref(), &key, interaction)
.await?;
let siblings = self.persist_with_siblings(
descriptor,
&Credential::api_key(&key.spec),
resource_root.as_deref(),
&checked,
)?;
checked.notes.extend(siblings);
Ok(LoginOutcome {
provider_id: descriptor.id.to_string(),
provider_name: descriptor.name.to_string(),
kind: Some(CredentialKind::ApiKey),
account: None,
suggested_model: checked.suggested_model,
notes: checked.notes,
advice: descriptor.after_login.map(str::to_string).into_iter().collect(),
})
}
/// Prove the key works and learn what it can serve.
///
/// What the resource has deployed is both the proof the key works and the only honest list of
/// what it serves. A resource that will not say falls back to the model list, which proves the
/// key but describes Azure rather than the resource.
async fn verify_or_discover<'a>(
&self,
descriptor: &'a ProviderDescriptor,
resource_root: Option<&str>,
key: &Key,
interaction: &dyn AuthInteraction,
) -> Result<Checked<'a>, AuthError> {
let mut checked = Checked::default();
let discovered = match (self.verify, resource_root) {
(true, Some(root)) if descriptor.lists_deployments => {
interaction.notify(AuthEvent::Progress {
message: "Reading the resource's deployments…".to_string(),
});
discover_with_key(descriptor, root, &ApiKey::new(&key.resolved)).await
}
_ => None,
};
if let Some(split) = &discovered {
let own = split.iter().find(|(id, _)| *id == &*descriptor.id);
checked.suggested_model =
own.and_then(|(_, served)| pick_model(descriptor, &served.models));
checked.notes.extend(deployments::describe(split));
}
// A provider with no model list can't answer for itself; where it shares a resource with
// one that can, the sibling proves the same key.
let checker = match descriptor.lists_models {
true => Some(descriptor),
false => self.halves(descriptor).into_iter().find(|sibling| sibling.lists_models),
};
if self.verify && discovered.is_none() {
if let Some(checker) = checker {
interaction.notify(AuthEvent::Progress {
message: "Checking the endpoint…".to_string(),
});
let auth = checker.key_style().headers(&ApiKey::new(&key.resolved));
let endpoint = resource_root
.map(|root| checker.endpoint_for(root))
.or_else(|| checker.base_url.map(str::to_string));
let models = verify_credential(checker, endpoint.as_deref(), &auth).await?;
checked.suggested_model = pick_model(descriptor, &models);
checked.notes.extend(describe_models(&models));
}
}
checked.discovered = discovered;
Ok(checked)
}
/// Write the credential and its config, and the same for the rest of a shared resource.
///
/// One resource, one key, two wire APIs: both halves are configured, whichever was named. Only
/// the half the user asked for becomes the default, so the sibling never steals it. Answers a
/// note per sibling.
fn persist_with_siblings(
&self,
descriptor: &ProviderDescriptor,
credential: &Credential,
resource_root: Option<&str>,
checked: &Checked<'_>,
) -> Result<Vec<String>, AuthError> {
let mut notes = Vec::new();
for sibling in self.halves(descriptor) {
self.persist(&sibling.id, credential)?;
self.record_provider(sibling, resource_root)?;
notes.push(format!("{} is configured with the same key", sibling.name));
}
self.persist(&descriptor.id, credential)?;
self.record_config(descriptor, resource_root, checked.suggested_model.as_deref())?;
for (id, served) in checked.discovered.iter().flatten() {
self.config
.set_deployments(id, served)
.map_err(|error| AuthError::Storage(error.to_string()))?;
}
Ok(notes)
}
/// The other providers this login configures — the rest of a shared resource.
fn halves(&self, descriptor: &ProviderDescriptor) -> Vec<&'static ProviderDescriptor> {
descriptor.paired_with.iter().filter_map(|id| provider_descriptor(id)).collect()
}
/// Run a subscription flow.
async fn login_subscription(
&self,
descriptor: &ProviderDescriptor,
interaction: &dyn AuthInteraction,
) -> Result<LoginOutcome, AuthError> {
let flow = descriptor.oauth_flow().ok_or_else(|| AuthError::UnknownMethod {
provider: descriptor.id.to_string(),
method: "oauth".to_string(),
})?;
let credential = super::oauth::login(flow, interaction).await?;
let mut notes = Vec::new();
let available =
credential.as_oauth().map(|oauth| oauth.available_models.clone()).unwrap_or_default();
let mut suggested_model = pick_model(descriptor, &available);
if let Some(note) = describe_models(&available) {
notes.push(note);
}
// OpenRouter's flow mints an API key; the others hand back a token pair. Either way the
// provider is only really configured once we can list its models.
if suggested_model.is_none() && self.verify {
interaction.notify(AuthEvent::Progress { message: "Checking access…".to_string() });
let auth = match &credential {
Credential::OAuth(oauth) => {
let mut auth = RequestAuth::bearer(&oauth.access);
if let Some(endpoint) = &oauth.endpoint {
auth = auth.with_base_url(endpoint.clone());
}
auth
}
Credential::ApiKey(api) => RequestAuth::bearer(&ApiKey::new(
resolve_key(api.key.expose()).await.unwrap_or_default(),
)),
};
let endpoint =
auth.base_url.clone().or_else(|| descriptor.base_url.map(str::to_string));
if let Ok(models) = verify_credential(descriptor, endpoint.as_deref(), &auth).await {
suggested_model = pick_model(descriptor, &models);
if let Some(note) = describe_models(&models) {
notes.push(note);
}
}
}
let account = credential.as_oauth().and_then(|oauth| oauth.account.clone());
self.persist(&descriptor.id, &credential)?;
self.record_config(descriptor, None, suggested_model.as_deref())?;
Ok(LoginOutcome {
provider_id: descriptor.id.to_string(),
provider_name: descriptor.name.to_string(),
kind: Some(credential.kind()),
account,
suggested_model,
notes,
// Advice that only makes sense now that the credential exists.
advice: descriptor.after_login.map(str::to_string).into_iter().collect(),
})
}
/// Connect to a local server: confirm the endpoint, list what it's serving, remember it.
async fn login_local(
&self,
descriptor: &ProviderDescriptor,
interaction: &dyn AuthInteraction,
) -> Result<LoginOutcome, AuthError> {
let default = descriptor.base_url.unwrap_or("http://127.0.0.1:1234/v1");
let answer = interaction
.prompt(AuthPrompt::optional_text(
format!("{} endpoint (blank for the default):", descriptor.name),
Some(default.to_string()),
))
.await?;
let typed = answer.expose_secret().trim().to_string();
let base_url =
if typed.is_empty() { default.to_string() } else { normalize_base_url(&typed)? };
interaction.notify(AuthEvent::Progress { message: format!("Contacting {base_url}…") });
let models = verify_credential(descriptor, Some(&base_url), &RequestAuth::none())
.await
.map_err(|error| match error {
AuthError::Network(message) => AuthError::Network(format!(
"{message} — is {} running and serving {base_url}?",
descriptor.name
)),
other => other,
})?;
if models.is_empty() {
return Err(AuthError::Rejected(format!(
"{base_url} answered but is serving no models — load one in {} first",
descriptor.name
)));
}
let suggested_model = models.first().cloned();
// Recorded even when it is the default, because the block is the only durable record that
// this server was connected at all — a keyless provider leaves nothing in `auth.json`, so
// without it the machine reports itself unconfigured on the next launch.
self.record_config(descriptor, Some(&base_url), suggested_model.as_deref())?;
// And what it serves, which the catalog cannot answer for a machine it has never seen.
self.config
.set_served_models(&descriptor.id, &models)
.map_err(|error| AuthError::Storage(error.to_string()))?;
Ok(LoginOutcome {
provider_id: descriptor.id.to_string(),
provider_name: descriptor.name.to_string(),
kind: None,
account: None,
suggested_model,
notes: describe_models(&models).into_iter().collect(),
advice: descriptor.after_login.map(str::to_string).into_iter().collect(),
})
}
/// Persist what the runtime needs to reach this provider next launch, and point Luxe at it.
fn record_config(
&self,
descriptor: &ProviderDescriptor,
resource_root: Option<&str>,
model: Option<&str>,
) -> Result<(), AuthError> {
self.record_provider(descriptor, resource_root)?;
self.config
.set_defaults(&descriptor.id, model)
.map_err(|error| AuthError::Storage(error.to_string()))
}
/// Record a provider's block, when the catalog can't supply the answer itself.
///
/// A plain `luxe auth login openai` leaves `models.json` alone apart from the defaults.
fn record_provider(
&self,
descriptor: &ProviderDescriptor,
resource_root: Option<&str>,
) -> Result<(), AuthError> {
let Some(base_url) = resource_root.map(|root| descriptor.endpoint_for(root)) else {
return Ok(());
};
self.config
.upsert_provider(
&descriptor.id,
Some(&base_url),
Some(descriptor.api),
descriptor.models_dev,
)
.map_err(|error| AuthError::Storage(error.to_string()))
}
}
#[async_trait::async_trait]
impl AuthService for ProviderAuth {
fn providers(&self) -> Vec<ProviderOption> {
self.options()
}
/// Accepts the aliases people type (`copilot`, `codex`, `gemini`) as well as catalog ids.
fn provider(&self, id: &str) -> Option<ProviderOption> {
let canonical = canonical_id(id);
self.providers().into_iter().find(|option| option.id == canonical || option.id == id)
}
async fn login(
&self,
provider_id: &str,
method_id: &str,
interaction: Arc<dyn AuthInteraction>,
) -> Result<LoginOutcome, AuthError> {
let id = canonical_id(provider_id);
let descriptor = provider_descriptor(&id)
.ok_or_else(|| AuthError::UnknownProvider(provider_id.to_string()))?;
let interaction = interaction.as_ref();
// The custom endpoint is a wizard entry, not a provider: it asks what to become first.
if descriptor.id == "custom" {
let (resolved, base_url) = self.resolve_custom(interaction).await?;
return self.login_api_key(&resolved, Some(base_url), interaction).await;
}
let method =
descriptor.methods().into_iter().find(|method| method.id == method_id).ok_or_else(
|| AuthError::UnknownMethod {
provider: descriptor.id.to_string(),
method: method_id.to_string(),
},
)?;
if let Some(note) = descriptor.note {
interaction.notify(AuthEvent::Info { message: note.to_string(), links: Vec::new() });
}
match method.id.as_str() {
"oauth" => self.login_subscription(descriptor, interaction).await,
"local" => self.login_local(descriptor, interaction).await,
_ if descriptor.needs_base_url => {
let prompt = match descriptor.endpoint {
Some(endpoint) => AuthPrompt::text(
format!("{} resource (name or endpoint):", descriptor.name),
Some(endpoint.host.replace("{resource}", "my-resource")),
),
None => AuthPrompt::text(
"Base URL, including the version segment:",
Some("https://host/v1".to_string()),
),
};
let answer = interaction.prompt(prompt).await?;
let root = normalize_base_url(&descriptor.resource_root(answer.expose_secret()))?;
self.login_api_key(descriptor, Some(root), interaction).await
}
_ => self.login_api_key(descriptor, None, interaction).await,
}
}
fn logout(&self, provider_id: &str) -> Result<bool, AuthError> {
let id = canonical_id(provider_id);
self.store.remove(&id).map_err(|error| AuthError::Storage(error.to_string()))
}
fn store_path(&self) -> std::path::PathBuf {
self.store.path().to_path_buf()
}
}
/// Ask for the provider's key and make sure it is something.
///
/// A `$ENV`/`!command` spec is stored verbatim (that's the point of it) but must resolve to
/// something now, or the user has a broken setup they won't discover until their first turn.
async fn ask_for_key(
descriptor: &ProviderDescriptor,
interaction: &dyn AuthInteraction,
) -> Result<Key, AuthError> {
if let Some(url) = descriptor.console_url {
interaction.notify(AuthEvent::Info {
message: format!("Create a key for {}, then paste it here.", descriptor.name),
links: vec![AuthLink { url: url.to_string(), label: Some("API keys".to_string()) }],
});
}
let answer = interaction
.prompt(AuthPrompt::secret(
format!("{} API key:", descriptor.name),
descriptor.key_hint.map(str::to_string),
))
.await?;
let spec = answer.expose_secret().trim().to_string();
if spec.is_empty() {
return Err(AuthError::Input("no key entered".to_string()));
}
let resolved = resolve_key(&spec).await.map_err(AuthError::Input)?;
if resolved.trim().is_empty() {
return Err(AuthError::Input(
"that resolved to an empty value — check the environment variable or command"
.to_string(),
));
}
if let Some(hint) = descriptor.key_hint {
let prefix = hint.trim_end_matches(['…', '.']);
if !prefix.is_empty() && !resolved.starts_with(prefix) {
// A warning, not a refusal: key formats change more often than this code does.
interaction.notify(AuthEvent::Info {
message: format!(
"Heads up: {} keys usually start with {prefix} — storing it anyway.",
descriptor.name
),
links: Vec::new(),
});
}
}
Ok(Key { spec, resolved })
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,70 @@
//! The custom endpoint — a wizard entry that becomes a provider once the user names it.
use luxe_core::auth::{ApiKind, AuthError, AuthInteraction, AuthPrompt};
use secrecy::ExposeSecret;
use super::models::normalize_base_url;
use super::{ProviderAuth, ProviderDescriptor};
use crate::auth::catalog::provider_descriptor;
impl ProviderAuth {
/// Resolve the custom-endpoint pseudo-provider into a real one the user names.
pub(super) async fn resolve_custom(
&self,
interaction: &dyn AuthInteraction,
) -> Result<(ProviderDescriptor, String), AuthError> {
let id_answer = interaction
.prompt(AuthPrompt::text(
"Name for this provider (letters, digits, - and _):",
Some("my-endpoint".to_string()),
))
.await?;
let id = id_answer.expose_secret().trim().to_ascii_lowercase();
if id.is_empty() || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
return Err(AuthError::Input(
"use letters, digits, dashes or underscores for the provider name".to_string(),
));
}
if provider_descriptor(&id).is_some() {
return Err(AuthError::Input(format!(
"'{id}' is already a built-in provider — run `luxe auth login {id}` instead"
)));
}
let url_answer = interaction
.prompt(AuthPrompt::text(
"Base URL, including the version segment:",
Some("https://host/v1".to_string()),
))
.await?;
let base_url = normalize_base_url(url_answer.expose_secret())?;
let api_answer = interaction
.prompt(AuthPrompt::select(
"Which API does it speak?",
vec![
luxe_core::auth::AuthChoice {
id: ApiKind::OpenaiCompletions.as_str().to_string(),
label: "OpenAI /chat/completions".to_string(),
detail: Some("vLLM, llama.cpp, Ollama, most proxies".to_string()),
},
luxe_core::auth::AuthChoice {
id: ApiKind::OpenaiResponses.as_str().to_string(),
label: "OpenAI /responses".to_string(),
detail: Some("Azure OpenAI, newer OpenAI-compatible gateways".to_string()),
},
luxe_core::auth::AuthChoice {
id: ApiKind::AnthropicMessages.as_str().to_string(),
label: "Anthropic /messages".to_string(),
detail: Some("An Anthropic-compatible gateway".to_string()),
},
],
))
.await?;
let api = ApiKind::parse(api_answer.expose_secret())
.ok_or_else(|| AuthError::Input("unknown API kind".to_string()))?;
let descriptor = ProviderDescriptor::custom(id, api);
Ok((descriptor, base_url))
}
}

View File

@@ -0,0 +1,193 @@
//! Model lists — verifying a credential reaches a provider, and reading what it serves.
//!
//! The pure half of a login: nothing here writes anything. [`verify_credential`] is the one network
//! call, and the rest turn its answer into the confirmation a user reads.
use luxe_core::auth::{ApiKind, AuthError, AuthEvent, AuthInteraction};
use super::ProviderDescriptor;
use crate::auth::source::RequestAuth;
/// How many models to name when confirming a login.
const MODEL_PREVIEW: usize = 3;
/// Check that a credential reaches the provider, and learn what it can serve.
///
/// One cheap authenticated request — the model list — which doubles as the source of the "17 models
/// available" confirmation and of a sensible default model. Codex has no such endpoint, and its login
/// already proved the account, so it is exempt; so is a provider whose `lists_models` says the same
/// (Foundry's Anthropic passthrough), which verifies through the sibling sharing its resource
/// rather than reading a 404 as a broken key.
///
/// **What this does and doesn't prove.** A 401/403 is a real rejection and fails the login, which is
/// what catches a mistyped or revoked key on the providers that authenticate this endpoint (OpenAI,
/// Anthropic, most others). A few providers serve `/models` publicly — NVIDIA NIM does — so a wrong
/// key there passes this check and fails on the first turn instead, with the auth error the adapter
/// now raises. The alternative is spending tokens on a real completion at every login, which is a
/// worse trade for a check whose main job is catching typos and unreachable endpoints.
pub(super) async fn verify_credential(
descriptor: &ProviderDescriptor,
base_url: Option<&str>,
auth: &RequestAuth,
) -> Result<Vec<String>, AuthError> {
if descriptor.api == ApiKind::OpenaiCodex || !descriptor.lists_models {
return Ok(Vec::new());
}
let Some(base) = base_url else { return Ok(Vec::new()) };
let url = format!("{}/models", base.trim_end_matches('/'));
let mut request = crate::http::shared_client().get(&url).header("Accept", "application/json");
request = auth.apply(request);
if descriptor.api == ApiKind::AnthropicMessages {
request = request.header("anthropic-version", "2023-06-01");
}
let response = within_start_timeout(&url, "an answer", request.send()).await?;
let status = response.status();
let body = within_start_timeout(&url, "the model list", async {
Ok(response.text().await.unwrap_or_default())
})
.await?;
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
return Err(AuthError::Rejected(format!(
"{} rejected that credential ({status})",
descriptor.name
)));
}
if !status.is_success() {
// A provider without a `/models` endpoint is not a broken credential. Say so and move on:
// refusing the login here would block a working local server or a minimal proxy.
tracing::debug!(provider = %descriptor.id, %status, "provider has no usable model list");
return Ok(Vec::new());
}
Ok(parse_model_ids(&body))
}
/// Pull model ids out of an OpenAI- or Anthropic-shaped list response.
pub(super) fn parse_model_ids(body: &str) -> Vec<String> {
let Ok(value) = serde_json::from_str::<serde_json::Value>(body) else { return Vec::new() };
let rows = value.get("data").and_then(|data| data.as_array());
let mut ids: Vec<String> = rows
.map(|rows| {
rows.iter()
.filter_map(|row| row.get("id").and_then(|id| id.as_str()))
.filter(|id| !answers_nothing(id))
.map(str::to_string)
.collect()
})
.unwrap_or_default();
ids.sort_unstable();
ids.dedup();
ids
}
/// Whether an id names a model that cannot hold a conversation.
///
/// `/v1/models` is a flat list — LM Studio, Ollama and OpenAI all return an embedding model
/// beside the ones that answer — and nothing in the response says which is which. So the name
/// does, which is a heuristic and is kept to the two families whose ids are a convention rather
/// than a brand: offering one is a default that fails on the first turn, and the reader has no
/// way to know why. A model deliberately named this way is still reachable by declaring it in
/// `models.json`.
pub(super) fn answers_nothing(id: &str) -> bool {
let id = id.to_ascii_lowercase();
["embed", "rerank"].iter().any(|kind| id.contains(kind))
}
/// A default model worth pointing the user at.
///
/// Prefers the provider's own preference order (the catalog default, when the account can actually
/// reach it), then the first model the endpoint reported. Never invents an id the account can't use.
pub(super) fn pick_model(descriptor: &ProviderDescriptor, available: &[String]) -> Option<String> {
if available.is_empty() {
return None;
}
descriptor
.preferred_models
.iter()
.find(|candidate| available.iter().any(|id| id == *candidate))
.map(|candidate| (*candidate).to_string())
.or_else(|| available.first().cloned())
}
/// "17 models available" — the line that tells a user the login actually worked.
pub(super) fn describe_models(models: &[String]) -> Option<String> {
if models.is_empty() {
return None;
}
let preview: Vec<&str> = models.iter().take(MODEL_PREVIEW).map(String::as_str).collect();
let suffix = if models.len() > preview.len() { ", …" } else { "" };
Some(format!(
"{} model{} available ({}{suffix})",
models.len(),
if models.len() == 1 { "" } else { "s" },
preview.join(", ")
))
}
/// Validate and tidy a user-typed base URL.
pub(super) fn normalize_base_url(raw: &str) -> Result<String, AuthError> {
let trimmed = raw.trim().trim_end_matches('/');
if trimmed.is_empty() {
return Err(AuthError::Input("no URL entered".to_string()));
}
let candidate =
if trimmed.contains("://") { trimmed.to_string() } else { format!("https://{trimmed}") };
let url = reqwest::Url::parse(&candidate)
.map_err(|error| AuthError::Input(format!("'{trimmed}' is not a URL ({error})")))?;
if !matches!(url.scheme(), "http" | "https") {
return Err(AuthError::Input("the endpoint must be an http(s) URL".to_string()));
}
if url.host_str().is_none() {
return Err(AuthError::Input("the endpoint has no host".to_string()));
}
Ok(candidate)
}
/// Say so when a key is about to travel over plain http to somewhere that is not this machine.
///
/// A warning, not a refusal: a lab server on the LAN is a legitimate thing to point at, and the
/// user typed the URL. They should know the key crosses the network in the clear.
pub(super) fn warn_if_sent_in_the_clear(url: &str, interaction: &dyn AuthInteraction) {
let Ok(url) = reqwest::Url::parse(url) else { return };
if url.scheme() != "http" || is_loopback(&url) {
return;
}
interaction.notify(AuthEvent::Info {
message: format!(
"{} is plain http, so your key will cross the network unencrypted.",
url.host_str().unwrap_or("that endpoint")
),
links: Vec::new(),
});
}
fn is_loopback(url: &reqwest::Url) -> bool {
let Some(host) = url.host_str() else { return false };
host.eq_ignore_ascii_case("localhost")
|| host
.trim_matches(['[', ']'])
.parse::<std::net::IpAddr>()
.is_ok_and(|ip| ip.is_loopback())
}
/// `work` against `url`, given as long as a provider gets to start answering.
///
/// Both halves of a verification need it: [`crate::http::send`] stops at the headers, so a server
/// that sends those and then goes quiet would hold the login there for good, and it speaks
/// [`luxe_core::provider::ProviderError`], which would stack a second "network error" on this
/// one's. `what` finishes "timed out after Ns waiting for …".
async fn within_start_timeout<T>(
url: &str,
what: &str,
work: impl std::future::Future<Output = Result<T, reqwest::Error>>,
) -> Result<T, AuthError> {
let unreachable = |why: String| AuthError::Network(format!("could not reach {url}: {why}"));
let finished = match crate::http::start_timeout() {
None => work.await,
Some(limit) => tokio::time::timeout(limit, work).await.map_err(|_| {
unreachable(format!("timed out after {}s waiting for {what}", limit.as_secs()))
})?,
};
finished.map_err(|error| unreachable(luxe_core::provider::describe_error_chain(&error)))
}

View File

@@ -0,0 +1,176 @@
//! Background refreshers — re-asking local servers and Azure resources what they serve.
//!
//! Both run while a picker is on screen and leave the recorded list standing when the server does
//! not answer in time.
use super::models::verify_credential;
use super::{ProviderAuth, ProviderDescriptor};
use crate::auth::catalog::provider_descriptors;
use crate::auth::deployments;
use crate::auth::source::{AuthSource, KeyStyle, RequestAuth, StoreAuth};
use crate::config::ApiKey;
/// How long a local server gets to answer before its recorded list stands in.
///
/// Short on purpose: this is a loopback request made while a picker is already on screen, so the
/// cost of waiting is a list that updates late, and the cost of not waiting is nothing.
const LOCAL_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);
/// How long an Azure resource gets to list its deployments before the recorded list stands in.
///
/// Longer than a local server gets, because this one crosses the internet, and still short: it
/// runs while a picker is on screen, and the cost of giving up is a list that updates next time.
const REMOTE_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
impl ProviderAuth {
/// Re-ask every connected local server what it is serving, answering whether anything moved.
///
/// A local list is not a fact about the world, it is a fact about this machine ten seconds
/// ago: loading a model in LM Studio changes it, and a picker built from a snapshot taken at
/// connect time would keep offering yesterday's. Only keyless providers with a block are
/// asked — they are the ones on this machine, so the call is a loopback round trip that costs
/// nothing and fails instantly when the server is off, and the recorded list stands in when it
/// does.
pub async fn refresh_local_models(&self) -> bool {
let Ok(config) = crate::config::load_models_config(self.config.path()) else {
return false;
};
let mut changed = false;
for descriptor in provider_descriptors().iter().filter(|entry| entry.keyless) {
let Some(block) = config.providers.get(&*descriptor.id) else { continue };
let Some(base_url) =
block.base_url.clone().or_else(|| descriptor.base_url.map(str::to_string))
else {
continue;
};
let anonymous = RequestAuth::none();
let probe = verify_credential(descriptor, Some(&base_url), &anonymous);
let Ok(Ok(models)) = tokio::time::timeout(LOCAL_PROBE_TIMEOUT, probe).await else {
tracing::debug!(provider = %descriptor.id, %base_url, "local server did not answer");
continue;
};
if models.is_empty() || block.served_models.as_deref() == Some(models.as_slice()) {
continue;
}
match self.config.set_served_models(&descriptor.id, &models) {
Ok(()) => changed = true,
Err(error) => {
tracing::warn!(%error, provider = %descriptor.id, "could not record what the local server serves")
}
}
}
changed
}
/// Ask every Azure resource Luxe is set up for what it has deployed, answering whether any
/// recorded list moved.
///
/// Deployments change in a portal Luxe never sees, so the list is re-read rather than trusted
/// from login. One request per resource, not per provider: the three Foundry providers share
/// one. A resource that does not answer in time, refuses the key, or no longer has the route
/// leaves its recorded list standing, and `"discover_deployments": false` on any of its
/// providers stops the request entirely.
pub async fn refresh_deployments(&self) -> bool {
let Ok(config) = crate::config::load_models_config(self.config.path()) else {
return false;
};
let mut asked: Vec<&str> = Vec::new();
let mut changed = false;
for descriptor in provider_descriptors().iter().filter(|entry| entry.lists_deployments) {
if asked.contains(&&*descriptor.id) {
continue;
}
let group = deployments::group(descriptor);
asked.extend(group.iter().map(|member| &*member.id));
let reachable =
|id: &str| config.providers.get(id).filter(|block| block.base_url.is_some());
if group.iter().any(|member| {
config.providers.get(&*member.id).and_then(|block| block.discover_deployments)
== Some(false)
}) {
continue;
}
let Some((lead, block)) =
group.iter().find_map(|member| reachable(&member.id).map(|block| (member, block)))
else {
continue;
};
let Some(url) = block.base_url.as_deref().and_then(deployments::listing_url) else {
continue;
};
let source = StoreAuth::new(
self.store.clone(),
lead.id.to_string(),
crate::config::resolve_api(&lead.id, Some(block)),
)
.with_key_style(Some(crate::config::resolve_key_style(&lead.id, Some(block))))
.with_fallback(block.api_key.clone());
let Ok(auth) = source.request_auth().await else { continue };
let found =
match tokio::time::timeout(REMOTE_PROBE_TIMEOUT, deployments::list(&url, &auth))
.await
{
Ok(Ok(found)) if !found.is_empty() => found,
Ok(Ok(_)) => continue,
Ok(Err(error)) => {
tracing::debug!(provider = %lead.id, %error, "deployments not listed");
continue;
}
Err(_) => {
tracing::debug!(provider = %lead.id, "deployment listing timed out");
continue;
}
};
for (id, served) in deployments::partition(&group, &found) {
let Some(block) = reachable(id) else { continue };
let recorded = deployments::Served {
models: block.served_models.clone().unwrap_or_default(),
deployments: block.deployments.clone(),
};
if block.served_models.is_some() && recorded == served {
continue;
}
match self.config.set_deployments(id, &served) {
Ok(()) => {
tracing::info!(
provider = id,
count = served.models.len(),
"recorded deployments"
);
changed = true;
}
Err(error) => {
tracing::warn!(%error, provider = id, "could not record deployments")
}
}
}
}
changed
}
}
/// What a resource has deployed, split between the providers that reach it, using a key that has
/// just been typed.
///
/// Sent as `api-key`, which every Azure data plane accepts for a key. `None` on any failure,
/// including a refusal: a key that cannot list deployments may still run models (a role scoped to
/// inference), so the ordinary verification gets the final say on whether the key is good.
pub(super) async fn discover_with_key<'a>(
descriptor: &'a ProviderDescriptor,
resource_root: &str,
key: &ApiKey,
) -> Option<Vec<(&'a str, deployments::Served)>> {
let url = deployments::listing_url(&descriptor.endpoint_for(resource_root))?;
let auth = KeyStyle::AzureKey.headers(key);
match tokio::time::timeout(REMOTE_PROBE_TIMEOUT, deployments::list(&url, &auth)).await {
Ok(Ok(found)) if !found.is_empty() => {
Some(deployments::partition(&deployments::group(descriptor), &found))
}
Ok(Ok(_)) => None,
Ok(Err(error)) => {
tracing::debug!(provider = %descriptor.id, %error, "deployments not listed at login");
None
}
Err(_) => None,
}
}

View File

@@ -0,0 +1,166 @@
//! Status — how each provider's credential resolves, and the wizard rows built from it.
//!
//! A listing asks the same question of every catalog entry, so the files that answer it are read
//! once into a [`Declared`] and handed to each row instead of re-parsed per provider.
use std::collections::{BTreeMap, BTreeSet};
use luxe_core::auth::{AuthMethod, CredentialStatus, ProviderOption};
use super::{ProviderAuth, ProviderDescriptor};
use crate::auth::config_file::declared_in;
use crate::auth::credential::Credential;
use crate::config::{models_config_from, ModelsConfig};
/// What the credential store and `models.json` say right now.
///
/// Both parse as [`ModelsConfig`], which is how the legacy nested `auth.json` shape
/// (`providers.<id>.api_key`) keeps working.
pub(super) struct Declared {
credentials: BTreeMap<String, Credential>,
store: Option<ModelsConfig>,
config: Option<ModelsConfig>,
config_providers: Vec<String>,
}
impl ProviderAuth {
/// Read the credential store and `models.json`, once.
pub(super) fn declared(&self) -> Declared {
let stored = self.store.read();
let configured = self.config.read();
Declared {
credentials: stored
.as_ref()
.map(|root| self.store.credentials_in(root))
.unwrap_or_default(),
config_providers: configured.as_ref().map(declared_in).unwrap_or_default(),
store: stored.and_then(typed),
config: configured.and_then(typed),
}
}
/// Every provider the wizard lists: the catalog's, then whatever the user configured that it
/// has never heard of.
///
/// A custom endpoint, a proxy or a hand-written provider block must show up, or a working
/// setup would look unconfigured — including to the first-run check, which would then reopen
/// the wizard on every launch.
pub(super) fn options(&self) -> Vec<ProviderOption> {
let declared = self.declared();
let mut options: Vec<ProviderOption> = crate::auth::provider_descriptors()
.iter()
.map(|descriptor| self.option(&declared, descriptor))
.collect();
let others: BTreeSet<&String> =
declared.credentials.keys().chain(&declared.config_providers).collect();
for id in others {
if options.iter().any(|option| &option.id == id) {
continue;
}
let status = self.status_for(&declared, id, &[]);
if !status.is_configured() {
continue;
}
options.push(ProviderOption {
name: id.clone(),
id: id.clone(),
methods: vec![AuthMethod::api_key(None)],
status,
note: None,
console_url: None,
keyless: false,
// It was configured by hand, so its endpoint is already settled.
needs_endpoint: false,
});
}
options
}
/// How a provider's credential currently resolves.
///
/// Same precedence the runtime applies: a stored credential, then an ambient environment
/// variable, then a key written by hand into a provider block. The last one matters more than it
/// looks — someone whose `models.json` already works must not be shown a first-run wizard.
///
/// A keyless provider has none of those and is still configured once it has been connected:
/// its block in `models.json` is the record, which is why [`Self::login_local`] writes one
/// even for the default endpoint.
fn status(&self, declared: &Declared, descriptor: &ProviderDescriptor) -> CredentialStatus {
match self.status_for(declared, &descriptor.id, descriptor.env) {
CredentialStatus::Missing if descriptor.keyless => {
match declared_endpoint(declared, descriptor) {
Some(endpoint) => CredentialStatus::Local(endpoint),
None => CredentialStatus::Missing,
}
}
resolved => resolved,
}
}
/// The credential half of [`Self::status`], for a provider the catalog has never heard of.
fn status_for(&self, declared: &Declared, id: &str, env: &[&str]) -> CredentialStatus {
if let Some(credential) = declared.credentials.get(id) {
return CredentialStatus::Stored(credential.info());
}
for name in env {
if std::env::var(name).is_ok_and(|value| !value.trim().is_empty()) {
return CredentialStatus::Env((*name).to_string());
}
}
match self.declared_key(declared, id) {
Some(file) => CredentialStatus::Config(file),
None => CredentialStatus::Missing,
}
}
/// The config file declaring an API key for `id`, if one does.
fn declared_key(&self, declared: &Declared, id: &str) -> Option<String> {
let files = [
(self.store.path(), declared.store.as_ref()),
(self.config.path(), declared.config.as_ref()),
];
files.into_iter().find_map(|(path, config)| {
let provider = config?.providers.get(id)?;
let has_key = provider.api_key.as_ref().is_some_and(|key| !key.is_empty());
has_key.then(|| {
path.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| path.display().to_string())
})
})
}
/// The wizard row for one provider.
fn option(&self, declared: &Declared, descriptor: &ProviderDescriptor) -> ProviderOption {
ProviderOption {
id: descriptor.id.to_string(),
name: descriptor.name.to_string(),
methods: descriptor.methods(),
status: self.status(declared, descriptor),
note: descriptor.note.map(str::to_string),
console_url: descriptor.console_url.map(str::to_string),
keyless: descriptor.keyless,
needs_endpoint: descriptor.needs_base_url,
}
}
}
/// The endpoint a connected local server was recorded at, if it was.
///
/// The block having been written is the fact; the URL in it is only what to show. A block that
/// omits one is still a connection, so it falls back to the descriptor's default rather than
/// reporting the provider as unconfigured.
fn declared_endpoint(declared: &Declared, descriptor: &ProviderDescriptor) -> Option<String> {
let block = declared.config.as_ref()?.providers.get(&*descriptor.id)?;
Some(
block
.base_url
.clone()
.or_else(|| descriptor.base_url.map(str::to_string))
.unwrap_or_else(|| "this machine".to_string()),
)
}
fn typed(root: serde_json::Map<String, serde_json::Value>) -> Option<ModelsConfig> {
models_config_from(serde_json::Value::Object(root)).ok()
}

View File

@@ -0,0 +1,781 @@
#![allow(clippy::unwrap_used)]
use super::models::parse_model_ids;
use super::*;
use local_server::LocalServer;
use luxe_core::auth::{AuthPromptKind, CredentialStatus};
use secrecy::SecretString;
use std::sync::{Arc, Mutex};
mod cleartext;
mod key_commands;
mod local_server;
mod reads;
mod verify;
/// A scripted interaction: answers in order, events recorded.
struct Scripted {
answers: Mutex<Vec<String>>,
events: Mutex<Vec<AuthEvent>>,
prompts: Mutex<Vec<AuthPrompt>>,
}
impl Scripted {
fn new(answers: &[&str]) -> Arc<Self> {
Arc::new(Self {
answers: Mutex::new(answers.iter().rev().map(|a| a.to_string()).collect()),
events: Mutex::new(Vec::new()),
prompts: Mutex::new(Vec::new()),
})
}
fn events(&self) -> Vec<AuthEvent> {
self.events.lock().unwrap().clone()
}
fn prompts(&self) -> Vec<AuthPrompt> {
self.prompts.lock().unwrap().clone()
}
}
#[async_trait::async_trait]
impl AuthInteraction for Scripted {
async fn prompt(&self, prompt: AuthPrompt) -> Result<SecretString, AuthError> {
self.prompts.lock().unwrap().push(prompt);
match self.answers.lock().unwrap().pop() {
Some(answer) => Ok(SecretString::from(answer)),
None => Err(AuthError::Cancelled),
}
}
fn notify(&self, event: AuthEvent) {
self.events.lock().unwrap().push(event);
}
}
fn service() -> (tempfile::TempDir, ProviderAuth) {
let dir = tempfile::tempdir().unwrap();
let service = ProviderAuth::with_paths(
AuthStore::new(dir.path().join("auth.json")),
ConfigFile::new(dir.path().join("models.json")),
)
.without_verification();
(dir, service)
}
#[tokio::test]
async fn an_api_key_login_stores_the_key_and_sets_the_default_provider() {
let (dir, service) = service();
let interaction = Scripted::new(&["sk-ant-live"]);
let outcome =
service.login("anthropic", "api-key", interaction.clone()).await.expect("stores the key");
assert_eq!(outcome.provider_id, "anthropic");
assert_eq!(outcome.kind, Some(CredentialKind::ApiKey));
match service.store().credential("anthropic").expect("stored") {
Credential::ApiKey(api) => assert_eq!(api.key.expose(), "sk-ant-live"),
Credential::OAuth(_) => panic!("wrong kind"),
}
let config = std::fs::read_to_string(dir.path().join("models.json")).expect("config written");
assert!(config.contains("\"default_provider\": \"anthropic\""), "got {config}");
// No provider block: the catalog already knows Anthropic's endpoint.
assert!(!config.contains("\"providers\""), "got {config}");
// The key prompt must be masked, and the ToS note has to reach the user.
assert!(matches!(interaction.prompts()[0].kind, AuthPromptKind::Secret));
assert!(interaction.events().iter().any(|event| matches!(
event,
AuthEvent::Info { message, .. } if message.contains("terms")
)));
}
#[tokio::test]
async fn an_empty_or_unresolvable_key_is_refused_before_anything_is_stored() {
let (_dir, service) = service();
let error =
service.login("openai", "api-key", Scripted::new(&[" "])).await.expect_err("must refuse");
assert!(matches!(error, AuthError::Input(_)), "got {error:?}");
assert!(service.store().credential("openai").is_none(), "nothing may be stored");
// A command spec that produces nothing fails at login, not silently at the first turn
let error = service
.login("openai", "api-key", Scripted::new(&["!printf ''"]))
.await
.expect_err("must refuse");
assert!(matches!(error, AuthError::Input(_)), "got {error:?}");
}
/// `echo` rather than `printf`, because login validates the spec by *running* it and the shell
/// that runs it is whatever the platform has — `cmd` on a Windows box without Git for Windows.
#[tokio::test]
async fn a_key_spec_is_stored_verbatim_so_the_secret_stays_where_the_user_put_it() {
let (_dir, service) = service();
service
.login("openai", "api-key", Scripted::new(&["!echo sk-from-1password"]))
.await
.expect("accepts a command spec");
match service.store().credential("openai").expect("stored") {
Credential::ApiKey(api) => assert_eq!(api.key.expose(), "!echo sk-from-1password"),
Credential::OAuth(_) => panic!("wrong kind"),
}
}
#[tokio::test]
async fn an_unexpected_key_shape_warns_but_still_stores() {
let (_dir, service) = service();
let interaction = Scripted::new(&["not-an-anthropic-key"]);
service.login("anthropic", "api-key", interaction.clone()).await.expect("stores anyway");
assert!(
interaction.events().iter().any(|event| matches!(
event,
AuthEvent::Info { message, .. } if message.contains("usually start with")
)),
"expected a shape warning: {:?}",
interaction.events()
);
}
#[tokio::test]
async fn cancelling_a_prompt_cancels_the_login() {
let (_dir, service) = service();
let error =
service.login("openai", "api-key", Scripted::new(&[])).await.expect_err("cancelled");
assert!(error.is_cancelled(), "got {error:?}");
}
/// Two models, as a `/models` body.
fn two_models() -> String {
r#"{"data":[{"id":"qwen3.8-27b"},{"id":"gemma-4-12b"}]}"#.to_string()
}
/// Connecting a local server has to leave something behind. It stores no credential, so the
/// provider block is the whole record — and the next launch reads it to decide whether this
/// machine can run a turn at all.
#[tokio::test]
async fn connecting_a_local_server_records_where_it_is() {
let server = LocalServer::start(&two_models());
let (dir, service) = service();
let outcome = service
.login("lmstudio", "local", Scripted::new(&[&server.endpoint]))
.await
.expect("the server answered");
// Whatever the server reported, in the order the list settles into.
assert_eq!(outcome.suggested_model.as_deref(), Some("gemma-4-12b"));
assert!(service.store().credential("lmstudio").is_none(), "nothing to store, so nothing is");
let config: serde_json::Value = serde_json::from_str(
&std::fs::read_to_string(dir.path().join("models.json")).expect("config"),
)
.unwrap();
assert_eq!(config["providers"]["lmstudio"]["base_url"], server.endpoint);
assert_eq!(config["default_provider"], "lmstudio");
// And what it is serving, which no catalog can answer for a machine it has never seen.
assert_eq!(
config["providers"]["lmstudio"]["served_models"],
serde_json::json!(["gemma-4-12b", "qwen3.8-27b"])
);
// Which is what makes the machine configured from here on.
assert!(matches!(
service.provider("lmstudio").expect("in catalog").status,
CredentialStatus::Local(_)
));
assert!(service.any_configured());
}
/// A local list is a fact about this machine a moment ago, so it is re-asked rather than
/// remembered: loading a model changes what the picker should offer, and only the endpoint
/// knows. A server that is switched off leaves the recorded list standing rather than
/// emptying the picker.
#[tokio::test]
async fn a_local_servers_list_is_re_asked_and_survives_the_server_going_away() {
let loaded = r#"{"data":[{"id":"qwen3.8-27b"},{"id":"gemma-4-12b"},{"id":"gpt-oss-20b"}]}"#;
let mut server = LocalServer::start(&two_models());
let (dir, service) = service();
let models = dir.path().join("models.json");
std::fs::write(
&models,
format!(r#"{{"providers": {{"lmstudio": {{"base_url": "{}"}}}}}}"#, server.endpoint),
)
.expect("the config");
let served = |path: &std::path::Path| -> Vec<String> {
crate::config::load_models_config(path)
.expect("loads")
.providers
.get("lmstudio")
.and_then(|block| block.served_models.clone())
.unwrap_or_default()
};
assert!(service.refresh_local_models().await, "the first answer is news");
assert_eq!(served(&models), vec!["gemma-4-12b".to_string(), "qwen3.8-27b".to_string()]);
// A model was loaded since, so the recorded list moves with it.
server.serves(loaded);
assert!(service.refresh_local_models().await, "a different answer is news too");
assert_eq!(
served(&models),
vec!["gemma-4-12b".to_string(), "gpt-oss-20b".to_string(), "qwen3.8-27b".to_string()]
);
// A server that is up with nothing loaded is not a server with no models: LM Studio
// loads on demand, so an empty answer must not erase what this machine is known to have.
server.serves(r#"{"data":[]}"#);
assert!(!service.refresh_local_models().await, "an empty answer is not news");
assert_eq!(served(&models).len(), 3, "and it does not wipe the list");
// The server has gone. Nothing changes, and nothing is lost.
server.stop();
assert!(!service.refresh_local_models().await, "an unreachable server is not news");
assert_eq!(served(&models).len(), 3, "the recorded list stands in");
}
/// A probe races `LOCAL_PROBE_TIMEOUT`, so a client that gives up leaves an accepted
/// connection that never became a request. What the server answers must not move because of
/// one: this failed on a loaded Windows runner and nowhere else, because the mock used to hand
/// out one scripted reply per accept and a dead connection ate the next test's answer.
#[tokio::test]
async fn a_connection_that_never_asks_does_not_shift_the_answer() {
let server = LocalServer::start(&two_models());
let (dir, service) = service();
let models = dir.path().join("models.json");
std::fs::write(
&models,
format!(r#"{{"providers": {{"lmstudio": {{"base_url": "{}"}}}}}}"#, server.endpoint),
)
.expect("the config");
let address = server.endpoint.trim_start_matches("http://").trim_end_matches("/v1").to_string();
for _ in 0..3 {
drop(std::net::TcpStream::connect(&address).expect("the mock is listening"));
}
assert!(service.refresh_local_models().await, "the real request still gets the answer");
let served = crate::config::load_models_config(&models)
.expect("loads")
.providers
.get("lmstudio")
.and_then(|block| block.served_models.clone())
.unwrap_or_default();
assert_eq!(served, vec!["gemma-4-12b".to_string(), "qwen3.8-27b".to_string()]);
}
/// A Foundry resource's deployment listing, as the resource spells it: the models it runs are
/// not the names it runs them under, and some of them cannot hold a conversation.
const FOUNDRY_LISTING: &str = r#"{"data": [
{"id": "gpt-5.6-sol", "model": "gpt-5.6-sol", "status": "succeeded", "object": "deployment"},
{"id": "gpt-realtime", "model": "gpt-realtime", "status": "succeeded", "object": "deployment"},
{"id": "claude-opus-5", "model": "claude-opus-5", "status": "succeeded", "object": "deployment"},
{"id": "Kimi-K2-Thinking", "model": "Kimi-K2.5", "status": "succeeded", "object": "deployment"}
], "object": "list"}"#;
/// What a provider's block records after discovery.
fn recorded(path: &std::path::Path, provider: &str) -> (Vec<String>, Vec<(String, String)>) {
let config = crate::config::load_models_config(path).expect("loads");
let block = config.providers.get(provider).cloned().unwrap_or_default();
(block.served_models.unwrap_or_default(), block.deployments.into_iter().collect())
}
/// The picker offers what the resource has deployed rather than what Azure sells, which was
/// the defect: `claude-opus-5-5` offered beside a resource that only has `claude-opus-5`.
#[tokio::test]
async fn a_foundry_resource_is_asked_what_it_has_deployed() {
let mut server = LocalServer::start(FOUNDRY_LISTING);
let root = server.endpoint.trim_end_matches("/v1").to_string();
let (dir, service) = service();
let models = dir.path().join("models.json");
std::fs::write(
&models,
serde_json::json!({ "providers": {
"foundry-openai": { "base_url": format!("{root}/openai/v1"), "api_key": "fk" },
"foundry-anthropic": { "base_url": format!("{root}/anthropic/v1") },
"foundry-completions": { "base_url": format!("{root}/openai/v1") },
}})
.to_string(),
)
.expect("the config");
assert!(service.refresh_deployments().await, "the first answer is news");
assert_eq!(recorded(&models, "foundry-openai").0, ["gpt-5.6-sol"], "no realtime model");
assert_eq!(recorded(&models, "foundry-anthropic").0, ["claude-opus-5"]);
assert_eq!(
recorded(&models, "foundry-completions"),
(
vec!["Kimi-K2-Thinking".to_string()],
vec![("Kimi-K2-Thinking".to_string(), "Kimi-K2.5".to_string())]
),
"routed by the model it runs, which is also what its metadata is looked up under"
);
assert!(!service.refresh_deployments().await, "the same answer is not news");
// The route going away, or the resource going quiet, leaves the record standing
server.serves(r#"{"error": {"code": "404"}}"#);
assert!(!service.refresh_deployments().await);
server.stop();
assert!(!service.refresh_deployments().await);
assert_eq!(recorded(&models, "foundry-anthropic").0, ["claude-opus-5"]);
}
/// `discover_deployments: false` is the switch the listing request answers to, and a list
/// written by hand under it is never overwritten.
#[tokio::test]
async fn a_resource_with_discovery_off_is_never_asked() {
let server = LocalServer::start(FOUNDRY_LISTING);
let root = server.endpoint.trim_end_matches("/v1").to_string();
let (dir, service) = service();
let models = dir.path().join("models.json");
std::fs::write(
&models,
serde_json::json!({ "providers": {
"foundry-openai": { "base_url": format!("{root}/openai/v1"), "api_key": "fk" },
"foundry-anthropic": {
"base_url": format!("{root}/anthropic/v1"),
"discover_deployments": false,
"served_models": ["sonnet-prod"],
},
}})
.to_string(),
)
.expect("the config");
assert!(!service.refresh_deployments().await);
assert_eq!(recorded(&models, "foundry-anthropic").0, ["sonnet-prod"]);
assert!(recorded(&models, "foundry-openai").0.is_empty(), "one switch covers the resource");
}
/// Logging in reads the deployments with the key just typed, records them for every surface
/// and suggests one that is actually deployed rather than one Azure merely offers.
#[tokio::test]
async fn a_foundry_login_records_the_deployments_it_found() {
let server = LocalServer::start(FOUNDRY_LISTING);
let root = server.endpoint.trim_end_matches("/v1").to_string();
let dir = tempfile::tempdir().unwrap();
let service = ProviderAuth::with_paths(
AuthStore::new(dir.path().join("auth.json")),
ConfigFile::new(dir.path().join("models.json")),
);
let outcome = service
.login("foundry-anthropic", "api-key", Scripted::new(&[&root, "fk-live"]))
.await
.expect("configured");
assert_eq!(outcome.suggested_model.as_deref(), Some("claude-opus-5"));
assert!(
outcome.notes.iter().any(|note| note.contains("3 chat deployments")),
"{:?}",
outcome.notes
);
let models = dir.path().join("models.json");
assert_eq!(recorded(&models, "foundry-anthropic").0, ["claude-opus-5"]);
assert_eq!(recorded(&models, "foundry-openai").0, ["gpt-5.6-sol"]);
}
#[tokio::test]
async fn a_custom_endpoint_asks_what_it_is_and_records_a_provider_block() {
let (dir, service) = service();
let interaction =
Scripted::new(&["my-proxy", "https://proxy.internal/v1", "openai-responses", "sk-x"]);
let outcome = service.login("custom", "api-key", interaction).await.expect("configured");
assert_eq!(outcome.provider_id, "my-proxy");
assert!(service.store().credential("my-proxy").is_some());
let config: serde_json::Value = serde_json::from_str(
&std::fs::read_to_string(dir.path().join("models.json")).expect("config"),
)
.unwrap();
assert_eq!(config["providers"]["my-proxy"]["base_url"], "https://proxy.internal/v1");
assert_eq!(config["providers"]["my-proxy"]["compat"]["use_responses_api"], true);
assert_eq!(config["default_provider"], "my-proxy");
}
/// One resource, one key, three wire APIs. Whichever surface is named, all three end up
/// reachable — each with its own path, its own API and the shared metadata catalog.
#[tokio::test]
async fn a_foundry_login_configures_every_surface_from_one_resource() {
const SURFACES: [(&str, &str, &str); 3] = [
("foundry-openai", "openai-responses", "/openai/v1"),
("foundry-anthropic", "anthropic-messages", "/anthropic/v1"),
("foundry-completions", "openai-completions", "/openai/v1"),
];
for (named, _, _) in SURFACES {
let (dir, service) = service();
let outcome = service
.login(named, "api-key", Scripted::new(&["acme-foundry", "fk-live"]))
.await
.expect("configures the resource");
assert_eq!(outcome.provider_id, named);
let config =
crate::config::load_models_config(&dir.path().join("models.json")).expect("loads");
for (id, api, path) in SURFACES {
match service.store().credential(id).expect("every surface holds the key") {
Credential::ApiKey(key) => assert_eq!(key.key.expose(), "fk-live"),
Credential::OAuth(_) => panic!("wrong kind"),
}
let block = config.providers.get(id).expect("block");
assert_eq!(
block.base_url.as_deref(),
Some(format!("https://acme-foundry.services.ai.azure.com{path}").as_str()),
"{id}"
);
assert_eq!(block.api.as_deref(), Some(api), "{id}");
assert_eq!(block.models_dev.as_deref(), Some("azure"), "{id}");
}
// Only the surface the user asked for becomes the default; the siblings are reported,
// not silently substituted.
let raw = std::fs::read_to_string(dir.path().join("models.json")).expect("config");
let root: serde_json::Value = serde_json::from_str(&raw).unwrap();
assert_eq!(root["default_provider"], named);
assert_eq!(
outcome.notes.iter().filter(|note| note.contains("same key")).count(),
2,
"both siblings have to be visible in the outcome: {:?}",
outcome.notes
);
}
}
/// Pasting the target URI off a deployment's Details tab is what people actually do, and the
/// half they copied it from must not decide which endpoints get recorded.
#[tokio::test]
async fn a_pasted_foundry_target_uri_still_yields_both_endpoints() {
let (dir, service) = service();
service
.login(
"foundry-openai",
"api-key",
Scripted::new(&[
"https://acme-foundry.services.ai.azure.com/anthropic/v1/messages",
"fk-live",
]),
)
.await
.expect("configures the resource");
let config = crate::config::load_models_config(&dir.path().join("models.json")).expect("loads");
assert_eq!(
config.providers["foundry-openai"].base_url.as_deref(),
Some("https://acme-foundry.services.ai.azure.com/openai/v1")
);
assert_eq!(
config.providers["foundry-anthropic"].base_url.as_deref(),
Some("https://acme-foundry.services.ai.azure.com/anthropic/v1")
);
assert_eq!(
config.providers["foundry-completions"].base_url.as_deref(),
Some("https://acme-foundry.services.ai.azure.com/openai/v1")
);
}
/// `/login foundry` has to reach something, and the alias table is the only place that can say
/// which half a bare name means.
#[test]
fn the_foundry_aliases_land_on_a_real_half() {
let (_dir, service) = service();
for (typed, expected) in [
("foundry", "foundry-openai"),
("microsoft-foundry", "foundry-openai"),
("azure-foundry", "foundry-openai"),
("foundry-claude", "foundry-anthropic"),
("foundry-partners", "foundry-completions"),
] {
assert_eq!(
service.provider(typed).map(|option| option.id).as_deref(),
Some(expected),
"typed {typed}"
);
}
}
#[tokio::test]
async fn a_custom_name_that_collides_with_a_builtin_is_refused() {
let (_dir, service) = service();
let error = service
.login("custom", "api-key", Scripted::new(&["openai"]))
.await
.expect_err("must refuse");
assert!(format!("{error}").contains("already a built-in"), "got {error}");
}
#[tokio::test]
async fn a_bad_custom_name_or_url_is_refused() {
let (_dir, service) = service();
for answers in [vec!["has spaces"], vec!["ok-name", "not a url at all"]] {
let error = service
.login("custom", "api-key", Scripted::new(&answers))
.await
.expect_err("must refuse");
assert!(matches!(error, AuthError::Input(_)), "got {error:?}");
}
}
#[tokio::test]
async fn unknown_providers_and_methods_are_named_in_the_error() {
let (_dir, service) = service();
let error =
service.login("not-a-provider", "api-key", Scripted::new(&[])).await.expect_err("unknown");
assert!(matches!(error, AuthError::UnknownProvider(id) if id == "not-a-provider"));
// Anthropic has no subscription method, by decision.
let error = service.login("anthropic", "oauth", Scripted::new(&[])).await.expect_err("unknown");
assert!(matches!(error, AuthError::UnknownMethod { .. }), "got {error:?}");
}
#[test]
fn status_reports_stored_then_environment_then_missing() {
let (_dir, service) = service();
let openai = || {
service.providers().into_iter().find(|option| option.id == "openai").expect("in catalog")
};
// The host may legitimately have OPENAI_API_KEY set; only assert on the stored transition.
let before = openai().status;
service.store().put("openai", &Credential::api_key("sk")).unwrap();
assert!(matches!(openai().status, CredentialStatus::Stored(_)));
service.logout("openai").unwrap();
assert_eq!(openai().status, before, "logging out restores the ambient status");
}
/// The Configuration surface offers three lists, and a row that opens an empty one is a dead
/// end a user meets on their first launch. Each has to be non-empty against the real catalog,
/// and single-method, so choosing a provider starts its flow rather than asking again.
#[test]
fn every_login_scope_offers_providers_that_start_on_one_choice() {
use luxe_core::auth::LoginScope;
let (_dir, service) = service();
let all = service.providers();
for scope in [LoginScope::Subscription, LoginScope::ApiKey, LoginScope::LocalOrCustom] {
let scoped = scope.filter(all.clone());
assert!(!scoped.is_empty(), "{} offers nothing", scope.as_str());
for option in &scoped {
assert!(
option.default_method().is_some(),
"{} / {}: a scoped row must be unambiguous, got {:?}",
scope.as_str(),
option.id,
option.methods
);
}
}
let named = |scope: LoginScope| -> Vec<String> {
scope.filter(all.clone()).into_iter().map(|option| option.id).collect()
};
assert_eq!(
named(LoginScope::Subscription),
vec!["openai-codex", "github-copilot", "openrouter"],
"the three sanctioned subscription flows, and only those"
);
let local = named(LoginScope::LocalOrCustom);
for id in ["lmstudio", "ollama", "custom"] {
assert!(local.iter().any(|listed| listed == id), "{id} belongs in local-or-custom");
}
assert!(
named(LoginScope::ApiKey).iter().any(|id| id == "anthropic"),
"a key-only provider belongs in the key list"
);
}
/// The regression from the first live run: a custom provider's stored credential was invisible
/// to `providers()`, so the first-run wizard reopened on every launch.
#[test]
fn a_provider_the_catalog_does_not_know_still_shows_as_configured() {
let (_dir, service) = service();
service.store().put("my-proxy", &Credential::api_key("sk-proxy")).unwrap();
let listed = service.provider("my-proxy").expect("a stored credential is a provider");
assert!(listed.status.is_stored());
assert!(service.any_configured(), "a configured machine must not be offered onboarding");
assert!(service.stored().iter().any(|option| option.id == "my-proxy"));
}
/// The other half of that: a key written by hand into a provider block counts as configured.
#[test]
fn a_hand_written_provider_block_counts_as_configured() {
let dir = tempfile::tempdir().unwrap();
let models = dir.path().join("models.json");
std::fs::write(
&models,
r#"{"providers": {"anthropic": {"api_key": "!printf sk-ant-from-a-command"}}}"#,
)
.unwrap();
let service = ProviderAuth::with_paths(
AuthStore::new(dir.path().join("auth.json")),
ConfigFile::new(models),
);
let anthropic = service.provider("anthropic").expect("in catalog");
assert!(
matches!(anthropic.status, CredentialStatus::Config(ref file) if file == "models.json"),
"got {:?}",
anthropic.status
);
assert!(service.any_configured());
assert!(
!anthropic.status.is_stored(),
"a config key isn't ours to delete, so /logout must not offer it"
);
}
/// A local server has no credential to find, so "nothing is stored" and "nothing is set up"
/// are the same file contents. Its recorded block is what tells them apart — without it a
/// machine running only LM Studio is told forever that no provider is configured, and the
/// model picker it is sent to has nothing in it.
#[test]
fn a_connected_local_server_counts_as_configured() {
let dir = tempfile::tempdir().unwrap();
let models = dir.path().join("models.json");
let open = |models: &std::path::Path| {
ProviderAuth::with_paths(
AuthStore::new(dir.path().join("auth.json")),
ConfigFile::new(models.to_path_buf()),
)
};
// Nothing written yet: a keyless provider nobody has connected is still unconfigured.
std::fs::write(&models, "{}").unwrap();
let service = open(&models);
assert_eq!(service.provider("lmstudio").expect("in catalog").status, CredentialStatus::Missing);
assert!(!service.any_configured(), "a keyless provider is not configured by existing");
// Connected at a chosen endpoint: the block names where.
std::fs::write(
&models,
r#"{"providers": {"lmstudio": {"base_url": "http://127.0.0.1:4891/v1"}}}"#,
)
.unwrap();
let service = open(&models);
let lmstudio = service.provider("lmstudio").expect("in catalog");
assert_eq!(lmstudio.status, CredentialStatus::Local("http://127.0.0.1:4891/v1".to_string()));
assert!(service.any_configured(), "a machine with a local model can run turns");
assert!(!lmstudio.status.is_stored(), "there is nothing in auth.json for /logout to take");
// Connected at the catalog's own default: the block carries no URL, and the status falls
// back to the one the connection used rather than reporting nothing at all.
std::fs::write(&models, r#"{"providers": {"lmstudio": {}}}"#).unwrap();
assert_eq!(
open(&models).provider("lmstudio").expect("in catalog").status,
CredentialStatus::Local("http://127.0.0.1:1234/v1".to_string())
);
// And the rule is about keyless providers, not about having a block: a provider that
// takes a key is not configured by someone writing down its endpoint.
std::fs::write(
&models,
r#"{"providers": {"openai": {"base_url": "https://api.openai.com/v1"}}}"#,
)
.unwrap();
let service = open(&models);
if std::env::var("OPENAI_API_KEY").is_err() {
assert_eq!(
service.provider("openai").expect("in catalog").status,
CredentialStatus::Missing
);
}
}
/// The legacy nested `auth.json` shape is the same code path, and predates this phase.
#[test]
fn the_legacy_nested_auth_file_still_counts_as_configured() {
let dir = tempfile::tempdir().unwrap();
let auth = dir.path().join("auth.json");
std::fs::write(&auth, r#"{"providers": {"openai": {"api_key": "sk-legacy"}}}"#).unwrap();
let service = ProviderAuth::with_paths(
AuthStore::new(auth),
ConfigFile::new(dir.path().join("models.json")),
);
let openai = service.provider("openai").expect("in catalog");
assert!(matches!(openai.status, CredentialStatus::Config(_)), "got {:?}", openai.status);
}
/// `/login copilot` has to reach GitHub Copilot; the alias table is in the catalog, so the
/// service has to apply it on lookup or every front-end would need its own copy.
#[test]
fn lookup_accepts_the_aliases_people_type() {
let (_dir, service) = service();
for (typed, expected) in [
("copilot", "github-copilot"),
("codex", "openai-codex"),
("gemini", "google"),
("openai_compat", "openai"),
] {
assert_eq!(
service.provider(typed).map(|option| option.id).as_deref(),
Some(expected),
"typed {typed}"
);
}
assert!(service.provider("not-a-provider").is_none());
}
#[test]
fn logout_reports_whether_there_was_anything_to_remove() {
let (_dir, service) = service();
assert!(!service.logout("openai").unwrap());
service.store().put("openai", &Credential::api_key("sk")).unwrap();
assert!(service.logout("openai").unwrap());
assert!(service.store().credential("openai").is_none());
// Aliases resolve, so `/logout copilot` works.
service.store().put("github-copilot", &Credential::api_key("t")).unwrap();
assert!(service.logout("copilot").unwrap());
}
#[test]
fn stored_lists_only_providers_with_a_credential_in_the_file() {
let (_dir, service) = service();
assert!(service.stored().is_empty());
service.store().put("openai", &Credential::api_key("sk")).unwrap();
let stored: Vec<String> = service.stored().into_iter().map(|option| option.id).collect();
assert_eq!(stored, vec!["openai".to_string()]);
assert!(service.any_configured());
}
#[test]
fn model_lists_are_parsed_from_both_shapes_and_summarized() {
let ids = parse_model_ids(
r#"{"data":[{"id":"b"},{"id":"a"},{"id":"a"},{"no_id":1}],"object":"list"}"#,
);
assert_eq!(ids, vec!["a".to_string(), "b".to_string()], "sorted and deduped");
assert!(parse_model_ids("not json").is_empty());
assert!(parse_model_ids(r#"{"models":[]}"#).is_empty());
// A flat `/v1/models` list mixes in the models that answer nothing. Offering one as the
// default — which is what a local server's first entry becomes — fails on the first turn
// with no way for the reader to know why.
let mixed = parse_model_ids(
r#"{"data":[{"id":"qwen3.8-27b"},{"id":"text-embedding-nomic-embed-text-v1.5"},
{"id":"bge-reranker-v2-m3"},{"id":"text-embedding-3-large"}]}"#,
);
assert_eq!(mixed, vec!["qwen3.8-27b".to_string()]);
assert_eq!(describe_models(&[]), None);
let one = describe_models(&["only".to_string()]).unwrap();
assert_eq!(one, "1 model available (only)");
let many: Vec<String> = (0..10).map(|index| format!("m{index}")).collect();
let summary = describe_models(&many).unwrap();
assert!(summary.starts_with("10 models available (m0, m1, m2, …"), "got {summary}");
}
#[test]
fn the_suggested_model_is_one_the_account_can_actually_use() {
let openai = provider_descriptor("openai").unwrap();
// Preference order wins when it's available.
let available = vec!["gpt-4o".to_string(), "gpt-5.4".to_string(), "gpt-5".to_string()];
assert_eq!(pick_model(openai, &available).as_deref(), Some("gpt-5.4"));
// Otherwise fall back to what the endpoint offered rather than inventing an id.
assert_eq!(pick_model(openai, &["local-thing".to_string()]).as_deref(), Some("local-thing"));
assert_eq!(pick_model(openai, &[]), None);
}
#[test]
fn base_urls_are_normalized_and_nonsense_is_rejected() {
assert_eq!(normalize_base_url(" https://x.dev/v1/ ").unwrap(), "https://x.dev/v1");
assert_eq!(normalize_base_url("x.dev/v1").unwrap(), "https://x.dev/v1");
assert_eq!(normalize_base_url("http://127.0.0.1:1234/v1").unwrap(), "http://127.0.0.1:1234/v1");
assert!(normalize_base_url("").is_err());
assert!(normalize_base_url("file:///etc/passwd").is_err());
assert!(normalize_base_url("not a url").is_err());
}

View File

@@ -0,0 +1,58 @@
//! A key typed for a plain-http endpoint is something the user should be told about.
use super::*;
/// Every message the login showed, whatever it was.
fn said(interaction: &Scripted) -> String {
interaction
.events()
.into_iter()
.filter_map(|event| match event {
AuthEvent::Info { message, .. } => Some(message),
_ => None,
})
.collect::<Vec<_>>()
.join("\n")
}
async fn custom_login_at(url: &str) -> String {
let (_dir, service) = service();
let interaction = Scripted::new(&["my-proxy", url, "openai-completions", "sk-x"]);
service.login("custom", "api-key", interaction.clone()).await.expect("configured");
said(&interaction)
}
/// The key goes to whatever URL was typed, and `http://` to another machine sends it readable
/// to everyone on the path. Not refused, since a lab server on a LAN is a fair thing to point at.
#[tokio::test]
async fn a_key_for_a_plain_http_endpoint_elsewhere_comes_with_a_warning() {
let said = custom_login_at("http://192.168.1.20:8080/v1").await;
assert!(said.contains("192.168.1.20") && said.contains("unencrypted"), "got: {said}");
}
/// This machine, https and the bare host (which becomes https) have nothing to warn about.
#[tokio::test]
async fn a_key_that_stays_on_this_machine_or_travels_over_tls_is_not_warned_about() {
for url in [
"http://127.0.0.1:1234/v1",
"http://localhost:1234/v1",
"http://[::1]:1234/v1",
"https://example.com/v1",
"example.com/v1",
] {
let said = custom_login_at(url).await;
assert!(!said.contains("unencrypted"), "{url} was warned about: {said}");
}
}
/// The warning is only worth anything while the user can still say no, so it comes before the
/// key is asked for. Here nobody answers the key prompt, and the login still said it.
#[tokio::test]
async fn the_warning_comes_before_the_key_is_asked_for() {
let (_dir, service) = service();
let interaction =
Scripted::new(&["my-proxy", "http://192.168.1.20:8080/v1", "openai-completions"]);
let error = service.login("custom", "api-key", interaction.clone()).await.expect_err("no key");
assert!(error.is_cancelled(), "got {error:?}");
assert!(said(&interaction).contains("unencrypted"), "got: {}", said(&interaction));
}

View File

@@ -0,0 +1,16 @@
//! Key commands at login; unix only, since the failing command is `sh` syntax.
#![cfg(unix)]
use super::*;
/// A key command that fails says why, from its own stderr, instead of "resolved to an empty value".
#[tokio::test]
async fn a_failing_key_command_says_why_at_login() {
let (_dir, service) = service();
let error = service
.login("openai", "api-key", Scripted::new(&["!echo 'vault is locked' >&2; exit 3"]))
.await
.expect_err("must refuse");
assert!(error.to_string().contains("vault is locked"), "got {error}");
assert!(service.store().credential("openai").is_none(), "nothing may be stored");
}

View File

@@ -0,0 +1,86 @@
//! A local server standing in for LM Studio.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
/// A local server standing in for LM Studio: answers every `/models` request with whatever it
/// currently serves, until it is stopped.
///
/// The reply is keyed on what the server is *holding*, never on how many connections have
/// arrived. That distinction is load-bearing. A probe races `LOCAL_PROBE_TIMEOUT`, so a client
/// that gives up still leaves an accepted connection behind; a queue popped per accept
/// desynchronizes the moment that happens, and every later assertion reads the answer meant
/// for the one before it. That is a real failure on a loaded runner and invisible everywhere
/// else, which is the worst combination a test can have.
pub(super) struct LocalServer {
pub(super) endpoint: String,
body: Arc<Mutex<String>>,
running: Arc<AtomicBool>,
thread: Option<std::thread::JoinHandle<()>>,
}
impl LocalServer {
/// Bind a port and start answering with `body`.
pub(super) fn start(body: &str) -> Self {
use std::io::{Read, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("a port");
listener.set_nonblocking(true).expect("a non-blocking listener");
let endpoint = format!("http://{}/v1", listener.local_addr().expect("an address"));
let body = Arc::new(Mutex::new(body.to_string()));
let running = Arc::new(AtomicBool::new(true));
let (served, alive) = (Arc::clone(&body), Arc::clone(&running));
let thread = std::thread::spawn(move || {
while alive.load(Ordering::Relaxed) {
let Ok((mut sock, _)) = listener.accept() else {
std::thread::sleep(std::time::Duration::from_millis(5));
continue;
};
sock.set_nonblocking(false).expect("a blocking connection");
// Read the request before answering: closing a socket with unread bytes on it
// sends a reset, and the reply goes with it.
let mut seen = Vec::new();
let mut chunk = [0u8; 1024];
while !seen.windows(4).any(|window| window == b"\r\n\r\n") {
match sock.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(read) => seen.extend_from_slice(&chunk[..read]),
}
}
let body = served.lock().expect("the body").clone();
// `Connection: close` keeps each request on its own socket. This loop answers
// one request per `accept` and goes back to accepting, so a client entitled to
// reuse the connection puts its next request into a socket nobody will read —
// and the test that changes what the server serves then never sees the change.
// Dropping the socket closes it, but the client only learns that on its own
// schedule; on Windows it learned late enough to fail in CI while passing
// everywhere else. Every other stub in the workspace says this out loud.
let reply = crate::test_server::http_reply("200 OK", "application/json", &body);
let _ = sock.write_all(reply.as_bytes());
let _ = sock.flush();
}
});
Self { endpoint, body, running, thread: Some(thread) }
}
/// What every request from here on answers with.
pub(super) fn serves(&self, body: &str) {
*self.body.lock().expect("the body") = body.to_string();
}
/// Take the server away, and wait until the port is really gone.
pub(super) fn stop(&mut self) {
self.running.store(false, Ordering::Relaxed);
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
impl Drop for LocalServer {
fn drop(&mut self) {
self.stop();
}
}

View File

@@ -0,0 +1,38 @@
//! Listing providers reads the two config files once, not once per row.
#![cfg(target_os = "linux")]
use super::*;
/// Bytes this process has asked the kernel to read, from `/proc/self/io`.
fn bytes_read() -> Option<u64> {
let io = std::fs::read_to_string("/proc/self/io").ok()?;
io.lines().find_map(|line| line.strip_prefix("rchar: ")?.trim().parse().ok())
}
/// `providers()` called `status()` per catalog entry, and each of those re-read and parsed
/// `auth.json` and `models.json`, so a first-run check on a real config meant dozens of parses.
///
/// Measured in bytes rather than counted in code, so a read added back anywhere in the listing
/// shows up whichever function does it. Both files carry a megabyte of padding to dwarf what the
/// rest of the process reads, and each should cost that once: the counter is the whole process's,
/// so the bound leaves room for another test's small reads under `cargo test`.
#[test]
fn listing_the_providers_reads_each_file_once() {
let (dir, service) = service();
let padding = "x".repeat(1 << 20);
let models = serde_json::json!({
"providers": { "mine": { "base_url": "http://127.0.0.1:1/v1", "api_key": "k" } },
"padding": padding,
});
std::fs::write(dir.path().join("models.json"), models.to_string()).unwrap();
let auth = serde_json::json!({ "padding": padding });
std::fs::write(dir.path().join("auth.json"), auth.to_string()).unwrap();
let before = bytes_read().expect("/proc/self/io, which Linux counts reads in");
let options = service.providers();
let read = bytes_read().expect("still readable") - before;
assert!(options.iter().any(|option| option.id == "mine"), "the hand-written block is listed");
// Two files, one read each; one per catalog entry would be ~50 of them.
assert!(read < 3 << 20, "read {} MiB listing the providers", read >> 20);
}

View File

@@ -0,0 +1,86 @@
//! Verification against an endpoint that stops answering.
use super::*;
use std::time::Duration;
/// A server that accepts, reads the request and then says `reply` (possibly nothing) before going
/// quiet for good. Answers once the request has arrived, so a paused clock can start there.
async fn quiet_server(reply: &'static str) -> (String, tokio::sync::oneshot::Receiver<()>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("bind");
let endpoint = format!("http://{}/v1", listener.local_addr().expect("address"));
let (arrived, heard) = tokio::sync::oneshot::channel();
tokio::spawn(async move {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let (mut socket, _) = listener.accept().await.expect("accept");
let mut buffer = [0u8; 1024];
let _ = socket.read(&mut buffer).await;
let _ = socket.write_all(reply.as_bytes()).await;
let _ = arrived.send(());
std::future::pending::<()>().await;
});
(endpoint, heard)
}
/// Verify against `endpoint`, then let the clock run until something gives up.
///
/// The outer two minutes only exists so a verification with no bound of its own fails this test
/// instead of hanging it; the bounded one answers long before.
async fn verified_against(
endpoint: String,
heard: tokio::sync::oneshot::Receiver<()>,
) -> Option<Result<Vec<String>, AuthError>> {
let descriptor = provider_descriptor("openai").expect("in the catalog");
let verifying = tokio::spawn(async move {
verify_credential(descriptor, Some(&endpoint), &RequestAuth::none()).await
});
heard.await.expect("the request arrived");
tokio::time::pause();
tokio::time::timeout(Duration::from_secs(120), verifying).await.ok().map(|done| done.unwrap())
}
/// `luxe auth login` against an endpoint that takes the connection and never answers used to
/// wait until Ctrl-C: only the background refreshers had a timeout.
#[tokio::test]
async fn an_endpoint_that_never_answers_ends_the_verification() {
let (endpoint, heard) = quiet_server("").await;
let outcome = verified_against(endpoint, heard).await.expect("gave up on its own");
let error = outcome.expect_err("nothing came back");
assert!(matches!(error, AuthError::Network(_)), "got {error:?}");
assert!(error.to_string().contains("timed out"), "got {error}");
assert_says_it_once(&error);
}
/// Headers arrive, the body never does: the first timeout is behind us and the read is not
/// covered by it.
#[tokio::test]
async fn an_endpoint_that_stalls_mid_answer_ends_the_verification() {
let reply = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 500\r\n\r\n{\"data\":";
let (endpoint, heard) = quiet_server(reply).await;
let outcome = verified_against(endpoint, heard).await.expect("gave up on its own");
let error = outcome.expect_err("the list never finished");
assert!(matches!(error, AuthError::Network(_)), "got {error:?}");
assert!(error.to_string().contains("timed out"), "got {error}");
assert_says_it_once(&error);
}
/// Nothing listening reads as the one thing it is, not as a provider error inside a network one.
#[tokio::test]
async fn an_endpoint_that_refuses_the_connection_says_so_plainly() {
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let descriptor = provider_descriptor("openai").expect("in the catalog");
let endpoint = format!("http://127.0.0.1:{port}/v1");
let error = verify_credential(descriptor, Some(&endpoint), &RequestAuth::none())
.await
.expect_err("nothing is listening");
assert!(error.to_string().contains("could not reach"), "got {error}");
// The cause, which reqwest's own text for the error leaves out
assert!(error.to_string().to_lowercase().contains("refused"), "got {error}");
assert_says_it_once(&error);
}
/// One `network error:` prefix, and no `provider error:` from the adapters' vocabulary.
fn assert_says_it_once(error: &AuthError) {
let said = error.to_string();
assert_eq!(said.matches("network error").count(), 1, "got {said}");
assert!(!said.contains("provider error"), "got {said}");
}

View File

@@ -0,0 +1,461 @@
//! Per-request auth — what an adapter puts on the wire for *this* call.
//!
//! An adapter cannot hold a key handed to it at construction: an OAuth access token outlives that
//! assumption by about an hour, so auth is resolved per request: [`AuthSource::request_auth`]
//! returns the headers (and, for GitHub Copilot, the base URL) for one call, refreshing an expiring
//! token on the way if it has to.
//!
//! Two implementations. [`StaticAuth`] is a fixed key in a provider-appropriate header.
//! [`StoreAuth`] reads the credential store, under a key named for the run and over the provider's
//! variables and configured key, so a `/login` mid-session takes effect on the next turn and a
//! rotating token stays fresh without rebuilding the engine.
use std::sync::Arc;
use luxe_core::auth::ApiKind;
use luxe_core::provider::ProviderError;
use tokio::sync::Mutex;
use super::catalog::{provider_descriptor, OauthFlow, ProviderDescriptor};
use super::credential::{now_ms, Credential, OAuthCredential};
use super::store::AuthStore;
use crate::config::{resolve_value_async, ApiKey};
mod key_style;
pub use key_style::KeyStyle;
/// Refresh a token this far ahead of its expiry.
///
/// Long enough that a turn started at the boundary can't have its token die mid-stream; short
/// enough that we aren't refreshing constantly.
const REFRESH_MARGIN_MS: u64 = 5 * 60 * 1000;
/// `key`, once it is remembered for redaction: every credential a request carries passes one of
/// [`RequestAuth`]'s key constructors, so this is where a shapeless one becomes known.
fn remembered(key: &ApiKey) -> &ApiKey {
luxe_core::redact::process_secrets().add(key.expose());
key
}
/// The auth a single request should carry.
///
/// Header values are [`ApiKey`]-wrapped whether or not they're secret, so a `Debug` of this struct
/// can never print a token — the cost is that a boring value reads as `[REDACTED]` too.
#[derive(Debug, Clone, Default)]
pub struct RequestAuth {
/// Headers to set, in order.
pub headers: Vec<(String, ApiKey)>,
/// Base URL this credential must be used against, when the provider hands out a
/// per-account endpoint (Copilot's `proxy-ep`). Overrides the adapter's configured base URL.
pub base_url: Option<String>,
}
impl RequestAuth {
/// No auth at all — a local server that doesn't check.
pub fn none() -> Self {
Self::default()
}
/// `Authorization: Bearer <key>`.
pub fn bearer(key: &ApiKey) -> Self {
let key = remembered(key);
Self {
headers: vec![(
"Authorization".to_string(),
ApiKey::new(format!("Bearer {}", key.expose())),
)],
base_url: None,
}
}
/// Anthropic's `x-api-key` (it rejects `Authorization: Bearer`).
pub fn anthropic_key(key: &ApiKey) -> Self {
let key = remembered(key);
Self { headers: vec![("x-api-key".to_string(), key.clone())], base_url: None }
}
/// Azure's `api-key`, which every Microsoft Foundry surface accepts.
pub fn azure_key(key: &ApiKey) -> Self {
let key = remembered(key);
Self { headers: vec![("api-key".to_string(), key.clone())], base_url: None }
}
/// Both `x-api-key` and `api-key`, for Foundry's Anthropic passthrough.
///
/// The endpoint authenticates on `x-api-key` and its own portal samples show `api-key`, so
/// Anthropic's `AnthropicFoundry` client sends the pair and so does Luxe. One header would
/// work today against a 401 that costs a user an evening.
pub fn foundry_key(key: &ApiKey) -> Self {
let key = remembered(key);
Self {
headers: vec![
("x-api-key".to_string(), key.clone()),
("api-key".to_string(), key.clone()),
],
base_url: None,
}
}
/// Add a non-secret header.
pub fn with_header(mut self, name: &str, value: impl Into<String>) -> Self {
self.headers.push((name.to_string(), ApiKey::new(value.into())));
self
}
/// Pin the base URL for this call.
pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
self.base_url = Some(base_url.into());
self
}
/// Apply every header to a request builder.
pub fn apply(&self, mut request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
for (name, value) in &self.headers {
request = request.header(name.as_str(), value.expose());
}
request
}
/// Whether anything was resolved (a keyless local server resolves to nothing).
pub fn is_empty(&self) -> bool {
self.headers.is_empty() && self.base_url.is_none()
}
}
/// Resolves the auth for one provider's requests.
#[async_trait::async_trait]
pub trait AuthSource: Send + Sync + std::fmt::Debug {
/// Auth for one request. Fails with [`ProviderError::Auth`] when there is no usable credential,
/// carrying a message that says how to fix it.
async fn request_auth(&self) -> Result<RequestAuth, ProviderError>;
/// The stored sign-in behind this source, for a provider that reads account details with it
/// (GitHub Copilot's plan usage). `None` for a key, or with nothing stored.
async fn oauth_credential(&self) -> Option<OAuthCredential> {
None
}
}
/// A fixed credential, resolved once at construction.
#[derive(Debug, Clone)]
pub struct StaticAuth {
auth: RequestAuth,
}
impl StaticAuth {
/// Bearer-token auth (OpenAI-compatible endpoints).
pub fn bearer(key: Option<ApiKey>) -> Self {
Self { auth: key.map(|key| RequestAuth::bearer(&key)).unwrap_or_default() }
}
/// Anthropic `x-api-key` auth.
pub fn anthropic(key: Option<ApiKey>) -> Self {
Self { auth: key.map(|key| RequestAuth::anthropic_key(&key)).unwrap_or_default() }
}
/// Auth appropriate to an API kind.
pub fn for_api(api: ApiKind, key: Option<ApiKey>) -> Self {
Self::for_style(KeyStyle::for_api(api), key)
}
/// Auth in an explicit style, for a provider whose header isn't implied by its API.
pub fn for_style(style: KeyStyle, key: Option<ApiKey>) -> Self {
Self { auth: key.map(|key| style.headers(&key)).unwrap_or_default() }
}
/// Whatever headers were resolved (used by adapters that also accept a `StoreAuth`).
pub fn into_arc(self) -> Arc<dyn AuthSource> {
Arc::new(self)
}
}
#[async_trait::async_trait]
impl AuthSource for StaticAuth {
async fn request_auth(&self) -> Result<RequestAuth, ProviderError> {
Ok(self.auth.clone())
}
}
/// Credential-store-backed auth for one provider.
///
/// Resolution order per request: the stored credential, then an ambient environment variable, then
/// the fallback supplied by the CLI/config. A stored credential wins so that logging out of a
/// provider doesn't silently fall back to a stale env var the user forgot about — except that an
/// explicit fallback (a `--api-key` flag) is *above* everything, since it was typed for this run.
#[derive(Debug)]
pub struct StoreAuth {
store: AuthStore,
provider_id: String,
/// How a resolved key goes on the wire.
key_style: KeyStyle,
/// OAuth flow to use when the stored credential needs refreshing.
flow: Option<OauthFlow>,
/// Env var names to consult when nothing is stored.
env: Vec<String>,
/// A key from the CLI/config, used when nothing is stored and no env var is set.
fallback: Option<ApiKey>,
/// A `--api-key`-style override that beats even a stored credential.
override_key: Option<ApiKey>,
/// How long a `!command` key may take to print.
command_deadline: std::time::Duration,
/// Whether this provider needs no credential.
keyless: bool,
/// Serializes refreshes inside this process; the store's file lock covers other processes.
refresh_lock: Mutex<()>,
}
impl StoreAuth {
/// Build a source for `provider_id`, taking defaults from the catalog when it knows the
/// provider.
pub fn new(store: AuthStore, provider_id: impl Into<String>, api: ApiKind) -> Self {
let provider_id = provider_id.into();
let descriptor = provider_descriptor(&provider_id);
Self {
store,
key_style: descriptor
.map(ProviderDescriptor::key_style)
.unwrap_or_else(|| KeyStyle::for_api(api)),
flow: descriptor.and_then(|descriptor| descriptor.oauth_flow()),
env: descriptor
.map(|descriptor| descriptor.env.iter().map(|name| name.to_string()).collect())
.unwrap_or_default(),
keyless: descriptor.is_some_and(|descriptor| descriptor.keyless),
provider_id,
fallback: None,
override_key: None,
command_deadline: luxe_core::secret_command::SECRET_COMMAND_TIMEOUT,
refresh_lock: Mutex::new(()),
}
}
/// A key from config, used only when nothing is stored and no env var is set.
pub fn with_fallback(mut self, key: Option<ApiKey>) -> Self {
self.fallback = key;
self
}
/// A key from the command line, which beats everything.
pub fn with_override(mut self, key: Option<ApiKey>) -> Self {
self.override_key = key;
self
}
/// Additional environment variables to consult (a user-declared provider).
pub fn with_env(mut self, env: Vec<String>) -> Self {
self.env.extend(env);
self
}
/// Override the header style, for a provider block that names one.
pub fn with_key_style(mut self, style: Option<KeyStyle>) -> Self {
if let Some(style) = style {
self.key_style = style;
}
self
}
/// Bound a `!command` key by `deadline` instead of the default.
pub fn with_command_deadline(mut self, deadline: std::time::Duration) -> Self {
self.command_deadline = deadline;
self
}
/// Treat a missing credential as fine (a local server).
pub fn keyless(mut self, keyless: bool) -> Self {
self.keyless = keyless;
self
}
/// Wrap in an `Arc` for an adapter.
pub fn into_arc(self) -> Arc<dyn AuthSource> {
Arc::new(self)
}
fn env_key(&self) -> Option<ApiKey> {
self.env
.iter()
.filter_map(|name| std::env::var(name).ok())
.map(|value| value.trim().to_string())
.find(|value| !value.is_empty())
.map(ApiKey::new)
}
/// Turn a resolved credential into request headers.
async fn derive(&self, credential: &Credential) -> Result<RequestAuth, ProviderError> {
match credential {
Credential::ApiKey(api) => {
// `$ENV` / `!command` specs are expanded here, at the moment of use — never while
// listing credentials.
let resolved = self.resolve(&api.key).await?;
if resolved.trim().is_empty() {
return Err(self.missing("its stored key resolved to nothing"));
}
Ok(self.api_key_auth(&ApiKey::new(resolved)))
}
Credential::OAuth(oauth) => self.oauth_auth(oauth),
}
}
/// A key spec as its value; a `!command` runs bounded, off the runtime thread.
async fn resolve(&self, key: &ApiKey) -> Result<String, ProviderError> {
resolve_value_async(key.expose(), self.command_deadline)
.await
.map_err(|reason| self.missing(&reason))
}
/// An override or fallback spec as a key, `None` when absent or when it expands to nothing.
///
/// Resolved on every call with nothing cached, so a short-lived token from a `!command` is
/// fresh for each request. A local server needs no key, so a spec that will not resolve is no
/// reason to stop there.
async fn resolve_spec(&self, spec: Option<&ApiKey>) -> Result<Option<ApiKey>, String> {
let Some(spec) = spec else { return Ok(None) };
match resolve_value_async(spec.expose(), self.command_deadline).await {
Ok(value) if !value.trim().is_empty() => Ok(Some(ApiKey::new(value))),
Err(reason) if !self.keyless => Err(reason),
_ => Ok(None),
}
}
/// The override, resolved. Signing in would not help when it fails, since it outranks the
/// store, so its error says which key it was rather than pointing at `luxe auth login`.
async fn resolved_override(&self) -> Result<Option<ApiKey>, ProviderError> {
self.resolve_spec(self.override_key.as_ref()).await.map_err(|reason| {
ProviderError::Auth(format!(
"the key given for '{}' on this run could not be read — {reason}",
self.provider_id
))
})
}
fn api_key_auth(&self, key: &ApiKey) -> RequestAuth {
self.key_style.headers(key)
}
/// OAuth headers, which are provider-specific beyond the bearer token.
fn oauth_auth(&self, oauth: &OAuthCredential) -> Result<RequestAuth, ProviderError> {
let mut auth = RequestAuth::bearer(&oauth.access);
match self.flow {
Some(OauthFlow::OpenaiCodex) => {
let account = oauth
.account
.clone()
.or_else(|| super::oauth::openai_codex::account_id(oauth.access.expose()))
.ok_or_else(|| {
self.missing("its ChatGPT credential carries no account id; sign in again")
})?;
auth = auth
.with_header("chatgpt-account-id", account)
.with_header("OpenAI-Beta", "responses=experimental")
.with_header("originator", super::oauth::openai_codex::originator());
}
Some(OauthFlow::GithubCopilot) => {
for (name, value) in super::oauth::github_copilot::EDITOR_HEADERS {
auth = auth.with_header(name, *value);
}
let base = oauth.endpoint.clone().unwrap_or_else(|| {
super::oauth::github_copilot::api_base_url(
oauth.access.expose(),
oauth.enterprise_domain.as_deref(),
)
});
auth = auth.with_base_url(base);
}
// OpenRouter's flow mints a plain API key, so it never lands here.
Some(OauthFlow::OpenRouter) | None => {}
}
Ok(auth)
}
/// Refresh the stored OAuth credential if it's within the margin of expiry.
///
/// Double-checked: the cheap check happens outside the lock, the authoritative one inside, so
/// concurrent turns produce exactly one refresh and the rotated token is persisted before any of
/// them reads it.
async fn refreshed(&self, current: OAuthCredential) -> Result<OAuthCredential, ProviderError> {
if current.expires_at_ms == 0 || now_ms() + REFRESH_MARGIN_MS < current.expires_at_ms {
return Ok(current);
}
let Some(flow) = self.flow else { return Ok(current) };
let _guard = self.refresh_lock.lock().await;
// Re-read under the lock: another task may have refreshed while we waited.
let latest = self
.store
.credential(&self.provider_id)
.and_then(|credential| credential.as_oauth().cloned())
.unwrap_or(current);
if latest.expires_at_ms != 0 && now_ms() + REFRESH_MARGIN_MS < latest.expires_at_ms {
return Ok(latest);
}
tracing::debug!(provider = %self.provider_id, "refreshing an expiring OAuth token");
let refreshed = super::oauth::refresh(flow, &latest).await.map_err(|error| {
ProviderError::Auth(format!(
"{}: could not refresh the stored credential ({error}) — run `luxe auth login {}`",
self.provider_id, self.provider_id
))
})?;
if let Err(error) = self.store.put(&self.provider_id, &Credential::OAuth(refreshed.clone()))
{
// A token we can't persist still works for this request; the next process pays again.
tracing::warn!(provider = %self.provider_id, %error, "could not persist refreshed token");
}
Ok(refreshed)
}
fn missing(&self, reason: &str) -> ProviderError {
ProviderError::Auth(format!(
"no credential for '{provider}' — {reason}. Run `luxe auth login {provider}` (or \
`/login {provider}` in the TUI).",
provider = self.provider_id
))
}
}
#[async_trait::async_trait]
impl AuthSource for StoreAuth {
async fn oauth_credential(&self) -> Option<OAuthCredential> {
// a key typed for this run outranks the store, so the store's sign-in is not this run's,
// unless that key expands to nothing and `request_auth` falls through to the store too
if !matches!(self.resolved_override().await, Ok(None)) {
return None;
}
self.store
.credential(&self.provider_id)
.and_then(|credential| credential.as_oauth().cloned())
}
async fn request_auth(&self) -> Result<RequestAuth, ProviderError> {
// An explicit command-line key is the user speaking about this run specifically.
if let Some(key) = self.resolved_override().await? {
return Ok(self.api_key_auth(&key));
}
if let Some(credential) = self.store.credential(&self.provider_id) {
return match credential {
Credential::OAuth(oauth) => {
let fresh = self.refreshed(oauth).await?;
self.derive(&Credential::OAuth(fresh)).await
}
api_key => self.derive(&api_key).await,
};
}
if let Some(key) = self.env_key() {
return Ok(self.api_key_auth(&key));
}
if let Some(key) = self
.resolve_spec(self.fallback.as_ref())
.await
.map_err(|reason| self.missing(&reason))?
{
return Ok(self.api_key_auth(&key));
}
if self.keyless {
return Ok(RequestAuth::none());
}
Err(self.missing("nothing is stored and no environment variable is set"))
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,60 @@
//! Key style — which header a provider's API key goes out in.
use luxe_core::auth::ApiKind;
use super::RequestAuth;
use crate::config::ApiKey;
/// How a provider wants an API key presented.
///
/// Derivable from [`ApiKind`] for every provider that speaks a vendor's own API, and *not*
/// derivable for a host that re-serves someone else's: Microsoft Foundry's Anthropic passthrough
/// speaks Anthropic Messages but authenticates the Azure way. So the style travels with the
/// provider, and a `models.json` block can override it — which is also how a Microsoft Entra ID
/// token reaches a Foundry endpoint, since a bearer token is just a different style over the same
/// `!command` credential.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum KeyStyle {
/// `Authorization: Bearer <key>`
#[default]
Bearer,
/// `x-api-key: <key>`
AnthropicKey,
/// `api-key: <key>`
AzureKey,
/// `x-api-key: <key>` and `api-key: <key>`
FoundryKey,
}
impl KeyStyle {
/// The style a provider speaking `api` uses unless it says otherwise.
pub fn for_api(api: ApiKind) -> Self {
match api {
ApiKind::AnthropicMessages => Self::AnthropicKey,
_ => Self::Bearer,
}
}
/// Parse the `auth` value of a `models.json` provider block.
///
/// Spelled as the header a user reads off a failing request rather than as a vendor name.
pub fn parse(raw: &str) -> Option<Self> {
match raw.trim().to_ascii_lowercase().replace('_', "-").as_str() {
"bearer" | "authorization" => Some(Self::Bearer),
"x-api-key" | "anthropic" => Some(Self::AnthropicKey),
"api-key" | "azure" => Some(Self::AzureKey),
"foundry" => Some(Self::FoundryKey),
_ => None,
}
}
/// The headers `key` goes out as.
pub fn headers(self, key: &ApiKey) -> RequestAuth {
match self {
Self::Bearer => RequestAuth::bearer(key),
Self::AnthropicKey => RequestAuth::anthropic_key(key),
Self::AzureKey => RequestAuth::azure_key(key),
Self::FoundryKey => RequestAuth::foundry_key(key),
}
}
}

View File

@@ -0,0 +1,295 @@
#![allow(clippy::unwrap_used)]
use super::*;
use crate::auth::credential::{ApiKeyCredential, OAuthCredential};
fn store() -> (tempfile::TempDir, AuthStore) {
let dir = tempfile::tempdir().unwrap();
let store = AuthStore::new(dir.path().join("auth.json"));
(dir, store)
}
fn header<'a>(auth: &'a RequestAuth, name: &str) -> Option<&'a str> {
auth.headers
.iter()
.find(|(header, _)| header.eq_ignore_ascii_case(name))
.map(|(_, value)| value.expose())
}
#[tokio::test]
async fn static_auth_reproduces_the_per_api_header_style() {
let bearer = StaticAuth::for_api(ApiKind::OpenaiCompletions, Some(ApiKey::new("sk-1")))
.request_auth()
.await
.unwrap();
assert_eq!(header(&bearer, "authorization"), Some("Bearer sk-1"));
// Anthropic rejects `Authorization: Bearer`; this is the regression that would break it.
let anthropic = StaticAuth::for_api(ApiKind::AnthropicMessages, Some(ApiKey::new("sk-ant")))
.request_auth()
.await
.unwrap();
assert_eq!(header(&anthropic, "x-api-key"), Some("sk-ant"));
assert!(header(&anthropic, "authorization").is_none());
let none = StaticAuth::for_api(ApiKind::OpenaiCompletions, None).request_auth().await.unwrap();
assert!(none.is_empty());
}
/// Foundry's Anthropic passthrough authenticates on `x-api-key` and its portal samples show
/// `api-key`; Anthropic's own Foundry client sends both, so a 401 can't turn on which one this
/// endpoint happened to want today.
#[tokio::test]
async fn the_foundry_style_sends_both_key_headers_and_never_a_bearer() {
let auth = StaticAuth::for_style(KeyStyle::FoundryKey, Some(ApiKey::new("fk-1")))
.request_auth()
.await
.unwrap();
assert_eq!(header(&auth, "x-api-key"), Some("fk-1"));
assert_eq!(header(&auth, "api-key"), Some("fk-1"));
assert!(header(&auth, "authorization").is_none());
let azure = StaticAuth::for_style(KeyStyle::AzureKey, Some(ApiKey::new("az-1")))
.request_auth()
.await
.unwrap();
assert_eq!(azure.headers.len(), 1);
assert_eq!(header(&azure, "api-key"), Some("az-1"));
}
/// The catalog decides the style, not the API — which is the whole point for a host that
/// re-serves someone else's wire format.
#[tokio::test]
async fn a_stored_key_takes_the_style_its_provider_asked_for() {
let (_dir, store) = store();
store.put("foundry-anthropic", &Credential::api_key("fk-stored")).unwrap();
let source = StoreAuth::new(store, "foundry-anthropic", ApiKind::AnthropicMessages);
let auth = source.request_auth().await.unwrap();
assert_eq!(header(&auth, "x-api-key"), Some("fk-stored"));
assert_eq!(header(&auth, "api-key"), Some("fk-stored"));
}
/// A Microsoft Entra ID token is a bearer token over the same credential machinery, so the
/// override is what makes keyless auth a one-line config change rather than a feature.
#[tokio::test]
async fn a_configured_style_overrides_the_catalog() {
let (_dir, store) = store();
store.put("foundry-anthropic", &Credential::api_key("!echo entra-token")).unwrap();
let source = StoreAuth::new(store, "foundry-anthropic", ApiKind::AnthropicMessages)
.with_key_style(Some(KeyStyle::Bearer));
let auth = source.request_auth().await.unwrap();
assert_eq!(header(&auth, "authorization"), Some("Bearer entra-token"));
assert!(header(&auth, "x-api-key").is_none());
}
#[test]
fn key_styles_parse_by_the_header_a_401_shows_you() {
assert_eq!(KeyStyle::parse("bearer"), Some(KeyStyle::Bearer));
assert_eq!(KeyStyle::parse("x-api-key"), Some(KeyStyle::AnthropicKey));
assert_eq!(KeyStyle::parse(" API-KEY "), Some(KeyStyle::AzureKey));
assert_eq!(KeyStyle::parse("foundry"), Some(KeyStyle::FoundryKey));
assert_eq!(KeyStyle::parse("x_api_key"), Some(KeyStyle::AnthropicKey));
assert_eq!(KeyStyle::parse("telepathy"), None);
}
#[tokio::test]
async fn a_stored_key_is_used_and_beats_the_environment() {
let (_dir, store) = store();
store.put("openai", &Credential::api_key("sk-stored")).unwrap();
let source = StoreAuth::new(store, "openai", ApiKind::OpenaiCompletions);
let auth = source.request_auth().await.unwrap();
assert_eq!(header(&auth, "authorization"), Some("Bearer sk-stored"));
}
/// `echo`, not `printf`: the spec is run through whatever shell the platform has, and on a
/// Windows box with no Git for Windows that is `cmd`, which has `echo` and not `printf`. The
/// resolver trims, so the trailing `\r\n` cmd adds costs nothing.
#[tokio::test]
async fn a_command_key_spec_is_resolved_at_request_time() {
let (_dir, store) = store();
store
.put(
"openai",
&Credential::ApiKey(ApiKeyCredential {
key: ApiKey::new("!echo sk-from-command"),
..Default::default()
}),
)
.unwrap();
let source = StoreAuth::new(store, "openai", ApiKind::OpenaiCompletions);
let auth = source.request_auth().await.unwrap();
assert_eq!(header(&auth, "authorization"), Some("Bearer sk-from-command"));
}
/// A key command that hangs is stopped at its deadline and says why, rather than holding the turn
/// (and the runtime thread under it) for as long as it likes.
#[cfg(unix)]
#[tokio::test]
async fn a_hanging_key_command_does_not_hold_the_turn() {
let (_dir, store) = store();
store.put("openai", &Credential::api_key("!sleep 10")).unwrap();
let source = StoreAuth::new(store, "openai", ApiKind::OpenaiCompletions)
.with_command_deadline(std::time::Duration::from_millis(300));
let started = std::time::Instant::now();
let error = source.request_auth().await.unwrap_err().to_string();
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{error}");
assert!(error.contains("did not finish"), "{error}");
}
/// A local server needs no key, so a configured key command that fails still leaves it reachable.
#[tokio::test]
async fn a_keyless_provider_survives_a_failing_fallback_command() {
let (_dir, store) = store();
let source = StoreAuth::new(store, "openai", ApiKind::OpenaiCompletions)
.with_fallback(Some(ApiKey::new("!exit 1")))
.keyless(true);
assert!(source.request_auth().await.unwrap().is_empty());
}
#[tokio::test]
async fn an_override_beats_a_stored_credential() {
let (_dir, store) = store();
store.put("openai", &Credential::api_key("sk-stored")).unwrap();
let source = StoreAuth::new(store, "openai", ApiKind::OpenaiCompletions)
.with_override(Some(ApiKey::new("sk-cli")));
let auth = source.request_auth().await.unwrap();
assert_eq!(header(&auth, "authorization"), Some("Bearer sk-cli"));
}
/// Signing in cannot rescue a key that outranks the store, so a failing override names itself
/// rather than sending the reader to `luxe auth login`.
#[tokio::test]
async fn a_failing_override_says_it_was_the_key_given_for_this_run() {
let (_dir, store) = store();
let source = StoreAuth::new(store, "openai", ApiKind::OpenaiCompletions)
.with_override(Some(ApiKey::new("!exit 1")));
let error = source.request_auth().await.unwrap_err().to_string();
assert!(error.contains("the key given for 'openai' on this run"), "{error}");
assert!(!error.contains("auth login"), "{error}");
}
/// An override that expands to nothing leaves the stored sign-in in charge, for the account
/// details read with it as well as for the request.
#[tokio::test]
async fn an_override_that_expands_to_nothing_leaves_the_stored_sign_in() {
let (_dir, store) = store();
let sign_in = OAuthCredential {
access: ApiKey::new("oauth-access"),
expires_at_ms: now_ms() + 86_400_000,
..Default::default()
};
store.put("openai", &Credential::OAuth(sign_in)).unwrap();
let source = StoreAuth::new(store, "openai", ApiKind::OpenaiCompletions)
.with_override(Some(ApiKey::new("${LUXE_TEST_UNSET_OVERRIDE_KEY}")));
let auth = source.request_auth().await.unwrap();
assert_eq!(header(&auth, "authorization"), Some("Bearer oauth-access"));
assert!(source.oauth_credential().await.is_some());
}
#[tokio::test]
async fn a_config_fallback_applies_only_when_nothing_is_stored() {
let (_dir, store) = store();
let source = StoreAuth::new(store.clone(), "openai", ApiKind::OpenaiCompletions)
.with_fallback(Some(ApiKey::new("sk-config")));
assert_eq!(
header(&source.request_auth().await.unwrap(), "authorization"),
Some("Bearer sk-config")
);
store.put("openai", &Credential::api_key("sk-stored")).unwrap();
assert_eq!(
header(&source.request_auth().await.unwrap(), "authorization"),
Some("Bearer sk-stored"),
"a stored credential outranks config"
);
}
#[tokio::test]
async fn a_missing_credential_says_what_to_run() {
let (_dir, store) = store();
let source = StoreAuth::new(store, "anthropic", ApiKind::AnthropicMessages);
let error = source.request_auth().await.expect_err("no credential");
assert!(matches!(error, ProviderError::Auth(_)), "must classify as auth: {error:?}");
let message = error.to_string();
assert!(message.contains("luxe auth login anthropic"), "unhelpful: {message}");
assert!(message.contains("/login anthropic"), "unhelpful: {message}");
}
#[tokio::test]
async fn a_keyless_local_server_needs_nothing() {
let (_dir, store) = store();
let source = StoreAuth::new(store, "lmstudio", ApiKind::OpenaiCompletions);
assert!(source.request_auth().await.unwrap().is_empty());
}
#[tokio::test]
async fn copilot_headers_and_per_account_base_url_are_derived() {
let (_dir, store) = store();
store
.put(
"github-copilot",
&Credential::OAuth(OAuthCredential {
access: ApiKey::new("tid=x;proxy-ep=proxy.business.githubcopilot.com;exp=1"),
refresh: ApiKey::new("gho_x"),
// Far future so no refresh is attempted (which would need the network).
expires_at_ms: now_ms() + 86_400_000,
..Default::default()
}),
)
.unwrap();
let source = StoreAuth::new(store, "github-copilot", ApiKind::OpenaiCompletions);
let auth = source.request_auth().await.unwrap();
assert!(header(&auth, "authorization").unwrap().starts_with("Bearer tid=x"));
assert_eq!(header(&auth, "Copilot-Integration-Id"), Some("vscode-chat"));
assert_eq!(
auth.base_url.as_deref(),
Some("https://api.business.githubcopilot.com"),
"proxy-ep decides the endpoint for this account"
);
}
#[tokio::test]
async fn codex_headers_carry_the_account_id() {
let (_dir, store) = store();
store
.put(
"openai-codex",
&Credential::OAuth(OAuthCredential {
access: ApiKey::new("header.payload.sig"),
refresh: ApiKey::new("r"),
expires_at_ms: now_ms() + 86_400_000,
account: Some("acct-123".into()),
..Default::default()
}),
)
.unwrap();
let source = StoreAuth::new(store, "openai-codex", ApiKind::OpenaiCodex);
let auth = source.request_auth().await.unwrap();
assert_eq!(header(&auth, "chatgpt-account-id"), Some("acct-123"));
assert_eq!(header(&auth, "originator"), Some("luxe"));
}
#[test]
fn debug_output_never_carries_a_header_value() {
let auth = RequestAuth::bearer(&ApiKey::new("sk-super-secret"));
let rendered = format!("{auth:?}");
assert!(!rendered.contains("sk-super-secret"), "leaked: {rendered}");
}
/// A key that reaches a request header is remembered, so a tool printing it later is scrubbed even
/// when it has no shape any pattern knows.
#[test]
fn a_key_put_on_a_request_is_remembered_for_redaction() {
RequestAuth::bearer(&ApiKey::new("bearer-plain-key-4417"));
RequestAuth::anthropic_key(&ApiKey::new("anthropic-plain-key-4417"));
RequestAuth::azure_key(&ApiKey::new("azure-plain-key-4417"));
RequestAuth::foundry_key(&ApiKey::new("foundry-plain-key-4417"));
for key in ["bearer", "anthropic", "azure", "foundry"] {
let literal = format!("{key}-plain-key-4417");
let seen = luxe_core::redact::process_secrets().redact(&format!("seen {literal}"));
assert_eq!(seen, "seen [REDACTED]", "{key}");
}
// a header that is not a credential is not remembered
let _ = RequestAuth::none().with_header("anthropic-version", "2023-06-01");
assert!(luxe_core::redact::process_secrets().redact("2023-06-01").contains("2023-06-01"));
}

View File

@@ -0,0 +1,149 @@
//! Credential store — `~/.config/luxe/auth.json`, `0600`, and never lossy.
//!
//! The file is a superset of the one Luxe already read: a few reserved keys keep their
//! [`crate::config::ModelsConfig`] meaning, and every *other* top-level key is one provider's
//! [`Credential`]. An existing hand-written file keeps working, and a file written by another tool
//! that uses the same convention can be dropped in.
//!
//! Losslessness and locking come from [`JsonFile`]; this module owns the schema on top of it.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use luxe_core::auth::StoredCredentialInfo;
use super::credential::Credential;
use super::json_file::{FileError, FileMode, JsonFile};
/// Top-level keys that are configuration, not credentials.
const RESERVED_KEYS: &[&str] =
&["providers", "models", "default_provider", "default_model", "$schema"];
/// Reading or writing the auth file failed.
pub type StoreError = FileError;
/// File-backed credential store.
#[derive(Debug, Clone)]
pub struct AuthStore {
file: JsonFile,
}
impl AuthStore {
/// Store at an explicit path (tests, alternate profiles).
pub fn new(path: PathBuf) -> Self {
Self { file: JsonFile::new(path, FileMode::OwnerOnly) }
}
/// The default store: `auth.json` in Luxe's config directory, or where an older build left it.
pub fn default_path() -> Self {
Self::new(luxe_core::user_dirs::luxe_config_file("auth.json"))
}
/// Where this store reads and writes.
pub fn path(&self) -> &Path {
self.file.path()
}
/// Every credential in the file, keyed by provider id. Unparseable entries are skipped with a
/// warning and left on disk.
///
/// Never resolves `$ENV` / `!command` key specs — enumerating credentials must not run a user's
/// shell command.
pub fn credentials(&self) -> BTreeMap<String, Credential> {
let Some(root) = self.file.read() else { return BTreeMap::new() };
self.credentials_in(&root)
}
/// The whole file, parsed once, for a caller that reads it more than one way.
pub(crate) fn read(&self) -> Option<serde_json::Map<String, serde_json::Value>> {
self.file.read()
}
/// [`Self::credentials`] over a document [`Self::read`] already returned.
pub(crate) fn credentials_in(
&self,
root: &serde_json::Map<String, serde_json::Value>,
) -> BTreeMap<String, Credential> {
let mut out = BTreeMap::new();
for (key, value) in root {
if RESERVED_KEYS.contains(&key.as_str()) {
continue;
}
match Credential::from_json(value) {
Some(credential) => {
out.insert(key.clone(), credential);
}
None => tracing::warn!(
provider = %key,
path = %self.path().display(),
"skipping unrecognized auth.json entry (left untouched)"
),
}
}
out
}
/// One provider's credential, if present.
pub fn credential(&self, provider_id: &str) -> Option<Credential> {
if RESERVED_KEYS.contains(&provider_id) {
return None;
}
Credential::from_json(self.file.read()?.get(provider_id)?)
}
/// Non-secret metadata for every stored credential.
pub fn summaries(&self) -> BTreeMap<String, StoredCredentialInfo> {
self.credentials()
.into_iter()
.map(|(provider, credential)| (provider, credential.info()))
.collect()
}
/// Whether the file holds any credential at all.
pub fn is_empty(&self) -> bool {
self.credentials().is_empty()
}
/// Store (or replace) one provider's credential.
pub fn put(&self, provider_id: &str, credential: &Credential) -> Result<(), StoreError> {
self.modify(provider_id, |_| Ok(Some(credential.clone()))).map(|_| ())
}
/// Remove one provider's credential. Returns whether there was one.
pub fn remove(&self, provider_id: &str) -> Result<bool, StoreError> {
let mut existed = false;
self.modify(provider_id, |current| {
existed = current.is_some();
Ok(None)
})?;
Ok(existed)
}
/// Read-modify-write one entry under the cross-process lock.
///
/// `update` sees the credential as it is *right now* — re-read inside the lock, so a decision
/// like "is this token still expiring?" is made against the truth rather than a stale copy — and
/// returns the replacement, or `None` to delete the entry.
pub fn modify<F>(&self, provider_id: &str, update: F) -> Result<Option<Credential>, StoreError>
where
F: FnOnce(Option<Credential>) -> Result<Option<Credential>, StoreError>,
{
if RESERVED_KEYS.contains(&provider_id) {
return Err(StoreError::Rejected(format!(
"'{provider_id}' is a reserved config key, not a provider"
)));
}
self.file.modify(|root| {
let current = root.get(provider_id).and_then(Credential::from_json);
let next = update(current)?;
match &next {
Some(credential) => root.insert(provider_id.to_string(), credential.to_json()),
None => root.remove(provider_id),
};
Ok(next)
})
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,154 @@
#![allow(clippy::unwrap_used)]
use super::*;
use crate::auth::credential::{ApiKeyCredential, OAuthCredential};
use crate::config::ApiKey;
use serde_json::Value;
fn store() -> (tempfile::TempDir, AuthStore) {
let dir = tempfile::tempdir().unwrap();
let store = AuthStore::new(dir.path().join("auth.json"));
(dir, store)
}
#[test]
fn writes_and_reads_a_credential() {
let (_dir, store) = store();
assert!(store.is_empty());
assert!(store.credential("openai").is_none());
store.put("openai", &Credential::api_key("sk-test")).unwrap();
match store.credential("openai").expect("stored") {
Credential::ApiKey(api) => assert_eq!(api.key.expose(), "sk-test"),
Credential::OAuth(_) => panic!("wrong kind"),
}
assert_eq!(store.summaries().len(), 1);
assert!(store.remove("openai").unwrap());
assert!(!store.remove("openai").unwrap(), "a second remove is a no-op");
}
#[cfg(unix)]
#[test]
fn the_file_is_owner_only() {
use std::os::unix::fs::PermissionsExt;
let (_dir, store) = store();
store.put("openai", &Credential::api_key("sk-test")).unwrap();
let mode = std::fs::metadata(store.path()).unwrap().permissions().mode();
assert_eq!(mode & 0o777, 0o600, "credentials must not be group/world readable");
}
/// The one regression that would actually hurt someone: clobbering config they already had.
#[test]
fn legacy_config_and_unknown_keys_survive_a_write() {
let (_dir, store) = store();
std::fs::write(
store.path(),
r#"{
"$schema": "https://luxe.dev/auth.schema.json",
"providers": { "lmstudio": { "base_url": "http://localhost:1234/v1" } },
"default_provider": "lmstudio",
"default_model": "qwen3",
"future_thing": { "type": "webauthn", "handle": "keep me" }
}"#,
)
.unwrap();
store.put("openai", &Credential::api_key("sk-new")).unwrap();
let raw: Value = serde_json::from_str(&std::fs::read_to_string(store.path()).unwrap())
.expect("still valid JSON");
assert_eq!(raw["default_provider"], "lmstudio");
assert_eq!(raw["providers"]["lmstudio"]["base_url"], "http://localhost:1234/v1");
assert_eq!(raw["future_thing"]["handle"], "keep me", "unknown entries are preserved");
assert_eq!(raw["openai"]["key"], "sk-new");
// Reserved keys are config, never credentials; the unparseable entry is skipped, not eaten.
assert_eq!(store.credentials().keys().collect::<Vec<_>>(), vec!["openai"]);
}
/// The nested legacy shape (`providers.<id>.api_key`) is still read by the config loader, so the
/// store must not treat it as a credential entry or offer to overwrite it.
#[test]
fn reserved_keys_are_not_addressable_as_providers() {
let (_dir, store) = store();
assert!(store.credential("providers").is_none());
let error = store.put("models", &Credential::api_key("x")).expect_err("must refuse");
assert!(format!("{error}").contains("reserved"), "got: {error}");
}
#[test]
fn a_malformed_file_fails_a_write_instead_of_erasing_it() {
let (_dir, store) = store();
std::fs::write(store.path(), "{ this is not json").unwrap();
let error = store.put("openai", &Credential::api_key("sk")).expect_err("must refuse");
assert!(format!("{error}").contains("not valid JSON"), "got: {error}");
assert_eq!(std::fs::read_to_string(store.path()).unwrap(), "{ this is not json");
}
#[test]
fn modify_sees_the_current_value_and_can_delete() {
let (_dir, store) = store();
store
.put(
"github-copilot",
&Credential::OAuth(OAuthCredential {
access: ApiKey::new("old"),
refresh: ApiKey::new("gho"),
expires_at_ms: 1,
..Default::default()
}),
)
.unwrap();
let updated = store
.modify("github-copilot", |current| {
let mut oauth = current.as_ref().and_then(Credential::as_oauth).cloned().unwrap();
assert_eq!(oauth.access.expose(), "old");
oauth.access = ApiKey::new("fresh");
oauth.expires_at_ms = 99;
Ok(Some(Credential::OAuth(oauth)))
})
.unwrap();
assert_eq!(updated.unwrap().as_oauth().unwrap().access.expose(), "fresh");
assert_eq!(
store.credential("github-copilot").unwrap().as_oauth().unwrap().refresh.expose(),
"gho",
"an untouched field survives the rewrite"
);
store.modify("github-copilot", |_| Ok(None)).unwrap();
assert!(store.credential("github-copilot").is_none());
}
#[test]
fn creates_the_parent_directory() {
let dir = tempfile::tempdir().unwrap();
let store = AuthStore::new(dir.path().join("nested").join("deeper").join("auth.json"));
store.put("openai", &Credential::api_key("sk")).unwrap();
assert!(store.path().exists());
}
#[test]
fn env_scoped_values_round_trip() {
let (_dir, store) = store();
let mut env = BTreeMap::new();
env.insert("CLOUDFLARE_ACCOUNT_ID".to_string(), "acct".to_string());
store
.put("cloudflare", &Credential::ApiKey(ApiKeyCredential { key: ApiKey::new("cf"), env }))
.unwrap();
match store.credential("cloudflare").unwrap() {
Credential::ApiKey(api) => {
assert_eq!(api.env.get("CLOUDFLARE_ACCOUNT_ID").map(String::as_str), Some("acct"));
}
Credential::OAuth(_) => panic!("wrong kind"),
}
}
#[test]
fn successive_writes_release_the_lock() {
let (_dir, store) = store();
for index in 0..3 {
store.put("openai", &Credential::api_key(format!("sk-{index}"))).unwrap();
}
assert!(!store.path().with_extension("lock").exists(), "lock must not leak");
}

View File

@@ -0,0 +1,22 @@
//! Model catalog — what Luxe knows about a model, and where it learned it.
//!
//! A model released after the binary was built still has to work properly: the right context
//! window, output cap, reasoning levels, and pricing, not silent fallbacks. Metadata therefore
//! comes from four layers — build-time [`snapshot`](mod@snapshot), refreshed [`fetch`](mod@fetch)
//! cache, and the user's config on top of provider-aware defaults — merged by [`resolve`] into the
//! single [`ModelInfo`](luxe_core::provider::ModelInfo) the engine runs on.
//!
//! Everything here is offline-safe: resolution never touches the network, and the refresh is a
//! best-effort background call that a missing network simply skips.
pub mod alias;
pub mod fetch;
mod resolve;
pub mod schema;
pub mod snapshot;
pub mod store;
pub use fetch::{fetch, Fetched, MODELS_DEV_API_URL};
pub use resolve::{resolve, Layer, Provenance, Sources, DEFAULT_CONTEXT_WINDOW};
pub use schema::{parse, Catalog, Model};
pub use snapshot::snapshot;

View File

@@ -0,0 +1,87 @@
//! Id mapping between Luxe's names and models.dev's.
//!
//! Luxe provider names are user-chosen (`lmstudio`, `dashscope`, `openai_compat`) and model ids
//! are whatever the endpoint expects, so neither is guaranteed to be a models.dev key. Both
//! mappings here affect **metadata lookup only** — the wire id a provider receives is never
//! rewritten.
use crate::config::ProviderConfig;
/// Luxe provider names that don't match their models.dev id.
///
/// Deliberately tiny: almost every name maps verbatim, the provider catalog carries the rest, and a
/// user whose provider needs a different id sets `"models_dev"` on it.
const ALIASES: &[(&str, &str)] = &[
// Luxe's default provider name; an OpenAI-compatible endpoint serving `gpt-*` really is
// serving OpenAI's models, and a local server's ids simply won't match anything.
("openai_compat", "openai"),
("dashscope", "alibaba"),
];
/// The models.dev provider id to look a Luxe provider up under.
///
/// Config wins, then the provider catalog, then the alias table, then the name verbatim. Never
/// `None`: a name that matches nothing just finds no models, which is the right answer for a local
/// server.
///
/// The catalog step is what makes a subscription provider work at all: `openai-codex` is a Luxe
/// provider, not a models.dev one, and without the mapping its models resolve to no metadata (a
/// zero context window, no pricing) and never appear in the picker.
pub fn models_dev_provider<'a>(provider: &'a str, config: Option<&'a ProviderConfig>) -> &'a str {
if let Some(id) = config.and_then(|c| c.models_dev.as_deref()).filter(|id| !id.is_empty()) {
return id;
}
if let Some(id) = crate::auth::provider_descriptor(provider).and_then(|d| d.models_dev) {
return id;
}
ALIASES.iter().find_map(|(name, id)| (*name == provider).then_some(*id)).unwrap_or(provider)
}
/// The base model id behind a pinned variant, or `None` when the id is already a base id.
///
/// models.dev carries both `claude-opus-4-5` and `claude-opus-4-5-20251101`, but it can't carry
/// every dated snapshot the moment it ships. A pinned or `-latest` alias inherits its family's
/// metadata, which beats falling back to generic defaults.
pub fn normalize_model_id(id: &str) -> Option<&str> {
let base = id.strip_suffix("-latest").or_else(|| {
let (base, suffix) = id.rsplit_once('-')?;
(suffix.len() == 8 && suffix.bytes().all(|b| b.is_ascii_digit())).then_some(base)
})?;
(!base.is_empty()).then_some(base)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn provider_id_prefers_config_then_alias_then_verbatim() {
let configured =
ProviderConfig { models_dev: Some("alibaba".into()), ..Default::default() };
assert_eq!(models_dev_provider("my-proxy", Some(&configured)), "alibaba");
assert_eq!(models_dev_provider("openai_compat", None), "openai");
assert_eq!(models_dev_provider("dashscope", None), "alibaba");
assert_eq!(models_dev_provider("anthropic", None), "anthropic");
assert_eq!(models_dev_provider("lmstudio", None), "lmstudio");
// A subscription provider borrows its metadata from the API-key provider serving the same
// models; without this, a Codex login resolves to no models and a zero context window.
assert_eq!(models_dev_provider("openai-codex", None), "openai");
assert_eq!(models_dev_provider("github-copilot", None), "github-copilot");
assert_eq!(models_dev_provider("fireworks", None), "fireworks-ai");
// An empty override is treated as unset rather than as "look up the empty provider".
let blank = ProviderConfig { models_dev: Some(String::new()), ..Default::default() };
assert_eq!(models_dev_provider("anthropic", Some(&blank)), "anthropic");
}
#[test]
fn model_id_normalization_strips_dates_and_latest() {
assert_eq!(normalize_model_id("claude-opus-4-5-20251101"), Some("claude-opus-4-5"));
assert_eq!(normalize_model_id("claude-3-5-sonnet-latest"), Some("claude-3-5-sonnet"));
assert_eq!(normalize_model_id("gpt-4o"), None);
assert_eq!(normalize_model_id("claude-opus-5"), None);
// Not a date: wrong length, or non-digits.
assert_eq!(normalize_model_id("model-2026"), None);
assert_eq!(normalize_model_id("model-2026072a"), None);
assert_eq!(normalize_model_id("-20251101"), None);
}
}

View File

@@ -0,0 +1,88 @@
//! Conditional models.dev fetch.
//!
//! The catalog is a few hundred KB gzipped and changes maybe daily, but it also serves an
//! `ETag`, so a revalidation that finds nothing new costs a `304` and zero bytes. Refreshing
//! often is therefore cheap; the only rule is that it never happens on a hot path.
use futures::StreamExt;
/// The public models.dev catalog endpoint.
pub const MODELS_DEV_API_URL: &str = "https://models.dev/api.json";
/// Hard ceiling on the decoded response body. The catalog is ~3 MB; this is remote, untrusted
/// JSON, so a server that streams forever gets cut off rather than exhausting memory.
const MAX_BODY_BYTES: usize = 32 * 1024 * 1024;
/// How long a single refresh may take, start to finish.
const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20);
/// Why a catalog refresh failed. Always non-fatal — the caller falls back to cache or snapshot.
#[derive(Debug, thiserror::Error)]
pub enum FetchError {
/// The request could not be built or sent.
#[error("models.dev request failed: {0}")]
Request(#[from] reqwest::Error),
/// The server answered with a non-success, non-304 status.
#[error("models.dev returned {0}")]
Status(reqwest::StatusCode),
/// The body exceeded `MAX_BODY_BYTES`.
#[error("models.dev response exceeded {MAX_BODY_BYTES} bytes")]
TooLarge,
/// The body was not valid UTF-8.
#[error("models.dev response was not valid UTF-8")]
NotUtf8,
}
/// The result of a conditional fetch.
#[derive(Debug)]
pub enum Fetched {
/// The catalog changed; here is the new body and its entity tag.
Changed {
/// Raw `api.json` body.
body: String,
/// `ETag` to send back on the next revalidation.
etag: Option<String>,
},
/// `304 Not Modified` — the cached copy is still current.
Unchanged,
}
/// Fetch the catalog, revalidating against `etag` when one is known.
pub async fn fetch(url: &str, etag: Option<&str>) -> Result<Fetched, FetchError> {
let client = reqwest::Client::builder()
.timeout(TIMEOUT)
.user_agent(concat!("luxe/", env!("CARGO_PKG_VERSION")))
.build()?;
let mut request = client.get(url);
if let Some(etag) = etag {
request = request.header(reqwest::header::IF_NONE_MATCH, etag);
}
let response = request.send().await?;
if response.status() == reqwest::StatusCode::NOT_MODIFIED {
return Ok(Fetched::Unchanged);
}
if !response.status().is_success() {
return Err(FetchError::Status(response.status()));
}
let etag = response
.headers()
.get(reqwest::header::ETAG)
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
// Bound the decoded stream rather than trusting Content-Length, which `gzip` strips anyway.
let mut body = Vec::new();
let mut stream = response.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
if body.len() + chunk.len() > MAX_BODY_BYTES {
return Err(FetchError::TooLarge);
}
body.extend_from_slice(&chunk);
}
let body = String::from_utf8(body).map_err(|_| FetchError::NotUtf8)?;
Ok(Fetched::Changed { body, etag })
}

View File

@@ -0,0 +1,471 @@
//! Layered model-metadata resolution — the one place a [`ModelInfo`] is built.
//!
//! Four layers, each overriding the previous field-by-field wherever it has a value:
//!
//! 1. **Defaults** — provider-aware floors, used when nothing else knows the model.
//! 2. **Snapshot** — the models.dev catalog embedded at build time; the offline/first-run floor.
//! 3. **Cache** — the refreshed on-disk models.dev catalog; stale is fine.
//! 4. **Config** — the user's `models.json`/`auth.json`, which always wins.
//!
//! Every entry point (startup, `--model`, headless, the loop, the `/model` picker, `luxe
//! models`) resolves through [`resolve`]. A layer only speaks where it has a value, so pinning
//! one field in config doesn't discard the rest. [`Provenance`] records which layer won each
//! field, which is what lets `luxe models show` explain a surprising context window.
use std::collections::HashMap;
use luxe_core::provider::{
CompatFlags, Cost, Modality, ModelInfo, ModelRef, ThinkingControls, ThinkingLevel,
PROVIDER_ONLY_COMPAT_KEYS,
};
use super::schema::{Catalog, Model};
use crate::config::{ModelConfig, ProviderConfig};
/// Context window assumed when no layer knows the model.
pub const DEFAULT_CONTEXT_WINDOW: u32 = 128_000;
/// Output cap for Anthropic when no layer knows the model.
///
/// Anthropic *requires* `max_tokens`, and a model no catalog knows is almost always a current one —
/// a fresh release, a Foundry deployment under its own name, a proxy — so this is the current
/// generation's ceiling rather than a safe floor. The old floor of 4,096 was safe and useless: with
/// thinking on, it truncated nearly every substantial reply. An older model that refuses this much
/// says what it does accept, and the adapter retries with that and remembers it. Everywhere else
/// `0` means "omit the field": OpenAI-compatible endpoints treat it as optional, an omitted cap is
/// the model's own maximum on every server Luxe targets, and a forced large value trips strict ones.
const ANTHROPIC_FALLBACK_MAX_TOKENS: u32 = 128_000;
/// Which layer supplied a resolved field.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Layer {
/// Built-in provider-aware default
#[default]
Default,
/// The models.dev catalog embedded at build time
Snapshot,
/// The refreshed on-disk models.dev cache
Cache,
/// The user's `models.json` / `auth.json`
Config,
}
impl Layer {
/// Short label for `luxe models show`.
pub fn label(self) -> &'static str {
match self {
Layer::Default => "default",
Layer::Snapshot => "snapshot",
Layer::Cache => "models.dev",
Layer::Config => "config",
}
}
}
/// Which layer won each resolved field.
#[derive(Debug, Clone, Copy, Default)]
pub struct Provenance {
/// Layer that supplied `display_name`
pub display_name: Layer,
/// Layer that supplied `context_window`
pub context_window: Layer,
/// Layer that supplied `max_tokens`
pub max_tokens: Layer,
/// Layer that supplied `reasoning`
pub reasoning: Layer,
/// Layer that supplied `thinking_level_map`
pub thinking_level_map: Layer,
/// Layer that supplied `default_thinking`
pub default_thinking: Layer,
/// Layer that supplied `compat`
pub compat: Layer,
/// Layer that supplied `sampling_params`
pub sampling_params: Layer,
/// Layer that supplied `thinking_controls`
pub thinking_controls: Layer,
/// Layer that supplied `input`
pub input: Layer,
/// Layer that supplied `cost`
pub cost: Layer,
}
impl Provenance {
/// Field name → winning layer, in display order.
pub fn fields(&self) -> [(&'static str, Layer); 11] {
[
("name", self.display_name),
("context window", self.context_window),
("max tokens", self.max_tokens),
("reasoning", self.reasoning),
("thinking levels", self.thinking_level_map),
("thinking default", self.default_thinking),
("thinking control", self.thinking_controls),
("compat", self.compat),
("sampling", self.sampling_params),
("modalities", self.input),
("cost", self.cost),
]
}
}
/// The catalogs and config a resolution draws on. Any of them may be absent.
#[derive(Debug, Clone, Copy, Default)]
pub struct Sources<'a> {
/// models.dev embedded at build time
pub snapshot: Option<&'a Catalog>,
/// models.dev refreshed on disk
pub cache: Option<&'a Catalog>,
/// The user's entry for this exact `provider/id`
pub model: Option<&'a ModelConfig>,
/// The user's entry for this provider
pub provider: Option<&'a ProviderConfig>,
}
/// Resolve a model's metadata from every available layer.
pub fn resolve(provider: &str, id: &str, sources: &Sources<'_>) -> (ModelInfo, Provenance) {
// The floors below are properties of the *API*, not of a brand: Anthropic Messages requires
// `max_tokens` and every model behind it reasons, whoever is hosting it. Keying on the name
// would leave a Foundry or proxy deployment of the same API without an output cap.
let is_anthropic = crate::config::resolve_api(provider, sources.provider)
== luxe_core::auth::ApiKind::AnthropicMessages;
let mut info = ModelInfo {
r#ref: ModelRef::new(provider, id),
display_name: None,
context_window: DEFAULT_CONTEXT_WINDOW,
max_tokens: if is_anthropic { ANTHROPIC_FALLBACK_MAX_TOKENS } else { 0 },
reasoning: is_anthropic,
thinking_level_map: HashMap::new(),
default_thinking: None,
compat: None,
sampling_params: serde_json::Map::new(),
thinking_controls: ThinkingControls::default(),
input: vec![Modality::Text],
cost: Cost::default(),
// Whether the published rates are a charge or a plan equivalent is a property of the
// provider, not of the model, so it comes from the provider catalog rather than models.dev.
billing: match crate::auth::provider_descriptor(provider) {
Some(descriptor) if descriptor.subscription_billed => {
luxe_core::provider::Billing::Subscription
}
_ => luxe_core::provider::Billing::PerToken,
},
};
let mut from = Provenance::default();
let dev_provider = super::alias::models_dev_provider(provider, sources.provider);
// A deployment is looked up under the model it runs; the wire still gets the deployment name
let catalog_id = sources
.provider
.and_then(|provider| provider.deployments.get(id))
.map_or(id, String::as_str);
for (layer, catalog) in [(Layer::Snapshot, sources.snapshot), (Layer::Cache, sources.cache)] {
if let Some(dev) = catalog.and_then(|c| c.model(dev_provider, catalog_id)) {
apply_dev(&mut info, &mut from, layer, dev);
}
}
// models.dev publishes no sampling recipe, so the only two layers are the user's own: a
// provider-wide baseline for a local server, and the model's own keys on top of it.
for params in [
sources.provider.map(|provider| &provider.sampling_params),
sources.model.map(|model| &model.sampling_params),
]
.into_iter()
.flatten()
.filter(|params| !params.is_empty())
{
info.sampling_params.extend(params.iter().map(|(k, v)| (k.clone(), v.clone())));
from.sampling_params = Layer::Config;
}
if let Some(config) = sources.model {
apply_config(&mut info, &mut from, config);
}
// Compat is two layers like sampling is, but merged into a typed value rather than a free-form
// map, and the provider's half has to be resolved the same way the adapter resolves it — through
// the catalog when no block was written — or a model would be resolved against flags its adapter
// is not running.
let provider_compat = crate::config::resolve_provider_compat(provider, sources.provider);
if let Some(written) =
sources.model.map(|model| &model.compat).filter(|written| !written.is_empty())
{
if let Some(merged) = merge_compat(&provider_compat, written, provider, id) {
info.compat = Some(merged);
from.compat = Layer::Config;
}
}
let compat = info.compat.as_ref().unwrap_or(&provider_compat);
// Anthropic's adaptive-thinking compat exposes an `ultra` level the catalog can't know about.
if is_anthropic
&& compat.force_adaptive_thinking
&& !info.thinking_level_map.contains_key("ultra")
&& !info.thinking_level_map.contains_key("max")
{
info.thinking_level_map.insert("ultra".into(), Some("max".into()));
}
// A thinking map implies reasoning, unless the user said outright otherwise.
if from.reasoning != Layer::Config && !info.thinking_level_map.is_empty() {
info.reasoning = true;
}
// Clamped once, here, where reasoning and the level map have both settled: a starting level the
// model cannot reach would otherwise go out as an invented provider value, and a default nobody
// can honor is config that silently does nothing.
if let Some(level) = info.default_thinking {
info.default_thinking = Some(info.effective_thinking_level(level));
}
(info, from)
}
/// The model's own compat keys merged over `provider_flags`, or `None` when it says nothing.
///
/// Merged as JSON rather than field by field for the reason the raw map exists: only the keys the
/// user wrote may override, and a typed struct cannot tell those from serde's defaults. Two ways it
/// declines instead of guessing — a key that chooses the transport (an adapter is built once per
/// provider, so honoring it per model would be a lie), and a value of the wrong shape. Both leave
/// the model on its provider's flags and say so, because that is the outcome a reader can predict.
fn merge_compat(
provider_flags: &CompatFlags,
written: &serde_json::Map<String, serde_json::Value>,
provider: &str,
id: &str,
) -> Option<CompatFlags> {
let serde_json::Value::Object(mut merged) = serde_json::to_value(provider_flags).ok()? else {
return None;
};
let mut overrides = 0usize;
for (key, value) in written {
if PROVIDER_ONLY_COMPAT_KEYS.contains(&key.as_str()) {
tracing::warn!(
model = %format!("{provider}/{id}"),
key = %key,
"compat key chooses the transport and is provider-level only; ignoring it here"
);
continue;
}
merged.insert(key.clone(), value.clone());
overrides += 1;
}
if overrides == 0 {
return None;
}
match serde_json::from_value::<CompatFlags>(serde_json::Value::Object(merged)) {
Ok(flags) => Some(flags),
Err(error) => {
tracing::warn!(
model = %format!("{provider}/{id}"),
%error,
"model compat block is not a valid set of flags; using the provider's"
);
None
}
}
}
/// Apply one models.dev layer, touching only the fields it actually carries.
fn apply_dev(info: &mut ModelInfo, from: &mut Provenance, layer: Layer, dev: &Model) {
if let Some(name) = &dev.name {
info.display_name = Some(name.clone());
from.display_name = layer;
}
if let Some(context) = dev.limit.as_ref().and_then(|l| l.context) {
info.context_window = context;
from.context_window = layer;
}
if let Some(output) = dev.limit.as_ref().and_then(|l| l.output) {
info.max_tokens = output;
from.max_tokens = layer;
}
if let Some(reasoning) = dev.reasoning {
info.reasoning = reasoning;
from.reasoning = layer;
}
let controls = thinking_controls(dev);
if controls != ThinkingControls::default() {
info.thinking_controls = controls;
from.thinking_controls = layer;
}
let thinking = thinking_map(dev);
if !thinking.is_empty() {
info.thinking_level_map = thinking;
from.thinking_level_map = layer;
}
if let Some(input) = modalities(dev) {
info.input = input;
from.input = layer;
}
if let Some(cost) = &dev.cost {
info.cost = Cost {
input: cost.input.unwrap_or_default(),
output: cost.output.unwrap_or_default(),
cache_read: cost.cache_read.unwrap_or_default(),
cache_write: cost.cache_write.unwrap_or_default(),
cache_write_1h: 0.0,
tiers: tiers(cost),
};
from.cost = layer;
}
}
/// A models.dev entry's long-prompt tiers, cheapest first.
///
/// A tier measured on anything but context size is skipped rather than guessed at, and so is one
/// without an input rate: billing a long prompt at zero would be worse than at the base rate.
fn tiers(cost: &super::schema::Cost) -> Vec<luxe_core::CostTier> {
let tier = |above_tokens: u64, rates: &super::schema::TierRates| {
Some(luxe_core::CostTier {
above_tokens,
input: rates.input?,
output: rates.output.unwrap_or_default(),
cache_read: rates.cache_read.unwrap_or_default(),
cache_write: rates.cache_write.unwrap_or_default(),
})
};
let mut tiers: Vec<luxe_core::CostTier> = cost
.tiers
.iter()
.filter_map(|entry| {
let bound = entry.tier.as_ref()?;
if bound.kind.as_deref() != Some("context") {
return None;
}
tier(bound.size?, &entry.rates)
})
.collect();
if tiers.is_empty() {
if let Some(rates) = &cost.context_over_200k {
tiers.extend(tier(200_000, rates));
}
}
tiers.sort_by_key(|tier| tier.above_tokens);
tiers
}
/// Apply the user's config — the top layer, so anything it sets is final.
fn apply_config(info: &mut ModelInfo, from: &mut Provenance, config: &ModelConfig) {
if let Some(name) = &config.name {
info.display_name = Some(name.clone());
from.display_name = Layer::Config;
}
if let Some(context) = config.context_window {
info.context_window = context;
from.context_window = Layer::Config;
}
if let Some(max_tokens) = config.max_tokens {
info.max_tokens = max_tokens;
from.max_tokens = Layer::Config;
}
if let Some(reasoning) = config.reasoning {
info.reasoning = reasoning;
from.reasoning = Layer::Config;
}
if !config.thinking_level_map.is_empty() {
// A hand-written map describes what the endpoint supports, so it replaces rather than
// merges — otherwise a stale catalog level would survive being deliberately removed.
info.thinking_level_map = config.thinking_level_map.clone();
from.thinking_level_map = Layer::Config;
}
if let Some(values) = &config.input {
// Replaces for the same reason the thinking map does: the list is a closed claim about
// what this endpoint accepts, so dropping a modality here must not be undone by a catalog
// entry that still advertises it. A list Luxe recognizes nothing in falls back to text
// rather than to nothing — no model accepts zero kinds of input, and an empty list would
// render as a blank row.
info.input = parse_modalities(values.iter().map(String::as_str))
.unwrap_or_else(|| vec![Modality::Text]);
from.input = Layer::Config;
}
if let Some(level) = config.thinking {
info.default_thinking = Some(level);
from.default_thinking = Layer::Config;
}
if let Some(cost) = &config.cost {
info.cost = Cost {
input: cost.input,
output: cost.output,
cache_read: cost.cache_read,
cache_write: cost.cache_write,
cache_write_1h: cost.cache_write_1h,
tiers: Vec::new(),
};
from.cost = Layer::Config;
}
}
/// Derive Luxe thinking levels from models.dev `reasoning_options` effort values.
///
/// A declared effort list is a *closed* set when effort is the model's only dial: the levels it
/// omits are marked unsupported so the picker grays them out and the wire request clamps to a value
/// the endpoint actually accepts, instead of inventing one and earning a 400. Where a token budget
/// is also on offer every level is expressible, so the list only adds what it names.
///
/// `off` is never mapped — thinking is switched off by its own parameter, and an entry here would
/// clamp "off" upward into thinking.
fn thinking_map(dev: &Model) -> HashMap<String, Option<String>> {
let mut map = HashMap::new();
for value in dev.reasoning_options.iter().flat_map(|option| &option.values) {
let entry = match value.as_str() {
level @ ("minimal" | "low" | "medium" | "high" | "xhigh") => (level, level),
// models.dev's `max` is Luxe's `ultra`.
"max" | "ultra" => ("ultra", "max"),
_ => continue,
};
map.insert(entry.0.to_string(), Some(entry.1.to_string()));
}
if !map.is_empty() && thinking_controls(dev).effort_only() {
for level in ThinkingLevel::ALL.iter().filter(|level| **level != ThinkingLevel::Off) {
map.entry(level.as_str().to_string()).or_insert(None);
}
}
map
}
/// Which reasoning dials the entry declares. models.dev types them: `effort` for discrete levels,
/// `budget_tokens` for a token budget; `toggle` says thinking can be switched on and off.
///
/// An off switch is claimed only where the entry says so — a `toggle` option, or `none` among the
/// effort values. Silence has to read as "no", because the endpoints that reject a disable are the
/// ones that answer 400 for it, and an entry with no `reasoning_options` at all is as likely to be
/// one of those as not.
fn thinking_controls(dev: &Model) -> ThinkingControls {
let mut controls = ThinkingControls::default();
for option in &dev.reasoning_options {
match option.kind.as_deref() {
Some("effort") => controls.effort = true,
Some("budget_tokens") => controls.budget_tokens = true,
Some("toggle") => controls.can_disable = true,
_ => {}
}
controls.can_disable |= option.values.iter().any(|value| value == "none");
}
controls
}
/// Input modalities Luxe understands, or `None` when the entry declares none it recognizes.
fn modalities(dev: &Model) -> Option<Vec<Modality>> {
let declared = dev.modalities.as_ref().map(|m| m.input.as_slice()).unwrap_or_default();
parse_modalities(declared.iter().map(String::as_str))
}
/// The modalities in `values` that Luxe models, in declared order and deduplicated.
///
/// Anything else is dropped rather than rejected. A catalog that grows a `pdf` or `audio` input,
/// or a hand-written entry with a typo in it, must not take the whole file down with it — the
/// worst outcome for an unknown value is that a capability goes unclaimed.
fn parse_modalities<'a>(values: impl IntoIterator<Item = &'a str>) -> Option<Vec<Modality>> {
let mut modalities: Vec<Modality> = Vec::new();
for value in values {
let modality = match value.to_ascii_lowercase().as_str() {
"text" => Modality::Text,
"image" => Modality::Image,
_ => continue,
};
if !modalities.contains(&modality) {
modalities.push(modality);
}
}
(!modalities.is_empty()).then_some(modalities)
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,625 @@
use super::*;
use crate::config::{CompatFlags, CostConfig};
/// The real models.dev entry for Claude Opus 5, trimmed to what Luxe reads.
const OPUS_5: &str = r#"{"anthropic":{"models":{"claude-opus-5":{
"name":"Claude Opus 5","reasoning":true,"tool_call":true,
"reasoning_options":[{"type":"effort","values":["low","medium","high","xhigh","max"]}],
"modalities":{"input":["text","image","pdf"],"output":["text"]},
"limit":{"context":1000000,"output":128000},
"cost":{"input":5.0,"output":25.0,"cache_read":0.5,"cache_write":6.25}}}}}"#;
fn catalog(json: &str) -> Catalog {
super::super::schema::parse(json).expect("fixture parses")
}
/// A compat block as a user wrote it — the keys, and nothing serde would have defaulted.
fn written(value: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
match value {
serde_json::Value::Object(map) => map,
_ => unreachable!("fixture is an object"),
}
}
#[test]
fn unknown_model_falls_back_to_provider_aware_defaults() {
let (info, from) = resolve("anthropic", "claude-opus-5", &Sources::default());
assert_eq!(info.context_window, DEFAULT_CONTEXT_WINDOW);
assert_eq!(info.max_tokens, ANTHROPIC_FALLBACK_MAX_TOKENS);
assert!(info.reasoning, "anthropic models reason by default");
assert_eq!(from.context_window, Layer::Default);
// Non-Anthropic omits max_tokens rather than forcing a value on a strict endpoint.
let (other, _) = resolve("openai_compat", "some-local-model", &Sources::default());
assert_eq!(other.max_tokens, 0);
assert!(!other.reasoning);
}
/// The floor follows the *API*, not the brand. A Foundry or proxy deployment of Anthropic
/// Messages requires `max_tokens` just as much, and a custom deployment name is exactly the
/// case where no catalog layer supplies one.
#[test]
fn the_anthropic_floor_follows_the_wire_api_rather_than_the_provider_name() {
let (foundry, _) = resolve("foundry-anthropic", "sonnet5-prod", &Sources::default());
assert_eq!(foundry.max_tokens, ANTHROPIC_FALLBACK_MAX_TOKENS);
assert!(foundry.reasoning);
// A provider the catalog has never heard of, declared by hand.
let declared = ProviderConfig { api: Some("anthropic-messages".into()), ..Default::default() };
let (proxy, _) = resolve(
"my-claude-proxy",
"whatever",
&Sources { provider: Some(&declared), ..Sources::default() },
);
assert_eq!(proxy.max_tokens, ANTHROPIC_FALLBACK_MAX_TOKENS);
// And the OpenAI-shaped half of the same resource still omits it.
let (openai, _) = resolve("foundry-openai", "my-deployment", &Sources::default());
assert_eq!(openai.max_tokens, 0);
}
/// A deployment is whatever somebody named it. Its metadata belongs to the model it runs, in
/// whatever case Azure reports that model, and the wire id stays the deployment's name.
#[test]
fn a_deployment_borrows_the_metadata_of_the_model_it_runs() {
let cache = catalog(
r#"{"azure":{"models":{"kimi-k2.5":{"name":"Kimi K2.5","limit":{"context":262144,"output":32768}}}}}"#,
);
let provider = ProviderConfig {
deployments: [("Kimi-K2-Thinking".to_string(), "Kimi-K2.5".to_string())].into(),
..Default::default()
};
let (info, from) = resolve(
"foundry-completions",
"Kimi-K2-Thinking",
&Sources { cache: Some(&cache), provider: Some(&provider), ..<_>::default() },
);
assert_eq!(info.r#ref.id, "Kimi-K2-Thinking", "the wire id is never rewritten");
assert_eq!(info.context_window, 262_144);
assert_eq!(from.context_window, Layer::Cache);
// A deployment named for its model, in Azure's capitals, needs no map at all
let (named, _) = resolve(
"foundry-completions",
"KIMI-K2.5",
&Sources { cache: Some(&cache), ..<_>::default() },
);
assert_eq!(named.context_window, 262_144);
}
#[test]
fn catalog_supplies_everything_config_omits() {
let cache = catalog(OPUS_5);
let (info, from) =
resolve("anthropic", "claude-opus-5", &Sources { cache: Some(&cache), ..<_>::default() });
assert_eq!(info.context_window, 1_000_000);
assert_eq!(info.max_tokens, 128_000);
assert_eq!(info.display_name.as_deref(), Some("Claude Opus 5"));
assert!(info.reasoning);
assert_eq!(info.cost.input, 5.0);
assert_eq!(info.cost.cache_read, 0.5);
assert_eq!(info.input, [Modality::Text, Modality::Image]);
assert_eq!(info.thinking_level_map.get("xhigh"), Some(&Some("xhigh".into())));
assert_eq!(info.thinking_level_map.get("ultra"), Some(&Some("max".into())));
assert_eq!(from.context_window, Layer::Cache);
// The whole point: the levels the model really supports are now reachable.
use luxe_core::provider::ThinkingLevel;
assert_eq!(info.effective_thinking_level(ThinkingLevel::Ultra), ThinkingLevel::Ultra);
assert_eq!(info.effective_thinking_level(ThinkingLevel::XHigh), ThinkingLevel::XHigh);
}
/// Copied from models.dev, the newer list and the older single key both.
#[test]
fn long_prompt_tiers_come_through_from_the_catalog() {
let cache = catalog(
r#"{"anthropic":{"models":{
"claude-haiku-5-5":{"cost":{"input":0.1,"output":0.5,"cache_read":0.01,
"cache_write":0.125,"tiers":[{"input":0.5,"output":2.5,"cache_read":0.05,
"cache_write":0.625,"tier":{"type":"context","size":100000}}]}},
"claude-sonnet-4-5":{"cost":{"input":3,"output":15,"cache_read":0.3,
"cache_write":3.75,"context_over_200k":{"input":6,"output":22.5,
"cache_read":0.6,"cache_write":7.5}}},
"claude-odd":{"cost":{"input":1,"output":5,"tiers":[{"input":2,"output":9,
"tier":{"type":"requests","size":10}}]}}}}}"#,
);
let sources = Sources { cache: Some(&cache), ..<_>::default() };
let (haiku, _) = resolve("anthropic", "claude-haiku-5-5", &sources);
assert_eq!(
haiku.cost.tiers,
[luxe_core::CostTier {
above_tokens: 100_000,
input: 0.5,
output: 2.5,
cache_read: 0.05,
cache_write: 0.625
}]
);
let (sonnet, _) = resolve("anthropic", "claude-sonnet-4-5", &sources);
assert_eq!(sonnet.cost.tiers.len(), 1);
assert_eq!(sonnet.cost.tiers[0].above_tokens, 200_000);
assert_eq!(sonnet.cost.tiers[0].output, 22.5);
let (odd, _) = resolve("anthropic", "claude-odd", &sources);
assert!(odd.cost.tiers.is_empty(), "a tier on something other than context is not guessed at");
}
#[test]
fn cache_overrides_snapshot_and_config_overrides_both() {
let snapshot = catalog(
r#"{"anthropic":{"models":{"claude-opus-5":{"name":"Old Name",
"limit":{"context":200000,"output":32000},"cost":{"input":9.0,"output":9.0}}}}}"#,
);
let cache = catalog(OPUS_5);
let model = ModelConfig { context_window: Some(500_000), ..Default::default() };
let (info, from) = resolve(
"anthropic",
"claude-opus-5",
&Sources {
snapshot: Some(&snapshot),
cache: Some(&cache),
model: Some(&model),
provider: None,
},
);
// Config wins where it speaks …
assert_eq!(info.context_window, 500_000);
assert_eq!(from.context_window, Layer::Config);
// … the fresher cache wins over the snapshot elsewhere …
assert_eq!(info.max_tokens, 128_000);
assert_eq!(info.display_name.as_deref(), Some("Claude Opus 5"));
assert_eq!(from.max_tokens, Layer::Cache);
// … and a field only the snapshot knows still survives when the cache is missing it.
let (snap_only, snap_from) = resolve(
"anthropic",
"claude-opus-5",
&Sources { snapshot: Some(&snapshot), ..<_>::default() },
);
assert_eq!(snap_only.max_tokens, 32_000);
assert_eq!(snap_from.max_tokens, Layer::Snapshot);
}
#[test]
fn config_can_disable_reasoning_and_override_cost() {
let cache = catalog(OPUS_5);
let model = ModelConfig {
reasoning: Some(false),
cost: Some(CostConfig { input: 1.0, output: 2.0, ..Default::default() }),
..Default::default()
};
let (info, from) = resolve(
"anthropic",
"claude-opus-5",
&Sources { cache: Some(&cache), model: Some(&model), ..<_>::default() },
);
// An explicit `false` survives even though the catalog gave a thinking map.
assert!(!info.reasoning);
assert_eq!(from.reasoning, Layer::Config);
assert_eq!(info.cost.input, 1.0);
assert_eq!(from.cost, Layer::Config);
}
/// A published sampling recipe is the point of the passthrough, so both layers have to reach
/// the resolved model — the provider's baseline for a local server hosting several builds, and
/// the model's own keys over the top of it.
#[test]
fn sampling_params_merge_per_key_with_the_model_on_top() {
let map = |json: serde_json::Value| match json {
serde_json::Value::Object(map) => map,
_ => unreachable!("fixture is an object"),
};
let provider = ProviderConfig {
sampling_params: map(serde_json::json!({ "min_p": 0.0, "top_k": 40 })),
..Default::default()
};
let model = ModelConfig {
sampling_params: map(serde_json::json!({ "top_k": 20, "temperature": 1.0 })),
..Default::default()
};
let (info, from) = resolve(
"lmstudio",
"qwen3.8-27b",
&Sources { provider: Some(&provider), model: Some(&model), ..<_>::default() },
);
assert_eq!(info.sampling_params["min_p"], 0.0, "the provider baseline survives");
assert_eq!(info.sampling_params["top_k"], 20, "the model wins the key it names");
assert_eq!(info.sampling_params["temperature"], 1.0);
assert_eq!(from.sampling_params, Layer::Config);
// Nothing configured means nothing sent — never an invented default.
let (bare, bare_from) = resolve("lmstudio", "qwen3.8-27b", &Sources::default());
assert!(bare.sampling_params.is_empty());
assert_eq!(bare_from.sampling_params, Layer::Default);
}
#[test]
fn a_config_thinking_map_replaces_the_catalog_one() {
let cache = catalog(OPUS_5);
let model = ModelConfig {
thinking_level_map: HashMap::from([("high".into(), Some("on".into()))]),
..Default::default()
};
let (info, from) = resolve(
"anthropic",
"claude-opus-5",
&Sources { cache: Some(&cache), model: Some(&model), ..<_>::default() },
);
assert_eq!(info.thinking_level_map.len(), 1);
assert_eq!(info.thinking_level_map.get("high"), Some(&Some("on".into())));
assert_eq!(from.thinking_level_map, Layer::Config);
// Implied by the map, since the user didn't say otherwise.
assert!(info.reasoning);
}
/// A model's compat keys override its provider's *one key at a time*.
///
/// The trap this closes is the one `layer_catalog_compat` closed a level up, and it bites harder
/// here: a model block is normally about a context window, so a `thinking_format` written beside
/// one must not also assert every flag serde would default. If it did, this entry would switch
/// off streamed usage (defaults on) and Anthropic prompt caching (a `null` format) for one model
/// while its sibling on the same endpoint kept both.
#[test]
fn a_models_compat_keys_merge_over_its_providers_rather_than_replacing_them() {
let provider = ProviderConfig {
compat: CompatFlags {
thinking_format: Some("openai".into()),
supports_reasoning_effort: true,
supports_developer_role: true,
cache_control_format: Some("anthropic".into()),
max_tokens_field: "max_completion_tokens".into(),
..Default::default()
},
..Default::default()
};
let model = ModelConfig {
compat: written(serde_json::json!({
"thinking_format": "chat_template",
"supports_developer_role": false
})),
..Default::default()
};
let (info, from) = resolve(
"lmstudio",
"qwen3.6-27b-fable-fusion",
&Sources { provider: Some(&provider), model: Some(&model), ..<_>::default() },
);
let compat = info.compat.expect("the model resolved its own flags");
// What it wrote …
assert_eq!(compat.thinking_format.as_deref(), Some("chat_template"));
assert!(!compat.supports_developer_role, "this template raises on a `developer` role");
// … and everything it did not, still the provider's.
assert!(compat.supports_reasoning_effort);
assert_eq!(compat.cache_control_format.as_deref(), Some("anthropic"));
assert_eq!(compat.max_tokens_field, "max_completion_tokens");
assert!(compat.supports_usage_in_streaming, "a default nobody wrote is not an override");
assert_eq!(from.compat, Layer::Config);
// The sibling on the same endpoint says nothing, so it has no flags of its own and the
// adapter keeps the ones it was built with.
let (sibling, sibling_from) = resolve(
"lmstudio",
"qwen3.8-27b",
&Sources { provider: Some(&provider), ..<_>::default() },
);
assert_eq!(sibling.compat, None);
assert_eq!(sibling_from.compat, Layer::Default);
}
/// With no provider block written, the base is the catalog's flags — the same ones the adapter is
/// built with.
///
/// Resolved through one function for that reason: a second implementation of "the provider's
/// compat" is how a model ends up merged over flags nothing is actually running.
#[test]
fn a_models_compat_merges_over_the_catalog_when_no_provider_block_exists() {
let model = ModelConfig {
compat: written(serde_json::json!({ "force_adaptive_thinking": true })),
..Default::default()
};
let (info, _) = resolve(
"anthropic",
"claude-opus-9-unreleased",
&Sources { model: Some(&model), ..<_>::default() },
);
let compat = info.compat.expect("resolved");
assert!(compat.force_adaptive_thinking, "what the model wrote");
assert!(
compat.cache_control_format.is_some(),
"and Anthropic's catalog default for prompt caching survives"
);
// Forcing adaptive thinking on one model exposes `ultra` on that model, as it does when the
// provider forces it — the two paths reach the same place.
assert_eq!(info.thinking_level_map.get("ultra"), Some(&Some("max".into())));
}
/// A key that chooses the *transport* is refused, because an adapter is built once per provider.
///
/// Honoring it here would be a lie: the request would be shaped for `/responses` and posted to
/// chat/completions. The rest of the block still applies — one bad key costs that key.
#[test]
fn a_model_may_not_choose_the_transport() {
let provider = ProviderConfig {
compat: CompatFlags { use_responses_api: true, ..Default::default() },
..Default::default()
};
let model = ModelConfig {
compat: written(serde_json::json!({
"use_responses_api": false,
"supports_developer_role": true
})),
..Default::default()
};
let (info, _) = resolve(
"openai",
"gpt-5",
&Sources { provider: Some(&provider), model: Some(&model), ..<_>::default() },
);
let compat = info.compat.expect("the rest of the block still resolved");
assert!(compat.use_responses_api, "the provider's transport choice stands");
assert!(compat.supports_developer_role, "and the shaping key it wrote applies");
// A block of nothing but refused keys leaves the model with no flags at all, rather than a
// copy of its provider's that would drift from them.
let only_refused = ModelConfig {
compat: written(serde_json::json!({ "use_responses_api": false })),
..Default::default()
};
let (bare, from) = resolve(
"openai",
"gpt-5",
&Sources { provider: Some(&provider), model: Some(&only_refused), ..<_>::default() },
);
assert_eq!(bare.compat, None);
assert_eq!(from.compat, Layer::Default);
}
/// A value of the wrong shape costs the block, never the file.
///
/// The same rule the modality list follows: `models.json` is a file on a user's disk, and a typo
/// in one model's compat must not take down the launch — it falls back to the provider's flags
/// and says so in the log.
#[test]
fn a_malformed_model_compat_block_falls_back_to_the_providers() {
let provider = ProviderConfig {
compat: CompatFlags { thinking_format: Some("openai".into()), ..Default::default() },
..Default::default()
};
let model = ModelConfig {
compat: written(serde_json::json!({ "thinking_format": 42 })),
..Default::default()
};
let (info, from) = resolve(
"lmstudio",
"typo",
&Sources { provider: Some(&provider), model: Some(&model), ..<_>::default() },
);
assert_eq!(info.compat, None, "nothing model-specific survives a value it cannot read");
assert_eq!(from.compat, Layer::Default);
}
/// A model's starting reasoning level is config-only — no catalog has an opinion about how much
/// *your* patience is worth — and it is clamped to a level the model can actually reach, so a
/// default the map forbids resolves to the nearest one it allows instead of silently doing
/// nothing.
#[test]
fn a_config_thinking_default_resolves_and_clamps_to_a_reachable_level() {
let reachable = ModelConfig {
thinking: Some(ThinkingLevel::Medium),
thinking_level_map: HashMap::from([
("off".into(), Some("none".into())),
("medium".into(), Some("medium".into())),
("high".into(), Some("high".into())),
]),
..Default::default()
};
let (info, from) =
resolve("lmstudio", "qwen3.8-27b", &Sources { model: Some(&reachable), ..<_>::default() });
assert_eq!(info.default_thinking, Some(ThinkingLevel::Medium));
assert_eq!(from.default_thinking, Layer::Config);
assert!(info.reasoning, "the map implies it, as it does for any other entry");
// A level the same file marks unsupported clamps rather than reaching the wire.
let forbidden = ModelConfig { thinking: Some(ThinkingLevel::XHigh), ..reachable.clone() };
let (clamped, _) =
resolve("lmstudio", "qwen3.8-27b", &Sources { model: Some(&forbidden), ..<_>::default() });
assert_eq!(clamped.default_thinking, Some(ThinkingLevel::High));
// And a model that cannot think at all cannot start anywhere but off.
let thoughtless = ModelConfig {
reasoning: Some(false),
thinking: Some(ThinkingLevel::High),
..Default::default()
};
let (off, _) =
resolve("lmstudio", "plain", &Sources { model: Some(&thoughtless), ..<_>::default() });
assert_eq!(off.default_thinking, Some(ThinkingLevel::Off));
// Nothing configured means nothing declared — never an invented starting level.
let (bare, bare_from) = resolve(
"anthropic",
"claude-opus-5",
&Sources { cache: Some(&catalog(OPUS_5)), ..<_>::default() },
);
assert_eq!(bare.default_thinking, None);
assert_eq!(bare_from.default_thinking, Layer::Default);
}
/// The gap this field exists to close: a local endpoint resolves entirely from config, so
/// without it a vision model loaded with its projector reported `text` and nothing the user
/// could write changed that.
#[test]
fn a_config_modality_list_overrides_the_default() {
let model =
ModelConfig { input: Some(vec!["text".into(), "image".into()]), ..Default::default() };
let (info, from) = resolve(
"lmstudio",
"some-vision-model",
&Sources { model: Some(&model), ..<_>::default() },
);
assert_eq!(info.input, [Modality::Text, Modality::Image]);
assert_eq!(from.input, Layer::Config, "and it says the answer came from the config");
}
/// The list is a closed claim about the endpoint, so removing a modality has to stick even
/// where the catalog still advertises it — the same rule the thinking map follows.
#[test]
fn a_config_modality_list_replaces_the_catalog_one() {
let cache = catalog(
r#"{"openai":{"models":{"gpt-5":{"modalities":{"input":["text","image"]},
"limit":{"context":400000,"output":128000}}}}}"#,
);
let model = ModelConfig { input: Some(vec!["text".into()]), ..Default::default() };
let (catalog_only, _) =
resolve("openai", "gpt-5", &Sources { cache: Some(&cache), ..<_>::default() });
assert_eq!(catalog_only.input, [Modality::Text, Modality::Image], "the catalog claims both");
let (info, from) = resolve(
"openai",
"gpt-5",
&Sources { cache: Some(&cache), model: Some(&model), ..<_>::default() },
);
assert_eq!(info.input, [Modality::Text], "and the config takes one away for good");
assert_eq!(from.input, Layer::Config);
}
/// An unrecognized value costs that one capability, never the file. Falling through to an
/// empty list instead would render as a blank row and claim the model accepts nothing at all.
#[test]
fn config_modalities_ignore_unrecognized_values_without_erroring() {
let model = ModelConfig { input: Some(vec!["pdf".into()]), ..Default::default() };
let (info, _) = resolve("lmstudio", "x", &Sources { model: Some(&model), ..<_>::default() });
assert_eq!(info.input, [Modality::Text]);
// A recognized value alongside an unknown one still lands, and case does not matter.
let mixed = ModelConfig {
input: Some(vec!["Image".into(), "audio".into(), "IMAGE".into()]),
..Default::default()
};
let (info, _) = resolve("lmstudio", "x", &Sources { model: Some(&mixed), ..<_>::default() });
assert_eq!(info.input, [Modality::Image], "deduplicated, and the unknown one dropped");
}
#[test]
fn provider_alias_routes_a_custom_name_to_its_models_dev_id() {
let cache = catalog(
r#"{"alibaba":{"models":{"qwen3-max":{"limit":{"context":262144,"output":65536}}}}}"#,
);
let provider = ProviderConfig { models_dev: Some("alibaba".into()), ..Default::default() };
let (info, _) = resolve(
"my-qwen-proxy",
"qwen3-max",
&Sources { cache: Some(&cache), provider: Some(&provider), ..<_>::default() },
);
assert_eq!(info.context_window, 262_144);
// Without the hint the name matches nothing, which is right for an unknown endpoint.
let (bare, _) =
resolve("my-qwen-proxy", "qwen3-max", &Sources { cache: Some(&cache), ..<_>::default() });
assert_eq!(bare.context_window, DEFAULT_CONTEXT_WINDOW);
}
/// The catalog's own account of which dial a model exposes decides how the Anthropic adapter
/// asks for thinking, so it has to survive resolution intact — and an effort-only list is a
/// closed set, which is what stops Luxe asking for a level the endpoint never advertised.
#[test]
fn declared_reasoning_dials_survive_resolution() {
// Real 2026-07 shapes: Sonnet 5 (effort only), Sonnet 4.5 (a token budget), Opus 4.5 (both).
let cache = catalog(
r#"{"anthropic":{"models":{
"claude-sonnet-5":{"reasoning":true,"reasoning_options":[{"type":"toggle"},
{"type":"effort","values":["low","medium","high","xhigh","max"]}]},
"claude-sonnet-4-5":{"reasoning":true,
"reasoning_options":[{"min":1024,"type":"budget_tokens"}]},
"claude-opus-4-5":{"reasoning":true,"reasoning_options":[
{"type":"effort","values":["low","medium","high"]},
{"min":1024,"type":"budget_tokens"}]}}}}"#,
);
let resolve_cached =
|id: &str| resolve("anthropic", id, &Sources { cache: Some(&cache), ..<_>::default() }).0;
let sonnet_5 = resolve_cached("claude-sonnet-5");
assert!(sonnet_5.thinking_controls.effort_only(), "effort is the only dial");
// Every level it names is reachable …
assert_eq!(sonnet_5.effective_thinking_level(ThinkingLevel::XHigh), ThinkingLevel::XHigh);
assert_eq!(sonnet_5.effective_thinking_level(ThinkingLevel::Ultra), ThinkingLevel::Ultra);
// … and one it doesn't clamps instead of inventing an effort value.
assert_eq!(sonnet_5.thinking_level_map.get("minimal"), Some(&None));
assert_eq!(sonnet_5.effective_thinking_level(ThinkingLevel::Minimal), ThinkingLevel::Low);
// Off keeps its own switch — a mapped `off` would clamp "no thinking" up into thinking.
assert!(!sonnet_5.thinking_level_map.contains_key("off"));
assert_eq!(sonnet_5.effective_thinking_level(ThinkingLevel::Off), ThinkingLevel::Off);
// A token budget expresses any depth, so nothing is closed off and the levels stay open.
let sonnet_4_5 = resolve_cached("claude-sonnet-4-5");
assert!(!sonnet_4_5.thinking_controls.effort_only());
assert!(sonnet_4_5.thinking_controls.budget_tokens);
assert!(sonnet_4_5.thinking_level_map.is_empty());
assert_eq!(sonnet_4_5.effective_thinking_level(ThinkingLevel::Medium), ThinkingLevel::Medium);
// Both dials: still not effort-only, so the adapter keeps extended thinking.
let opus_4_5 = resolve_cached("claude-opus-4-5");
assert!(opus_4_5.thinking_controls.effort);
assert!(opus_4_5.thinking_controls.budget_tokens);
assert!(!opus_4_5.thinking_controls.effort_only());
assert!(!opus_4_5.thinking_level_map.contains_key("minimal"), "the list only adds");
}
/// Whether reasoning can be switched off is a claim the catalog has to make out loud, because
/// the endpoints that refuse are the ones that answer 400 to a disable. Real 2026-08 shapes
/// from the models.dev `openrouter` block, one per way of learning it.
#[test]
fn an_off_switch_is_claimed_only_where_the_catalog_says_so() {
let cache = catalog(
r#"{"openrouter":{"models":{
"anthropic/claude-sonnet-5":{"reasoning":true,"reasoning_options":[{"type":"toggle"},
{"type":"effort","values":["low","medium","high","xhigh","max"]}]},
"openai/gpt-5.6-sol":{"reasoning":true,"reasoning_options":[
{"type":"effort","values":["none","low","medium","high","xhigh","max"]}]},
"google/gemini-3.5-flash":{"reasoning":true,"reasoning_options":[
{"type":"effort","values":["minimal","low","medium","high"]}]},
"moonshotai/kimi-k2-thinking":{"reasoning":true}}}}"#,
);
let disables = |id: &str| {
resolve("openrouter", id, &Sources { cache: Some(&cache), ..<_>::default() })
.0
.thinking_controls
.can_disable
};
assert!(disables("anthropic/claude-sonnet-5"), "a toggle option is the plain statement");
assert!(disables("openai/gpt-5.6-sol"), "`none` among the efforts says the same thing");
assert!(!disables("google/gemini-3.5-flash"), "a closed effort list without `none`");
assert!(!disables("moonshotai/kimi-k2-thinking"), "silence is not permission");
}
#[test]
fn adaptive_thinking_compat_still_adds_ultra() {
let provider = ProviderConfig {
compat: CompatFlags { force_adaptive_thinking: true, ..Default::default() },
..Default::default()
};
let (info, _) =
resolve("anthropic", "claude-x", &Sources { provider: Some(&provider), ..<_>::default() });
assert_eq!(info.thinking_level_map.get("ultra"), Some(&Some("max".into())));
assert!(info.reasoning);
}
#[test]
fn pinned_date_suffix_inherits_the_base_model() {
let cache = catalog(OPUS_5);
let (info, from) = resolve(
"anthropic",
"claude-opus-5-20260724",
&Sources { cache: Some(&cache), ..<_>::default() },
);
// Metadata is inherited …
assert_eq!(info.context_window, 1_000_000);
assert_eq!(from.context_window, Layer::Cache);
// … but the wire id is untouched.
assert_eq!(info.r#ref.id, "claude-opus-5-20260724");
}

View File

@@ -0,0 +1,296 @@
//! models.dev `api.json` schema — the subset Luxe actually uses.
//!
//! The wire shape is `{ providerId: { models: { modelId: {…} } } }`. Unknown fields are ignored
//! on the way in and omitted on the way out, so the same types parse the live API, the on-disk
//! cache, and the embedded snapshot, and re-serialize to the compact form we persist.
use serde::{Deserialize, Deserializer, Serialize};
use std::collections::HashMap;
/// A models.dev catalog: provider id → provider block.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Catalog {
/// Provider blocks keyed by models.dev provider id (`anthropic`, `openai`, …).
#[serde(flatten)]
pub providers: HashMap<String, Provider>,
}
/// One provider block.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Provider {
/// Human provider name (e.g. `Anthropic`)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Models keyed by model id.
#[serde(
default,
deserialize_with = "lenient_models",
skip_serializing_if = "HashMap::is_empty"
)]
pub models: HashMap<String, Model>,
}
/// Parse models one at a time, dropping any that don't fit the schema.
///
/// models.dev is community-maintained and occasionally ships an entry with, say, a `null` inside
/// a string array. Strict parsing would turn that into "Luxe knows nothing about any model" —
/// the exact failure this whole module exists to prevent. Losing one entry is a far better trade.
fn lenient_models<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<HashMap<String, Model>, D::Error> {
let raw = HashMap::<String, serde_json::Value>::deserialize(deserializer)?;
Ok(raw
.into_iter()
.filter_map(|(id, value)| match serde_json::from_value(value) {
Ok(model) => Some((id, model)),
Err(error) => {
tracing::debug!(model = %id, %error, "skipping malformed models.dev entry");
None
}
})
.collect())
}
/// One model entry.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Model {
/// Display name (e.g. `Claude Opus 5`)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Whether the model supports reasoning/thinking
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reasoning: Option<bool>,
/// Whether the model can call tools — a hard requirement for agentic use
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tool_call: Option<bool>,
/// Release date (`YYYY-MM-DD`), used to sort newest-first in the picker
#[serde(default, skip_serializing_if = "Option::is_none")]
pub release_date: Option<String>,
/// Lifecycle marker (`alpha` / `beta` / `deprecated`)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
/// Context/output token limits
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<Limit>,
/// Cost per million tokens
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cost: Option<Cost>,
/// Supported input/output modalities
#[serde(default, skip_serializing_if = "Option::is_none")]
pub modalities: Option<Modalities>,
/// Declared reasoning-effort options, used to derive a thinking-level map
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub reasoning_options: Vec<ReasoningOption>,
}
/// Context/output token limits.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Limit {
/// Context window in tokens
#[serde(default, skip_serializing_if = "Option::is_none")]
pub context: Option<u32>,
/// Max output tokens
#[serde(default, skip_serializing_if = "Option::is_none")]
pub output: Option<u32>,
}
/// Cost per million tokens.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Cost {
/// Input cost per million tokens
#[serde(default, skip_serializing_if = "Option::is_none")]
pub input: Option<f64>,
/// Output cost per million tokens
#[serde(default, skip_serializing_if = "Option::is_none")]
pub output: Option<f64>,
/// Cache-hit read cost per million tokens
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cache_read: Option<f64>,
/// Cache-write cost per million tokens
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cache_write: Option<f64>,
/// Dearer rates past a prompt size
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tiers: Vec<CostTier>,
/// The older spelling of a single tier at 200k tokens
#[serde(default, skip_serializing_if = "Option::is_none")]
pub context_over_200k: Option<TierRates>,
}
/// One entry of `cost.tiers`: rates, and the prompt size they start past.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CostTier {
/// The rates themselves
#[serde(flatten)]
pub rates: TierRates,
/// What the tier is measured on
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tier: Option<TierBound>,
}
/// A tier's rates per million tokens.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TierRates {
/// Input cost per million tokens
#[serde(default, skip_serializing_if = "Option::is_none")]
pub input: Option<f64>,
/// Output cost per million tokens
#[serde(default, skip_serializing_if = "Option::is_none")]
pub output: Option<f64>,
/// Cache-hit read cost per million tokens
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cache_read: Option<f64>,
/// Cache-write cost per million tokens
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cache_write: Option<f64>,
}
/// Where a tier starts: `{"type": "context", "size": 100000}`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TierBound {
/// What is measured; only `context` is understood
#[serde(default, rename = "type", skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
/// Tokens past which the tier applies
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<u64>,
}
/// Input/output modality lists.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Modalities {
/// Supported input modalities (`text`, `image`, `pdf`, …)
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub input: Vec<String>,
/// Supported output modalities
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub output: Vec<String>,
}
/// A declared reasoning-effort option group (`{type: "effort", values: […]}`).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ReasoningOption {
/// Option kind (typically `effort`)
#[serde(default, rename = "type", skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
/// Allowed values (e.g. `low`/`medium`/`high`/`xhigh`/`max`)
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub values: Vec<String>,
}
impl Catalog {
/// Look up one model by models.dev provider id + model id, retrying with a normalized id
/// (see [`crate::catalog::alias::normalize_model_id`]) when the exact id is absent, then
/// ignoring case.
///
/// Case last, and only on a miss: models.dev ids are lowercase, but an Azure deployment of a
/// partner model is reported as `DeepSeek-V4-Flash`, and that is the same model.
pub fn model(&self, provider: &str, id: &str) -> Option<&Model> {
let models = &self.providers.get(provider)?.models;
let exact = |id: &str| {
models
.get(id)
.or_else(|| super::alias::normalize_model_id(id).and_then(|base| models.get(base)))
};
exact(id).or_else(|| {
let lower = id.to_ascii_lowercase();
(lower != id).then(|| exact(&lower)).flatten()
})
}
/// Iterate `(model_id, model)` for a provider, or nothing when it's absent.
pub fn provider_models(&self, provider: &str) -> impl Iterator<Item = (&String, &Model)> {
self.providers.get(provider).into_iter().flat_map(|block| block.models.iter())
}
/// Total model count across every provider.
pub fn len(&self) -> usize {
self.providers.values().map(|block| block.models.len()).sum()
}
/// Whether the catalog carries any provider at all.
pub fn is_empty(&self) -> bool {
self.providers.is_empty()
}
}
/// Parse a raw models.dev `api.json` body.
pub fn parse(json: &str) -> Result<Catalog, serde_json::Error> {
serde_json::from_str(json)
}
#[cfg(test)]
mod tests {
use super::*;
const SAMPLE: &str = r#"{
"anthropic": {
"id": "anthropic",
"name": "Anthropic",
"env": ["ANTHROPIC_API_KEY"],
"models": {
"claude-opus-5": {
"id": "claude-opus-5",
"name": "Claude Opus 5",
"description": "ignored",
"reasoning": true,
"tool_call": true,
"release_date": "2026-07-24",
"reasoning_options": [{"type":"effort","values":["low","high","max"]}],
"modalities": {"input":["text","image","pdf"],"output":["text"]},
"limit": {"context": 1000000, "output": 128000},
"cost": {"input": 5.0, "output": 25.0, "cache_read": 0.5, "cache_write": 6.25}
}
}
}
}"#;
#[test]
fn parses_the_real_nested_shape_and_ignores_unknown_fields() {
let catalog = parse(SAMPLE).expect("real models.dev shape parses");
let model = catalog.model("anthropic", "claude-opus-5").expect("model present");
assert_eq!(model.name.as_deref(), Some("Claude Opus 5"));
assert_eq!(model.reasoning, Some(true));
assert_eq!(model.limit.as_ref().and_then(|l| l.context), Some(1_000_000));
assert_eq!(model.cost.as_ref().and_then(|c| c.cache_read), Some(0.5));
assert_eq!(model.reasoning_options[0].values, ["low", "high", "max"]);
assert_eq!(model.reasoning_options[0].kind.as_deref(), Some("effort"));
assert_eq!(catalog.len(), 1);
assert_eq!(catalog.provider_models("missing").count(), 0);
}
#[test]
fn round_trips_through_serialize_without_losing_fields() {
let catalog = parse(SAMPLE).expect("parse");
let written = serde_json::to_string(&catalog).expect("serialize");
let back = parse(&written).expect("reparse");
let model = back.model("anthropic", "claude-opus-5").expect("model survives");
assert_eq!(model.limit.as_ref().and_then(|l| l.output), Some(128_000));
assert_eq!(model.cost.as_ref().and_then(|c| c.cache_write), Some(6.25));
assert_eq!(model.release_date.as_deref(), Some("2026-07-24"));
assert_eq!(model.tool_call, Some(true));
// Empty/None fields are omitted, keeping the persisted cache small.
assert!(!written.contains("status"));
}
#[test]
fn one_malformed_entry_does_not_sink_the_catalog() {
// `values: [null]` is real upstream data (sarvam-*, 2026-07). The good model must survive.
let catalog = parse(
r#"{"sarvam":{"models":{
"broken":{"reasoning_options":[{"type":"effort","values":[null]}]},
"fine":{"name":"Fine","limit":{"context":32768}}}}}"#,
)
.expect("catalog still parses");
assert!(catalog.model("sarvam", "broken").is_none(), "bad entry dropped");
assert_eq!(catalog.model("sarvam", "fine").and_then(|m| m.name.as_deref()), Some("Fine"));
}
#[test]
fn dated_and_latest_suffixes_fall_back_to_the_base_id() {
let catalog = parse(SAMPLE).expect("parse");
assert!(catalog.model("anthropic", "claude-opus-5-20260724").is_some());
assert!(catalog.model("anthropic", "claude-opus-5-latest").is_some());
assert!(catalog.model("anthropic", "claude-opus-6").is_none());
}
}

View File

@@ -0,0 +1,88 @@
//! Build-time models.dev snapshot.
//!
//! The floor under every other layer: a fresh install with no network, no cache, and no config
//! still resolves real context windows, output caps, reasoning levels, and pricing. Regenerate
//! with `scripts/update-models-snapshot.sh`; the runtime cache supersedes it for anything
//! released since the build.
use std::sync::OnceLock;
use super::schema::{parse, Catalog};
/// The gzipped projection produced by `scripts/update-models-snapshot.sh` (~130 KB).
const SNAPSHOT_GZ: &[u8] = include_bytes!("../../data/models-dev-snapshot.json.gz");
/// The embedded catalog, inflated and parsed once on first use.
///
/// A corrupt blob degrades to an empty catalog rather than killing startup — the cache and
/// config layers still work, which is exactly the pre-snapshot behavior.
pub fn snapshot() -> &'static Catalog {
static SNAPSHOT: OnceLock<Catalog> = OnceLock::new();
SNAPSHOT.get_or_init(|| match decode() {
Ok(catalog) => catalog,
Err(error) => {
tracing::warn!(%error, "embedded models.dev snapshot unreadable");
Catalog::default()
}
})
}
fn decode() -> Result<Catalog, String> {
use std::io::Read;
let mut json = String::new();
flate2::read::GzDecoder::new(SNAPSHOT_GZ)
.read_to_string(&mut json)
.map_err(|error| error.to_string())?;
parse(&json).map_err(|error| error.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn embedded_snapshot_decodes_and_carries_real_metadata() {
let catalog = snapshot();
assert!(catalog.len() > 1_000, "snapshot looks truncated: {} models", catalog.len());
assert!(catalog.providers.contains_key("anthropic"));
assert!(catalog.providers.contains_key("openai"));
// Spot-check a model that shipped after this code was written: the whole point is that a
// recent release resolves properly with no network and no config.
let opus = catalog.model("anthropic", "claude-opus-5").expect("claude-opus-5 in snapshot");
assert_eq!(opus.limit.as_ref().and_then(|l| l.context), Some(1_000_000));
assert_eq!(opus.limit.as_ref().and_then(|l| l.output), Some(128_000));
assert_eq!(opus.reasoning, Some(true));
assert!(opus.cost.as_ref().and_then(|c| c.cache_read).is_some());
assert!(!opus.reasoning_options.is_empty());
// The current Anthropic generation offers effort and no token budget, which is what routes
// it to adaptive thinking; sending extended thinking to these models is a 400.
for id in ["claude-opus-5", "claude-sonnet-5"] {
let (info, _) = super::super::resolve(
"anthropic",
id,
&super::super::Sources { snapshot: Some(catalog), ..<_>::default() },
);
assert!(info.thinking_controls.effort_only(), "{id} must resolve to effort-only");
}
}
/// The snapshot must not be *pathologically* slow to inflate. It sits on the startup path, but
/// only once — [`snapshot`] holds it in a `OnceLock`.
///
/// The budget is deliberately loose, and that is the point. It was 500ms, which is within a
/// factor of two of what a loaded runner actually takes (706ms on windows-latest against ~50ms
/// on a developer machine), so it was measuring the runner rather than the code and went red on
/// a commit that touched neither. What is worth catching is a *catastrophe* — a codec swap, or
/// decoding per call instead of once — and an order of magnitude still catches that.
#[test]
fn decoding_is_not_pathologically_slow_on_the_startup_path() {
let start = std::time::Instant::now();
let catalog = decode().expect("snapshot decodes");
let elapsed = start.elapsed();
assert!(catalog.len() > 1_000, "a decode that returns nothing proves nothing");
assert!(elapsed < std::time::Duration::from_secs(5), "snapshot decode took {elapsed:?}");
}
}

View File

@@ -0,0 +1,136 @@
//! On-disk catalog cache.
//!
//! The cache is derived data, so it lives under `$XDG_CACHE_HOME` and any read failure simply
//! means "no cache". A sidecar carries the `ETag` and the last-checked time: freshness is
//! tracked there rather than by file mtime so a `304` can reset the clock without rewriting
//! several megabytes.
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use super::schema::{parse, Catalog};
/// Revalidation state stored alongside the cached catalog.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Meta {
/// `ETag` from the last successful fetch, replayed as `If-None-Match`
#[serde(default)]
pub etag: Option<String>,
/// Unix seconds of the last check, whether it returned `200` or `304`
#[serde(default)]
pub checked_at: u64,
}
impl Meta {
/// How long since the catalog was last revalidated.
pub fn age(&self) -> Option<Duration> {
let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();
Some(Duration::from_secs(now.saturating_sub(self.checked_at)))
}
/// Whether the last check is older than `ttl`.
pub fn is_stale(&self, ttl: Duration) -> bool {
self.age().is_none_or(|age| age >= ttl)
}
}
/// The sidecar path for a cache file.
fn meta_path(path: &Path) -> PathBuf {
path.with_extension("meta.json")
}
/// Read the cached catalog, or `None` when it's absent or unparseable.
pub fn load(path: &Path) -> Option<Catalog> {
let body = std::fs::read_to_string(path).ok()?;
match parse(&body) {
Ok(catalog) => Some(catalog),
Err(error) => {
tracing::warn!(path = %path.display(), %error, "ignoring corrupt models.dev cache");
None
}
}
}
/// Read the sidecar, defaulting to "never checked".
pub fn load_meta(path: &Path) -> Meta {
std::fs::read_to_string(meta_path(path))
.ok()
.and_then(|body| serde_json::from_str(&body).ok())
.unwrap_or_default()
}
/// Write the catalog body and sidecar, replacing any previous copy.
///
/// Atomically, so a concurrent reader (or a second `luxe` refreshing at the same time) always sees a
/// whole file.
pub fn store(path: &Path, body: &str, etag: Option<String>) -> std::io::Result<()> {
luxe_core::fs_atomic::replace(path, body.as_bytes())?;
touch(path, etag)
}
/// Record a successful revalidation without rewriting the body (the `304` path).
pub fn touch(path: &Path, etag: Option<String>) -> std::io::Result<()> {
let checked_at =
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or_default();
let meta = Meta { etag: etag.or_else(|| load_meta(path).etag), checked_at };
let body = serde_json::to_string(&meta).unwrap_or_default();
luxe_core::fs_atomic::replace(&meta_path(path), body.as_bytes())
}
#[cfg(test)]
mod tests {
use super::*;
const BODY: &str = r#"{"anthropic":{"models":{"claude-opus-5":{"name":"Claude Opus 5"}}}}"#;
#[test]
fn store_then_load_round_trips_body_and_meta() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("nested").join("models-dev.json");
assert!(load(&path).is_none(), "no cache yet");
assert!(load_meta(&path).is_stale(Duration::from_secs(1)));
store(&path, BODY, Some("\"abc\"".into())).expect("store");
let catalog = load(&path).expect("cache reads back");
assert!(catalog.model("anthropic", "claude-opus-5").is_some());
let meta = load_meta(&path);
assert_eq!(meta.etag.as_deref(), Some("\"abc\""));
assert!(!meta.is_stale(Duration::from_secs(3600)));
// No temp files left behind.
let leftovers: Vec<_> = std::fs::read_dir(path.parent().unwrap())
.unwrap()
.filter_map(|e| e.ok())
.filter(|e| e.file_name().to_string_lossy().contains("tmp"))
.collect();
assert!(leftovers.is_empty(), "temp file survived: {leftovers:?}");
}
#[test]
fn touch_resets_the_clock_and_keeps_the_etag() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("models-dev.json");
store(&path, BODY, Some("\"abc\"".into())).expect("store");
// Simulate an old check, then revalidate with no new etag (a 304).
std::fs::write(path.with_extension("meta.json"), r#"{"etag":"\"abc\"","checked_at":1}"#)
.unwrap();
assert!(load_meta(&path).is_stale(Duration::from_secs(3600)));
touch(&path, None).expect("touch");
let meta = load_meta(&path);
assert!(!meta.is_stale(Duration::from_secs(3600)), "clock reset");
assert_eq!(meta.etag.as_deref(), Some("\"abc\""), "etag survives a 304");
}
#[test]
fn a_corrupt_cache_reads_as_absent_rather_than_panicking() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("models-dev.json");
std::fs::write(&path, "{ not json").unwrap();
assert!(load(&path).is_none());
}
}

View File

@@ -0,0 +1,158 @@
//! Chat-template arguments — the `chat_template_kwargs` payload, described rather than hardcoded.
//!
//! Servers that render a Jinja chat template (raw `llama-server`, vLLM, SGLang) take their thinking
//! controls as template arguments rather than as wire fields, and every template names them
//! differently: Qwen3.8 accepts `enable_thinking`, `preserve_thinking` and `reasoning_effort`, the
//! next one will accept something else. So the shape is configuration — a map of literal values
//! and `$var` references resolved against the turn's thinking level.
//!
//! Note that LM Studio's HTTP layer *drops* `chat_template_kwargs` entirely; a model served through
//! it wants `thinking_format: "openai"` and a top-level `reasoning_effort` instead.
use serde_json::{Map, Value};
use tracing::warn;
/// The payload a template with nothing configured gets: Qwen's two flags, which is what Luxe sent
/// for every chat-template model before the map existed.
fn default_kwargs(enabled: bool) -> Value {
serde_json::json!({ "enable_thinking": enabled, "preserve_thinking": true })
}
/// Build the `chat_template_kwargs` object for one request.
///
/// `template` is the configured map; an empty one falls back to [`default_kwargs`], so a config
/// written without one gets the defaults. Returns `None` when every configured key resolved away,
/// in which case the field is omitted rather than sent empty.
///
/// Args: `(template, enabled, effort)` — `enabled` is whether this turn thinks at all, `effort` the
/// provider value for its level (already clamped to one the model supports).
pub(crate) fn kwargs(template: &Map<String, Value>, enabled: bool, effort: &str) -> Option<Value> {
if template.is_empty() {
return Some(default_kwargs(enabled));
}
let resolved: Map<String, Value> = template
.iter()
.filter_map(|(key, value)| Some((key.clone(), resolve(key, value, enabled, effort)?)))
.collect();
(!resolved.is_empty()).then_some(Value::Object(resolved))
}
/// Resolve one configured value, or `None` to leave the key out.
///
/// Anything that isn't a `$var` reference is a literal and travels verbatim — a template argument
/// can be any JSON the template understands, and Luxe has no business inspecting it.
fn resolve(key: &str, value: &Value, enabled: bool, effort: &str) -> Option<Value> {
let Some(reference) = value.as_object().filter(|object| object.contains_key("$var")) else {
return Some(value.clone());
};
// A level-shaped argument is meaningless with thinking off, and some templates raise on one.
let omit_when_off = ["omit_when_off", "omitWhenOff"]
.iter()
.any(|name| reference.get(*name).and_then(Value::as_bool).unwrap_or(false));
if omit_when_off && !enabled {
return None;
}
match reference.get("$var").and_then(Value::as_str) {
Some("thinking.enabled") => Some(Value::Bool(enabled)),
// `thinking.effort` is Pi's spelling of the same reference, accepted so a model entry can
// be carried across without translation.
Some("thinking.level" | "thinking.effort") => Some(Value::String(effort.to_string())),
other => {
// Skipped rather than guessed: sending the wrong argument is a template that renders
// the wrong prompt, which reads as a bad model rather than a bad config.
warn!(key, reference = other.unwrap_or("(not a string)"), "unknown chat-template $var");
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn template(json: Value) -> Map<String, Value> {
match json {
Value::Object(map) => map,
_ => unreachable!("fixture is an object"),
}
}
/// A config written before the map existed must send exactly what it always sent.
#[test]
fn nothing_configured_keeps_the_payload_luxe_always_sent() {
assert_eq!(
kwargs(&Map::new(), true, "high"),
Some(serde_json::json!({ "enable_thinking": true, "preserve_thinking": true }))
);
assert_eq!(
kwargs(&Map::new(), false, "none"),
Some(serde_json::json!({ "enable_thinking": false, "preserve_thinking": true }))
);
}
/// The Qwen3.8 template's real vocabulary: a flag, a literal, and a level.
#[test]
fn references_resolve_against_the_turns_thinking_level() {
let configured = template(serde_json::json!({
"enable_thinking": { "$var": "thinking.enabled" },
"preserve_thinking": false,
"reasoning_effort": { "$var": "thinking.level", "omit_when_off": true },
}));
assert_eq!(
kwargs(&configured, true, "xhigh"),
Some(serde_json::json!({
"enable_thinking": true,
"preserve_thinking": false,
"reasoning_effort": "xhigh",
})),
"a literal `false` is a value the map is there to express"
);
assert_eq!(
kwargs(&configured, false, "none"),
Some(serde_json::json!({ "enable_thinking": false, "preserve_thinking": false })),
"an effort argument is dropped when the turn does not think"
);
}
/// Pi writes the same two references in camelCase; a model entry should carry across whole.
#[test]
fn pis_spelling_of_the_same_references_is_accepted() {
let configured = template(serde_json::json!({
"reasoning_effort": { "$var": "thinking.effort", "omitWhenOff": true },
}));
assert_eq!(
kwargs(&configured, true, "medium"),
Some(serde_json::json!({ "reasoning_effort": "medium" }))
);
assert_eq!(kwargs(&configured, false, "none"), None, "and the whole field goes with it");
}
/// Guessing at a misspelled reference would render the wrong prompt, which looks like a bad
/// model rather than a bad config.
#[test]
fn an_unknown_reference_is_skipped_rather_than_guessed() {
let configured = template(serde_json::json!({
"reasoning_effort": { "$var": "thinking.levl" },
"enable_thinking": { "$var": "thinking.enabled" },
}));
assert_eq!(
kwargs(&configured, true, "high"),
Some(serde_json::json!({ "enable_thinking": true }))
);
}
/// A template argument can be any JSON the template understands.
#[test]
fn a_value_that_is_not_a_reference_travels_verbatim() {
let configured = template(serde_json::json!({
"tools_in_user_message": true,
"budget": 4096,
"persona": "terse",
"stops": ["</think>"],
"nested": { "a": 1 },
"nothing": null,
}));
assert_eq!(kwargs(&configured, true, "high"), Some(Value::Object(configured)));
}
}

View File

@@ -0,0 +1,461 @@
//! Configuration — `models.json` / `auth.json` parsing and value resolution.
//!
//! The shape of a config file and the `$ENV` / `${ENV}` / `!command` / literal forms a value may
//! take. *Which* credential a request uses is `crate::auth::source`'s job — it resolves per
//! request so a token can refresh mid-session. Keys live in [`ApiKey`], backed by
//! `secrecy::SecretString`.
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::time::Duration;
use luxe_core::secret_command::SECRET_COMMAND_TIMEOUT;
use secrecy::{ExposeSecret, SecretString};
use std::sync::Arc;
use tracing::warn;
// Compat flags describe how a request must be shaped, which is per-*model* knowledge as often as
// per-provider — so the type lives beside the rest of the metadata that travels with a request. Re-
// exported here because a compat block is written in these files and every caller in the tree knows
// it by this path.
pub use luxe_core::provider::CompatFlags;
/// An API key held in memory as a redacted, zeroize-on-drop secret.
///
/// A stand-in for a plaintext `String` that never reveals the value through `Debug`
/// or `Serialize` (both emit `[REDACTED]`), so a config or provider struct that carries one
/// can't leak the key via a log line or an accidental round-trip serialize. `Deserialize` still
/// reads the real value from config; [`ApiKey::expose`] hands it to the one place that needs it
/// (the outbound auth header). Cheap to clone — the secret is shared behind an `Arc` and zeroized
/// when the last clone drops.
#[derive(Clone)]
pub struct ApiKey(Arc<SecretString>);
impl ApiKey {
/// Wrap a resolved key value.
pub fn new(value: impl Into<String>) -> Self {
Self(Arc::new(SecretString::from(value.into())))
}
/// Borrow the raw key for the auth header. Keep the exposed lifetime as short as possible.
pub fn expose(&self) -> &str {
self.0.expose_secret()
}
/// Whether the key is empty (unset / blank).
pub fn is_empty(&self) -> bool {
self.0.expose_secret().is_empty()
}
}
impl std::fmt::Debug for ApiKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("ApiKey([REDACTED])")
}
}
impl Default for ApiKey {
fn default() -> Self {
Self::new(String::new())
}
}
impl From<String> for ApiKey {
fn from(value: String) -> Self {
Self::new(value)
}
}
impl From<&str> for ApiKey {
fn from(value: &str) -> Self {
Self::new(value)
}
}
impl<'de> serde::Deserialize<'de> for ApiKey {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(ApiKey::new(String::deserialize(deserializer)?))
}
}
impl serde::Serialize for ApiKey {
/// Fail-safe: serialize to a redacted placeholder, never the real key. Nothing in-tree
/// round-trips these configs, so this can't clobber a live key — it only guarantees a stray
/// serialize can't leak one.
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str("[REDACTED]")
}
}
/// Parsed Luxe config — the shared shape of `auth.json` and `models.json`.
///
/// The documented `auth.json` nests keys under `providers.<name>` and can also set
/// `default_provider` / `default_model`; `models.json` adds per-model overrides. Both
/// parse into this one struct so a single loader can merge them.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ModelsConfig {
/// Model overrides (provider/model -> config).
#[serde(default)]
pub models: HashMap<String, ModelConfig>,
/// Provider-level defaults (api key, base url, compat).
#[serde(default)]
pub providers: HashMap<String, ProviderConfig>,
/// Provider used when none is given on the CLI/env.
#[serde(default)]
pub default_provider: Option<String>,
/// Model used when none is given on the CLI/env.
#[serde(default)]
pub default_model: Option<String>,
}
/// Per-model configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ModelConfig {
/// Human-friendly display name for the TUI (`/model` picker + statusline). Cosmetic only —
/// the wire model id stays the `provider/id` config key, so the provider gets the exact
/// identifier it expects.
pub name: Option<String>,
/// API key (resolved via auth resolution).
pub api_key: Option<ApiKey>,
/// Base URL override.
pub base_url: Option<String>,
/// Context window override.
pub context_window: Option<u32>,
/// Max tokens override.
pub max_tokens: Option<u32>,
/// Whether this model supports reasoning/thinking.
pub reasoning: Option<bool>,
/// Input kinds this endpoint accepts (`["text", "image"]`), overriding the catalog.
///
/// The one piece of model metadata a config-resolved endpoint could not state. Every local or
/// self-hosted model — LM Studio, Ollama, vLLM, a proxy — resolves purely from this file, so
/// without it a vision model loaded with its projector reports `text`. Kept as strings rather
/// than a typed enum so an unrecognized value costs that one capability instead of failing the
/// whole file (see `catalog::resolve::parse_modalities`).
#[serde(rename = "modalities", default)]
pub input: Option<Vec<String>>,
/// Price per million tokens, for endpoints models.dev doesn't cover (a proxy, a private
/// deployment) or whose published rates don't match a negotiated one.
pub cost: Option<CostConfig>,
/// Thinking level map (level -> provider value; `null` = unsupported).
#[serde(default)]
pub thinking_level_map: HashMap<String, Option<String>>,
/// Reasoning level a session starts at on this model, overriding whatever the last session
/// chose.
///
/// The level is otherwise remembered globally, which is wrong the moment two models disagree
/// about what a level costs: a local 27B at `xhigh` spends minutes restating the question for
/// no measurable gain, and it inherited that level from the frontier model you were on an hour
/// ago. A bump made in-session still holds until the model changes — this is where you start,
/// not a ceiling. Say which levels the endpoint *cannot* do with `thinking_level_map` instead.
pub thinking: Option<luxe_core::provider::ThinkingLevel>,
/// Sampling parameters merged verbatim into the request body, after the fields Luxe sets
/// itself — so these keys win. Lets a model carry the samplers Luxe doesn't model (llama.cpp
/// `min_p`/`repeat_penalty`, vLLM `top_k`), which is how a published sampling recipe is
/// expressed at all. Merges per key over the provider's map. OpenAI-shaped APIs only.
#[serde(default)]
pub sampling_params: serde_json::Map<String, serde_json::Value>,
/// Request-shaping quirks this model needs where they differ from its provider's, **exactly as
/// written** — which is the point of the raw map.
///
/// A typed [`CompatFlags`] here could not tell a flag the user set from one serde defaulted, so
/// a model entry naming `thinking_format` would also assert `supports_usage_in_streaming: true`
/// and `cache_control_format: null` — silently switching off streamed usage, or Anthropic prompt
/// caching, for that model alone. Keys are merged over the provider's flags at resolution time
/// (`catalog::resolve`), so only what is written here overrides anything.
#[serde(default)]
pub compat: serde_json::Map<String, serde_json::Value>,
}
/// Per-model price overrides, in USD per million tokens.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq)]
pub struct CostConfig {
/// Input cost per million tokens
#[serde(default)]
pub input: f64,
/// Output cost per million tokens
#[serde(default)]
pub output: f64,
/// Cache-hit read cost per million tokens
#[serde(default)]
pub cache_read: f64,
/// Cache-write cost per million tokens
#[serde(default)]
pub cache_write: f64,
/// Cost per million tokens of a cache write kept for an hour; unset prices it at twice input
#[serde(default, skip_serializing_if = "is_unset_rate")]
pub cache_write_1h: f64,
}
fn is_unset_rate(rate: &f64) -> bool {
*rate == 0.0
}
/// Per-provider configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProviderConfig {
/// Default API key.
pub api_key: Option<ApiKey>,
/// Default base URL.
pub base_url: Option<String>,
/// models.dev provider id to inherit model metadata from, when this provider's name isn't
/// one (e.g. a `dashscope` entry serving Alibaba's catalog). Affects metadata lookup only.
pub models_dev: Option<String>,
/// Which wire API this provider speaks: `openai-completions`, `openai-responses`,
/// `anthropic-messages`, or `openai-codex`.
///
/// The built-in provider catalog normally answers this. Set it for a proxy or private deployment
/// Luxe doesn't recognize, or to pin a known provider to a different endpoint than its catalog
/// default.
pub api: Option<String>,
/// How this provider's API key goes on the wire: `bearer`, `x-api-key`, `api-key`, or
/// `foundry` (both key headers).
///
/// Named for the header rather than the vendor, because that is what a 401 shows you. The
/// catalog answers it for every provider Luxe knows; set it for a gateway that wants a
/// different one, or to send a Microsoft Entra ID token as `bearer` against a Foundry endpoint
/// that would otherwise get a key header.
pub auth: Option<String>,
/// What this endpoint answered `/models` with, last time anything asked.
///
/// The models.dev catalog is a poor description of a *local* server: it lists the models
/// people commonly run under that name, not the ones this machine has, so a picker built from
/// it offers ids the endpoint will refuse. Recorded here because the endpoint is the only
/// authority, and because it has to survive a launch with the server switched off.
///
/// An Azure resource is the same story told by a cloud: the catalog lists what Azure offers,
/// not what anybody deployed, so Luxe records the resource's deployments here too.
pub served_models: Option<Vec<String>>,
/// Deployment name → the model it runs, for a deployment named something other than its
/// model (`"sonnet-prod": "claude-sonnet-5"`).
///
/// The name is what goes on the wire; the model is what context window, output cap and price
/// are looked up under. Written by deployment discovery, and yours to write when it is off.
#[serde(default)]
pub deployments: std::collections::BTreeMap<String, String>,
/// Whether to ask an Azure resource which models it has deployed. On unless `false`.
///
/// Off leaves `served_models` and `deployments` exactly as written, for a resource whose key
/// cannot list deployments or a list you want to curate by hand.
pub discover_deployments: Option<bool>,
/// Sampling parameters applied to every model this provider serves, unless the model's own
/// map overrides the key. A local server hosting several builds usually wants one recipe.
#[serde(default)]
pub sampling_params: serde_json::Map<String, serde_json::Value>,
#[serde(default)]
pub compat: CompatFlags,
}
/// Which wire API a provider speaks: explicit config, then the built-in catalog, then the legacy
/// `use_responses_api` compat flag, then chat/completions.
///
/// One owner, because three callers need the same answer for different reasons: the CLI builds an
/// adapter with it, model resolution needs it to know whether Anthropic's required `max_tokens`
/// applies, and auth needs it to pick a header. Deriving it twice is how a provider ends up
/// resolved against an API it is not speaking.
pub fn resolve_api(
provider_name: &str,
config: Option<&ProviderConfig>,
) -> luxe_core::auth::ApiKind {
use luxe_core::auth::ApiKind;
if let Some(api) = config.and_then(|config| config.api.as_deref()).and_then(ApiKind::parse) {
return api;
}
if let Some(descriptor) = crate::auth::provider_descriptor(provider_name) {
return descriptor.api;
}
match config.is_some_and(|config| config.compat.use_responses_api) {
true => ApiKind::OpenaiResponses,
false => ApiKind::OpenaiCompletions,
}
}
/// How a provider's API key goes on the wire: its own block when it names one, else the catalog's,
/// else whatever its API implies.
pub fn resolve_key_style(
provider_name: &str,
config: Option<&ProviderConfig>,
) -> crate::auth::KeyStyle {
if let Some(style) =
config.and_then(|config| config.auth.as_deref()).and_then(crate::auth::KeyStyle::parse)
{
return style;
}
match crate::auth::provider_descriptor(provider_name) {
Some(descriptor) => descriptor.key_style(),
None => crate::auth::KeyStyle::for_api(resolve_api(provider_name, config)),
}
}
/// Resolve a value that may contain `$ENV`, `${ENV}`, `$env:ENV` or `!command` references; an
/// unset `${ENV}` expands to nothing.
pub fn resolve_value(value: &str) -> String {
// Check for `!command` on the original value (not `$!` which is an escape).
if let Some(cmd) = value.strip_prefix('!') {
return run_command(cmd.trim());
}
// Process escape sequences: `$$` → `$`, `$!` → `!`.
let mut result = String::with_capacity(value.len());
let mut chars = value.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '$' && chars.peek() == Some(&'$') {
result.push('$');
chars.next(); // consume the second `$`
} else if ch == '$' && chars.peek() == Some(&'!') {
result.push('!');
chars.next(); // consume the `!`
} else {
result.push(ch);
}
}
// The same expander `mcp.json` uses, so `${VAR}` means one thing everywhere; a bare `$NAME` is
// this file's own, and stays as written when unset since a key may hold a `$` of its own
luxe_core::mcp_client::expand_env_with_bare(&result)
}
/// Run a key command bounded by the default deadline, for the sync callers; a failure is logged
/// with stderr only and resolves to nothing.
fn run_command(cmd: &str) -> String {
luxe_core::secret_command::run_blocking(cmd, KEY_COMMAND, SECRET_COMMAND_TIMEOUT)
.unwrap_or_else(|error| {
warn!(%error, "key command failed");
String::new()
})
}
/// What a command in a config value is, in its errors: usually a key, sometimes a base URL.
const KEY_COMMAND: &str = "a configured value";
/// [`resolve_value_async`] at the default deadline, for a login checking the key it was handed.
pub async fn resolve_key(value: &str) -> Result<String, String> {
resolve_value_async(value, SECRET_COMMAND_TIMEOUT).await
}
/// [`resolve_value`] for a request: a `!command` runs bounded by `deadline` and off the runtime
/// thread, and a failure says why instead of resolving to nothing.
pub async fn resolve_value_async(value: &str, deadline: Duration) -> Result<String, String> {
match value.strip_prefix('!') {
Some(command) => {
luxe_core::secret_command::run(command.trim(), KEY_COMMAND, deadline).await
}
None => Ok(resolve_value(value)),
}
}
/// Load and parse `models.json` from a path.
pub fn load_models_config(path: &Path) -> Result<ModelsConfig, Box<dyn std::error::Error>> {
let content = fs::read_to_string(path)?;
Ok(models_config_from(serde_json::from_str(&content)?)?)
}
/// Parse an already-read `models.json`, for a caller that wants the raw document too.
pub(crate) fn models_config_from(
mut raw: serde_json::Value,
) -> Result<ModelsConfig, serde_json::Error> {
layer_catalog_compat(&mut raw);
serde_json::from_value(raw)
}
/// Fill each provider block's `compat` with the defaults for every flag the user did not write, so
/// only what they actually wrote overrides.
///
/// A provider block is normally about a base URL or a key, and the flags come along by accident:
/// `{"providers":{"anthropic":{"base_url":"…"}}}` must not deserialize `compat` from serde defaults
/// and replace the catalog's wholesale, which would silently switch off Anthropic prompt caching
/// (and every other catalog quirk) for anyone who configured a provider by hand.
///
/// The catalog answers for a provider it knows. For one it does not, the declared wire API answers
/// instead: a private Anthropic Messages deployment caches by `cache_control` however it is named,
/// and a proxy left with caching off would re-read its whole transcript at full price every turn.
fn layer_catalog_compat(raw: &mut serde_json::Value) {
let Some(providers) = raw.get_mut("providers").and_then(|value| value.as_object_mut()) else {
return;
};
for (name, block) in providers.iter_mut() {
let Some(block) = block.as_object_mut() else { continue };
let declared_api = block.get("api").and_then(|value| value.as_str()).unwrap_or_default();
let Some(defaults) = crate::auth::provider_descriptor(name)
.map(|descriptor| descriptor.compat())
.or_else(|| crate::auth::wire_api_compat_floor(declared_api))
else {
continue;
};
let Ok(serde_json::Value::Object(defaults)) = serde_json::to_value(defaults) else {
continue;
};
let written =
block.get("compat").and_then(|value| value.as_object()).cloned().unwrap_or_default();
let mut merged = defaults;
merged.extend(written);
block.insert("compat".to_string(), serde_json::Value::Object(merged));
}
}
/// The compat flags a provider runs with: its own block when the user wrote one (already layered
/// over the catalog's defaults at load), else the catalog's, else conservative ones.
///
/// One owner, because two callers need the same answer for different reasons: the adapter is built
/// with these, and a model's own keys are merged over them into its resolved [`CompatFlags`].
/// Computing it twice is how a model ends up resolved against flags its adapter is not running.
pub fn resolve_provider_compat(
provider_name: &str,
config: Option<&ProviderConfig>,
) -> CompatFlags {
match config {
Some(config) => config.compat.clone(),
None => crate::auth::provider_descriptor(provider_name)
.map(|descriptor| descriptor.compat())
.unwrap_or_default(),
}
}
/// Create an OpenAI-compatible provider from configuration.
pub fn openai_compat_provider(
config: ProviderConfig,
compat: CompatFlags,
) -> crate::openai_compat::OpenaiCompatProvider {
crate::openai_compat::OpenaiCompatProvider::new(config, compat)
}
/// Create an OpenAI Responses API provider from configuration.
pub fn openai_responses_provider(
config: ProviderConfig,
) -> crate::openai_responses::OpenaiResponsesProvider {
crate::openai_responses::OpenaiResponsesProvider::new(config)
}
/// Map the generic [`CompatFlags`] onto Anthropic's adapter flags.
///
/// The conversion itself lives on `AnthropicCompat`, which the adapter runs per request since a
/// model may carry its own flags.
pub fn anthropic_compat(flags: &CompatFlags) -> crate::anthropic::AnthropicCompat {
crate::anthropic::AnthropicCompat::from(flags)
}
/// Create an Anthropic provider from configuration + resolved model info.
pub fn anthropic_provider(
api_key: ApiKey,
base_url: Option<String>,
model_info: luxe_core::provider::ModelInfo,
compat: CompatFlags,
) -> crate::anthropic::AnthropicProvider {
crate::anthropic::AnthropicProvider::new(
api_key,
base_url,
model_info,
anthropic_compat(&compat),
)
}
mod adapter;
pub use adapter::build_adapter;
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,73 @@
//! Building an adapter — which of the wire adapters a provider's API gets, and how Copilot's three
//! are put together.
use std::sync::Arc;
use luxe_core::auth::ApiKind;
use luxe_core::provider::{ModelInfo, Provider};
use super::{anthropic_provider, openai_compat_provider, openai_responses_provider};
use super::{ApiKey, CompatFlags, ProviderConfig};
use crate::auth::AuthSource;
/// 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.
///
/// One owner for the routing, Copilot's included, so the TUI, `--rpc` and the loop cannot disagree
/// about which adapter a provider gets.
pub fn build_adapter(
api: ApiKind,
model: ModelInfo,
auth: Arc<dyn AuthSource>,
base_url: Option<String>,
compat: CompatFlags,
) -> Arc<dyn Provider + Send + Sync> {
match api {
ApiKind::AnthropicMessages => {
Arc::new(anthropic_provider(ApiKey::default(), base_url, model, compat).with_auth(auth))
}
ApiKind::OpenaiResponses | ApiKind::OpenaiCodex => {
let config = ProviderConfig { base_url, compat, ..Default::default() };
let adapter = openai_responses_provider(config);
let adapter = match api {
ApiKind::OpenaiCodex => adapter.codex(),
_ => adapter,
};
Arc::new(adapter.with_auth(auth))
}
// Copilot speaks chat completions, Responses and Anthropic Messages on one host, and picks
// per model
ApiKind::OpenaiCompletions if compat.copilot_headers => {
copilot_adapter(model, auth, base_url, compat)
}
ApiKind::OpenaiCompletions => {
let config = ProviderConfig { base_url, compat: compat.clone(), ..Default::default() };
Arc::new(openai_compat_provider(config, compat).with_auth(auth))
}
}
}
/// GitHub Copilot: one provider over its three wire APIs.
fn copilot_adapter(
model: ModelInfo,
auth: Arc<dyn AuthSource>,
base_url: Option<String>,
compat: CompatFlags,
) -> Arc<dyn Provider + Send + Sync> {
use crate::copilot::{messages_auth, CopilotAdapters, CopilotProvider};
let config = ProviderConfig { base_url, compat: compat.clone(), ..Default::default() };
let chat = openai_compat_provider(config.clone(), compat.clone()).with_auth(auth.clone());
let responses = openai_responses_provider(config.clone()).with_auth(auth.clone());
let messages = anthropic_provider(ApiKey::default(), None, model, compat)
.with_auth(messages_auth(auth.clone(), config.base_url.clone()));
let adapters = CopilotAdapters {
chat: Arc::new(chat),
responses: Arc::new(responses),
messages: Arc::new(messages),
};
Arc::new(CopilotProvider::new(adapters, auth, config.base_url))
}

View File

@@ -0,0 +1,424 @@
#![allow(clippy::unwrap_used)]
use super::*;
use luxe_core::auth::ApiKind;
use std::env;
#[test]
fn resolve_value_literal() {
assert_eq!(resolve_value("plain-key"), "plain-key");
}
#[test]
fn resolve_value_env_var() {
env::set_var("TEST_LUXE_RESOLVE", "resolved-value");
assert_eq!(resolve_value("$TEST_LUXE_RESOLVE"), "resolved-value");
env::remove_var("TEST_LUXE_RESOLVE");
}
#[test]
fn resolve_value_braced_env_var() {
env::set_var("TEST_LUXE_RESOLVE2", "braced-value");
assert_eq!(resolve_value("${TEST_LUXE_RESOLVE2}"), "braced-value");
env::remove_var("TEST_LUXE_RESOLVE2");
}
/// An unset `${VAR}` expands to nothing, as it does in `mcp.json`, while a bare `$NAME` that names
/// nothing stays as written.
///
/// The break this catches: the same `${VAR}` gave a literal here and an empty string in the MCP
/// config, so an unset key went to the provider as the text `${VAR}`.
#[test]
fn an_unset_braced_variable_is_empty_and_a_bare_one_stays() {
env::set_var("TEST_LUXE_RESOLVE_ENV_FORM", "env-form");
assert_eq!(resolve_value("$env:TEST_LUXE_RESOLVE_ENV_FORM"), "env-form", "the MCP form too");
env::remove_var("TEST_LUXE_RESOLVE_ENV_FORM");
assert_eq!(resolve_value("${LUXE_RESOLVE_DEFINITELY_UNSET}"), "");
assert_eq!(resolve_value("$LUXE_RESOLVE_DEFINITELY_UNSET"), "$LUXE_RESOLVE_DEFINITELY_UNSET");
}
#[test]
fn resolve_value_command() {
// Use a simple command that always succeeds.
assert_eq!(resolve_value("!echo hello"), "hello");
}
#[test]
fn resolve_value_escape_double_dollar() {
// `$$` should collapse to a literal `$`.
assert_eq!(resolve_value("$$"), "$");
assert_eq!(resolve_value("a$$b"), "a$b");
// After `$$`, the remaining `$key` is still subject to env expansion.
env::set_var("TEST_LUXE_KEY", "resolved");
assert_eq!(resolve_value("$$TEST_LUXE_KEY"), "resolved");
env::remove_var("TEST_LUXE_KEY");
}
#[test]
fn resolve_value_escape_dollar_bang() {
// `$!` should escape to a literal `!` so it's not treated as a command.
assert_eq!(resolve_value("$!echo hi"), "!echo hi");
// `$b` is not a valid escape — only `$$` and `$!` are.
assert_eq!(resolve_value("a$b!b"), "a$b!b");
}
/// The header a key goes out on decides whether a request is authenticated at all, and for a
/// host that re-serves another vendor's API it does not follow from the protocol.
#[test]
fn the_key_style_comes_from_the_provider_then_its_api_then_config() {
use crate::auth::KeyStyle;
// The catalog answers first — Foundry's passthrough speaks Anthropic and authenticates the
// Azure way, which no rule about the API could have derived.
assert_eq!(resolve_key_style("foundry-anthropic", None), KeyStyle::FoundryKey);
assert_eq!(resolve_key_style("foundry-openai", None), KeyStyle::Bearer);
assert_eq!(resolve_key_style("anthropic", None), KeyStyle::AnthropicKey);
assert_eq!(resolve_key_style("openai", None), KeyStyle::Bearer);
// A provider only the user knows falls back to what its API implies.
let declared = ProviderConfig { api: Some("anthropic-messages".into()), ..Default::default() };
assert_eq!(resolve_key_style("my-proxy", Some(&declared)), KeyStyle::AnthropicKey);
assert_eq!(resolve_key_style("my-proxy", None), KeyStyle::Bearer);
// And an explicit `auth` wins over both — the line that makes an Entra ID token reach a
// Foundry endpoint that would otherwise get a key header.
let entra = ProviderConfig { auth: Some("bearer".into()), ..Default::default() };
assert_eq!(resolve_key_style("foundry-anthropic", Some(&entra)), KeyStyle::Bearer);
// An unparseable value falls through rather than failing the launch, as `api` does.
let nonsense = ProviderConfig { auth: Some("semaphore".into()), ..Default::default() };
assert_eq!(resolve_key_style("foundry-anthropic", Some(&nonsense)), KeyStyle::FoundryKey);
}
/// Its three callers must agree: the adapter is built from this, the auth header is picked from
/// it, and model resolution asks it whether Anthropic's required `max_tokens` applies.
#[test]
fn the_wire_api_comes_from_config_then_the_catalog_then_the_legacy_flag() {
use luxe_core::auth::ApiKind;
assert_eq!(resolve_api("foundry-anthropic", None), ApiKind::AnthropicMessages);
assert_eq!(resolve_api("foundry-openai", None), ApiKind::OpenaiResponses);
assert_eq!(resolve_api("groq", None), ApiKind::OpenaiCompletions);
assert_eq!(resolve_api("some-proxy", None), ApiKind::OpenaiCompletions);
let pinned = ProviderConfig { api: Some("anthropic-messages".into()), ..Default::default() };
assert_eq!(resolve_api("foundry-openai", Some(&pinned)), ApiKind::AnthropicMessages);
// The pre-catalog way of asking for `/responses` still works for a config that set it.
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 compat_flags_default() {
let flags = CompatFlags::default();
assert!(!flags.supports_developer_role);
assert!(!flags.supports_reasoning_effort);
// Note: max_tokens_field has a default function, so this test verifies the default.
// The actual default is set by the `default` attribute in serde, not in Rust's Default impl.
// For this test, we just verify the struct compiles and other fields are correct.
assert!(flags.thinking_format.is_none());
assert!(flags.cache_control_format.is_none());
assert!(!flags.requires_tool_result_name);
// Usage-in-streaming is on by default so token/cost/context accounting works OOTB.
assert!(flags.supports_usage_in_streaming);
assert_eq!(flags.max_tokens_field, "max_tokens");
}
#[test]
fn compat_flags_usage_default_survives_partial_config() {
// A compat block that omits the field must still default it on (field-level serde
// default), matching the Rust Default — the reference lmstudio config relies on this.
let flags: CompatFlags = serde_json::from_str(r#"{"supports_developer_role": true}"#).unwrap();
assert!(flags.supports_usage_in_streaming);
// An explicit opt-out is still honored.
let off: CompatFlags =
serde_json::from_str(r#"{"supports_usage_in_streaming": false}"#).unwrap();
assert!(!off.supports_usage_in_streaming);
}
/// A provider block written for a base URL must not switch off the catalog's quirks.
#[test]
fn a_partial_provider_block_keeps_the_catalog_compat_defaults() {
let dir = tempfile::tempdir().expect("temp dir");
let path = dir.path().join("models.json");
std::fs::write(&path, r#"{"providers":{"anthropic":{"base_url":"https://proxy.example/v1"}}}"#)
.expect("write");
let config = load_models_config(&path).expect("loads");
let anthropic = config.providers.get("anthropic").expect("provider block");
assert_eq!(anthropic.base_url.as_deref(), Some("https://proxy.example/v1"));
assert!(
anthropic.compat.cache_control_format.is_some(),
"prompt caching must survive a block that never mentioned it"
);
}
#[test]
fn an_explicitly_written_compat_flag_still_wins() {
let dir = tempfile::tempdir().expect("temp dir");
let path = dir.path().join("models.json");
std::fs::write(
&path,
r#"{"providers":{"anthropic":{"compat":{"cache_control_format":null,"max_tokens_field":"max_completion_tokens"}}}}"#,
)
.expect("write");
let config = load_models_config(&path).expect("loads");
let anthropic = config.providers.get("anthropic").expect("provider block");
assert!(anthropic.compat.cache_control_format.is_none(), "an explicit null disables it");
assert_eq!(anthropic.compat.max_tokens_field, "max_completion_tokens");
}
#[test]
fn an_unknown_provider_block_is_left_alone() {
let dir = tempfile::tempdir().expect("temp dir");
let path = dir.path().join("models.json");
std::fs::write(&path, r#"{"providers":{"my-proxy":{"base_url":"http://localhost/v1"}}}"#)
.expect("write");
let config = load_models_config(&path).expect("loads");
let proxy = config.providers.get("my-proxy").expect("provider block");
assert!(proxy.compat.cache_control_format.is_none());
}
/// … unless it says which wire API it speaks, because that is the thing that decides whether
/// `cache_control` means anything. A hand-declared Claude proxy used to come out of here with
/// prompt caching off: no error, no warning, and roughly ten times the input bill.
#[test]
fn a_declared_anthropic_proxy_still_gets_prompt_caching() {
let dir = tempfile::tempdir().expect("temp dir");
let path = dir.path().join("models.json");
std::fs::write(
&path,
r#"{"providers":{"my-claude-proxy":{
"api": "anthropic-messages", "base_url": "https://proxy.example/v1"
}}}"#,
)
.expect("write");
let config = load_models_config(&path).expect("loads");
let proxy = config.providers.get("my-claude-proxy").expect("provider block");
assert_eq!(proxy.compat.cache_control_format.as_deref(), Some("anthropic"));
// And an explicit refusal is still a refusal.
std::fs::write(
&path,
r#"{"providers":{"my-claude-proxy":{
"api": "anthropic-messages", "compat": {"cache_control_format": null}
}}}"#,
)
.expect("write");
let config = load_models_config(&path).expect("loads");
assert!(config.providers["my-claude-proxy"].compat.cache_control_format.is_none());
}
#[test]
fn models_config_deserialize() {
let json = r#"{
"models": {
"openai/gpt-4o": {
"api_key": "sk-test",
"base_url": "https://api.openai.com/v1",
"context_window": 128000,
"max_tokens": 16000,
"reasoning": true,
"modalities": ["text", "image"],
"thinking_level_map": {
"minimal": "low",
"ultra": "max"
}
}
},
"providers": {
"openai": {
"api_key": "sk-provider",
"compat": {
"supports_developer_role": true,
"max_tokens_field": "max_completion_tokens"
}
}
}
}"#;
let config: ModelsConfig = serde_json::from_str(json).unwrap();
assert_eq!(config.models.len(), 1);
assert_eq!(config.providers.len(), 1);
let model = config.models.get("openai/gpt-4o").unwrap();
assert_eq!(model.api_key.as_ref().map(|k| k.expose()), Some("sk-test"));
assert_eq!(model.context_window, Some(128000));
assert_eq!(model.reasoning, Some(true));
// The JSON key is `modalities`; the field mirrors `ModelInfo::input`.
assert_eq!(model.input.as_deref(), Some(["text".to_string(), "image".to_string()].as_slice()));
assert_eq!(
model.thinking_level_map.get("ultra").and_then(|value| value.as_deref()),
Some("max")
);
let provider = config.providers.get("openai").unwrap();
assert!(provider.compat.supports_developer_role);
assert_eq!(provider.compat.max_tokens_field, "max_completion_tokens");
}
/// Every field here is optional, and a `models.json` written before one existed has to keep
/// parsing — it is a file on a user's disk, not something a release can migrate.
#[test]
fn an_entry_without_modalities_still_parses() {
let json = r#"{"models": {"lmstudio/local": {"context_window": 32000}}}"#;
let config: ModelsConfig = serde_json::from_str(json).unwrap();
assert_eq!(config.models["lmstudio/local"].input, None, "absent, not empty");
assert_eq!(config.models["lmstudio/local"].thinking, None, "and no starting level");
}
/// A model's starting reasoning level parses by its Luxe name, and an unknown one fails the
/// entry rather than being read as some neighboring level.
#[test]
fn a_model_can_declare_the_level_a_session_starts_at() {
let json = r#"{"models": {"lmstudio/qwen3.8-27b": {"thinking": "medium"}}}"#;
let config: ModelsConfig = serde_json::from_str(json).unwrap();
assert_eq!(
config.models["lmstudio/qwen3.8-27b"].thinking,
Some(luxe_core::provider::ThinkingLevel::Medium)
);
// `max` is the documented alias for `ultra`, the one spelling that isn't its own name.
let aliased = r#"{"models": {"x/y": {"thinking": "max"}}}"#;
let config: ModelsConfig = serde_json::from_str(aliased).unwrap();
assert_eq!(config.models["x/y"].thinking, Some(luxe_core::provider::ThinkingLevel::Ultra));
let typo = r#"{"models": {"x/y": {"thinking": "mediumish"}}}"#;
assert!(serde_json::from_str::<ModelsConfig>(typo).is_err(), "a typo is not a level");
}
/// A model's compat block is kept exactly as written, because only the keys a user typed may
/// override the provider's — see `ModelConfig::compat`. An unknown key parses and is dropped at
/// resolution, the same way an unknown sampling key reaches the endpoint and an unknown modality
/// costs one capability: a typo never fails the file.
#[test]
fn a_model_compat_block_parses_as_the_keys_that_were_written() {
let json = r#"{
"models": {
"lmstudio/fable-fusion": { "compat": {
"thinking_format": "chat_template",
"supports_developer_role": false
} },
"lmstudio/qwen3.8-27b": { "context_window": 262144 }
},
"providers": { "lmstudio": { "compat": { "thinking_format": "openai" } } }
}"#;
let config: ModelsConfig = serde_json::from_str(json).unwrap();
let written = &config.models["lmstudio/fable-fusion"].compat;
assert_eq!(written.len(), 2, "the two keys written, and nothing serde would default");
assert_eq!(written["thinking_format"], "chat_template");
assert_eq!(written["supports_developer_role"], false);
assert!(!written.contains_key("supports_usage_in_streaming"), "{written:?}");
// A model that says nothing about compat has nothing to merge — distinct from writing the
// defaults, which is exactly the distinction a typed struct here could not make.
assert!(config.models["lmstudio/qwen3.8-27b"].compat.is_empty());
// The provider's block stays typed and fully resolved: it is applied wholesale.
assert_eq!(config.providers["lmstudio"].compat.thinking_format.as_deref(), Some("openai"));
}
/// A published sampling recipe is written as JSON and carried as JSON — no key is modelled,
/// because the servers Luxe doesn't model are exactly the reason the field exists.
#[test]
fn sampling_params_parse_as_free_form_json_at_both_layers() {
let json = r#"{
"models": { "lmstudio/qwen3.8-27b": { "sampling_params": {
"temperature": 1.0, "top_k": 20, "min_p": 0.0, "repeat_penalty": 1.0
} } },
"providers": { "lmstudio": { "sampling_params": { "min_p": 0.05 } } }
}"#;
let config: ModelsConfig = serde_json::from_str(json).unwrap();
let model = config.models.get("lmstudio/qwen3.8-27b").unwrap();
assert_eq!(model.sampling_params["top_k"], 20);
assert_eq!(model.sampling_params["min_p"], 0.0);
assert_eq!(model.sampling_params["repeat_penalty"], 1.0);
assert_eq!(config.providers.get("lmstudio").unwrap().sampling_params["min_p"], 0.05);
// Absent is empty, so a config that never mentions sampling sends nothing.
let bare: ModelsConfig =
serde_json::from_str(r#"{"models":{"a/b":{}},"providers":{"a":{}}}"#).unwrap();
assert!(bare.models.get("a/b").unwrap().sampling_params.is_empty());
assert!(bare.providers.get("a").unwrap().sampling_params.is_empty());
}
#[test]
fn create_openai_compat_provider() {
use luxe_core::Provider;
let config = ProviderConfig {
api_key: Some("sk-test".into()),
base_url: Some("https://api.example.com/v1".into()),
..Default::default()
};
let provider = openai_compat_provider(config, CompatFlags::default());
assert_eq!(provider.name(), "openai_compat");
}
/// A config written for an older Luxe keeps loading: retired flags are simply ignored, and the
/// ones that are still real are honored.
#[test]
fn compat_flags_anthropic() {
let json = r#"{
"supports_eager_tool_input_streaming": true,
"supports_long_cache_retention": true,
"force_adaptive_thinking": true,
"cache_control_format": "anthropic"
}"#;
let flags: CompatFlags = serde_json::from_str(json).unwrap();
assert!(flags.force_adaptive_thinking);
assert_eq!(flags.cache_control_format.as_deref(), Some("anthropic"));
assert!(flags.supports_long_cache_retention);
assert!(!CompatFlags::default().supports_long_cache_retention, "opt-in, not a default");
}
#[test]
fn anthropic_provider_config() {
let config = ProviderConfig {
api_key: Some("sk-ant-test".into()),
base_url: Some("https://api.anthropic.com/v1".into()),
compat: CompatFlags { force_adaptive_thinking: false, ..Default::default() },
..Default::default()
};
assert_eq!(config.api_key.unwrap().expose(), "sk-ant-test");
assert_eq!(config.base_url.unwrap(), "https://api.anthropic.com/v1");
}
/// The sync form goes through the bounded runner too: from the home folder, first line only, as
/// a password manager's entry prints the secret and then everything else it holds.
#[cfg(unix)]
#[test]
fn resolve_value_runs_a_command_like_the_request_path() {
assert_eq!(resolve_value("!printf 'first\\nsecond'"), "first");
let home = luxe_core::user_dirs::home_dir().unwrap();
let home = std::fs::canonicalize(home).unwrap();
assert_eq!(std::path::PathBuf::from(resolve_value("!pwd -P")), home);
}
/// The wire API decides the adapter, and Copilot — chat completions with its own headers — is the
/// one provider routed per model between its endpoints.
#[test]
fn each_api_kind_builds_its_own_adapter() {
let auth = crate::auth::StaticAuth::bearer(None).into_arc();
let model = luxe_core::provider::ModelInfo::default();
let name_of = |api: ApiKind| {
build_adapter(api, model.clone(), auth.clone(), None, CompatFlags::default())
.name()
.to_string()
};
assert_eq!(name_of(ApiKind::AnthropicMessages), "anthropic");
assert_eq!(name_of(ApiKind::OpenaiCompletions), "openai_compat");
assert_eq!(name_of(ApiKind::OpenaiResponses), "openai_responses");
assert_eq!(name_of(ApiKind::OpenaiCodex), "openai_responses");
let copilot = resolve_provider_compat("github-copilot", None);
let built = build_adapter(ApiKind::OpenaiCompletions, model, auth, None, copilot);
assert_eq!(built.name(), "github_copilot");
}

View File

@@ -0,0 +1,431 @@
//! Copilot — one subscription, three wire APIs, chosen per model by what Copilot says it serves.
//!
//! Copilot fronts chat-completions models, Responses-only ones (the newer GPT, Grok, MAI) and
//! Claude on the same host, and refuses a model on the wrong door: "model … is not accessible via
//! the /chat/completions endpoint". Its own `/models` lists each model's `supported_endpoints`, so
//! the routing comes from there rather than from a table that rots or a guess at the id: each model
//! goes to the richest protocol it takes (Messages, then Responses, then chat completions), and one
//! Luxe knows nothing about stays on chat completions. The same list says which `reasoning_effort`
//! values each model accepts, which Copilot enforces.
//!
//! Claude takes chat completions too, but that door costs it two things: Copilot hands its thinking
//! back in fields of its own that nothing reads, and it caches only the system prompt there, so
//! the whole conversation is billed again on every call. `/v1/messages` honors thinking, effort
//! and every cache breakpoint the Anthropic adapter places.
//!
//! The list is the account's own, fetched with the request's credential the first time it is
//! needed and again once it is an hour old, or sooner for a model it has not seen.
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use futures::stream::{BoxStream, StreamExt};
use luxe_core::message::ContentBlock;
use luxe_core::provider::{
CompletionRequest, ModelInfo, Provider, ProviderError, ProviderEvent, ThinkingLevel, Usage,
};
use serde_json::Value;
use tracing::debug;
use crate::auth::{AuthSource, RequestAuth};
/// How long a fetched list is trusted before it is fetched again.
const FRESH_FOR: Duration = Duration::from_secs(60 * 60);
/// How soon a model the list does not name may send Luxe back to ask, as it may be new.
const RECHECK_UNKNOWN_AFTER: Duration = Duration::from_secs(5 * 60);
/// How long the list may take before a request goes ahead without it.
const FETCH_TIMEOUT: Duration = Duration::from_secs(10);
/// How long a reading of the plan's allowance stands before a request reads it again.
const PLAN_FRESH_FOR: Duration = Duration::from_secs(5 * 60);
/// Set to `0` to stop reading the plan's allowance.
const PLAN_USAGE_SWITCH: &str = "LUXE_COPILOT_PLAN_USAGE";
/// Copilot's `/models` API version.
const MODELS_API_VERSION: &str = "2026-06-01";
/// Where Copilot answers when the credential names no endpoint of its own.
const DEFAULT_BASE_URL: &str = "https://api.individual.githubcopilot.com";
/// Which wire API a model is spoken to in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Route {
/// `POST /chat/completions`
Chat,
/// `POST /responses`
Responses,
/// `POST /v1/messages`, Anthropic's protocol
Messages,
}
/// The account's models and the route each takes, as last fetched.
#[derive(Debug)]
struct Catalog {
/// When Luxe last asked, whether or not the answer arrived
asked: Instant,
routes: HashMap<String, Route>,
/// The `reasoning_effort` values each model takes, for the models that list any
efforts: HashMap<String, Vec<String>>,
}
/// What one request does about the model list.
enum Claim {
/// Fetch it, holding the refresh lock until done
Refresh(tokio::sync::OwnedMutexGuard<()>),
/// Wait for the fetch already running
Wait,
/// Go by what is known
Known,
}
/// The three adapters Copilot is spoken to through, one per wire API.
pub struct CopilotAdapters {
/// Chat completions, and the fallback for anything the list does not name
pub chat: Arc<dyn Provider + Send + Sync>,
/// The Responses API
pub responses: Arc<dyn Provider + Send + Sync>,
/// Anthropic Messages, authenticated through [`messages_auth`]
pub messages: Arc<dyn Provider + Send + Sync>,
}
/// GitHub Copilot, routed per model between its chat-completions, Responses and Messages endpoints.
pub struct CopilotProvider {
adapters: CopilotAdapters,
auth: Arc<dyn AuthSource>,
/// The configured base URL, for a credential that does not carry its own
base_url: Option<String>,
catalog: tokio::sync::Mutex<Option<Catalog>>,
/// Held while the list is fetched, so a request with no known route can wait for it
refreshing: Arc<tokio::sync::Mutex<()>>,
/// When the plan's allowance was last read, so a turn of many calls reads it once
plan_read: std::sync::Mutex<Option<Instant>>,
}
impl CopilotProvider {
/// Routes between adapters already built for Copilot, using `auth` to read the model list.
pub fn new(
adapters: CopilotAdapters,
auth: Arc<dyn AuthSource>,
base_url: Option<String>,
) -> Self {
Self {
adapters,
auth,
base_url,
catalog: tokio::sync::Mutex::new(None),
refreshing: Arc::default(),
plan_read: std::sync::Mutex::new(None),
}
}
/// The adapter a route is spoken through.
fn adapter(&self, route: Route) -> &Arc<dyn Provider + Send + Sync> {
match route {
Route::Chat => &self.adapters.chat,
Route::Responses => &self.adapters.responses,
Route::Messages => &self.adapters.messages,
}
}
/// The route already known for `model`, without fetching: the cache warmer asks from code that
/// cannot wait on the network, and a request that went out has already settled its route.
fn known_route(&self, model: &str) -> Route {
self.catalog
.try_lock()
.ok()
.and_then(|catalog| catalog.as_ref().and_then(|known| known.routes.get(model).copied()))
.unwrap_or(Route::Chat)
}
/// The route for `model`, fetching the account's list when it is missing, old, or silent on
/// this model and has not been asked lately.
async fn route(&self, model: &str) -> Route {
self.route_at(model, Instant::now()).await
}
/// [`Self::route`] as of `now`, so the hour can pass in a test.
///
/// The list is fetched outside the catalog's lock and stamped asked for once the fetch is
/// over: what is known stays readable meanwhile, a request with a route of its own goes by
/// it, and one without waits for the fetch and looks again. A fetch abandoned partway stamps
/// nothing, so the next request fetches.
async fn route_at(&self, model: &str, now: Instant) -> Route {
loop {
match self.claim_refresh(model, now).await {
Claim::Refresh(_refreshing) => {
let fetched = self.fetch_list().await;
let mut catalog = self.catalog.lock().await;
// a failed fetch keeps what was known, and waits its turn before asking again
let (routes, efforts) = match fetched {
Some(body) => (routes(&body), efforts(&body)),
None => catalog
.take()
.map(|known| (known.routes, known.efforts))
.unwrap_or_default(),
};
*catalog = Some(Catalog { asked: now, routes, efforts });
break;
}
Claim::Wait => drop(self.refreshing.lock().await),
Claim::Known => break,
}
}
let catalog = self.catalog.lock().await;
catalog.as_ref().and_then(|known| known.routes.get(model).copied()).unwrap_or(Route::Chat)
}
/// What a request for `model` as of `now` does about the list: fetch it, when due and nobody
/// is; wait for the fetch already running, having no route of its own; or go by what is known.
async fn claim_refresh(&self, model: &str, now: Instant) -> Claim {
let catalog = self.catalog.lock().await;
if !stale(catalog.as_ref(), model, now) {
return Claim::Known;
}
let known = catalog.as_ref().is_some_and(|known| known.routes.contains_key(model));
match Arc::clone(&self.refreshing).try_lock_owned() {
Ok(guard) => Claim::Refresh(guard),
Err(_) if !known => Claim::Wait,
Err(_) => Claim::Known,
}
}
/// Whether the plan's allowance is due a reading as of `now`, marking it read if so.
fn plan_due(&self, now: Instant) -> bool {
if std::env::var(PLAN_USAGE_SWITCH).is_ok_and(|value| value.trim() == "0") {
return false;
}
let mut read = self.plan_read.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let due = read.is_none_or(|at| now.saturating_duration_since(at) >= PLAN_FRESH_FOR);
if due {
*read = Some(now);
}
due
}
/// How much of the plan's monthly allowance is used, read with the account's GitHub sign-in.
async fn read_plan(&self) -> Option<luxe_core::provider::PlanUsage> {
let credential = self.auth.oauth_credential().await?;
crate::auth::oauth::github_copilot::plan_usage(
credential.refresh.expose(),
credential.enterprise_domain.as_deref(),
)
.await
}
/// The `reasoning_effort` values the list last said `model` takes, if it said.
async fn efforts(&self, model: &str) -> Option<Vec<String>> {
let catalog = self.catalog.lock().await;
catalog.as_ref().and_then(|known| known.efforts.get(model).cloned())
}
async fn fetch_list(&self) -> Option<Value> {
let auth = self.auth.request_auth().await.ok()?;
let base = endpoint(auth.base_url.as_deref(), self.base_url.as_deref());
let url = format!("{base}/models");
let request = crate::http::shared_client()
.get(&url)
.timeout(FETCH_TIMEOUT)
.header("Accept", "application/json")
.header("X-GitHub-Api-Version", MODELS_API_VERSION);
let response = match auth.apply(request).send().await {
Ok(response) if response.status().is_success() => response,
Ok(response) => {
debug!(status = %response.status(), "copilot model list refused");
return None;
}
Err(error) => {
debug!(%error, "copilot model list unavailable");
return None;
}
};
let body = response.json::<Value>().await.ok()?;
debug!(models = routes(&body).len(), "copilot model routes");
Some(body)
}
}
#[async_trait::async_trait]
impl Provider for CopilotProvider {
fn name(&self) -> &str {
"github_copilot"
}
async fn stream(
&self,
req: CompletionRequest,
cancel: tokio::sync::watch::Receiver<bool>,
) -> Result<BoxStream<'static, ProviderEvent>, ProviderError> {
let mut req = req;
let route = self.route(&req.model.r#ref.id).await;
if let Some(efforts) = self.efforts(&req.model.r#ref.id).await {
adopt_efforts(&mut req.model, &efforts);
}
debug!(model = %req.model.r#ref.id, ?route, "copilot route");
// Read beside the request rather than before it, so the reading costs the turn nothing
let due = self.plan_due(Instant::now());
let plan = async {
match due {
true => self.read_plan().await,
false => None,
}
};
let (plan, stream) = tokio::join!(plan, self.adapter(route).stream(req, cancel));
let stream = stream?;
Ok(match plan {
Some(plan) => {
let lead = futures::stream::once(async move { ProviderEvent::PlanUsage(plan) });
Box::pin(lead.chain(stream))
}
None => stream,
})
}
fn prompt_cache_ttl(&self, req: &CompletionRequest) -> Option<Duration> {
self.adapter(self.known_route(&req.model.r#ref.id)).prompt_cache_ttl(req)
}
async fn warm_cache(&self, req: CompletionRequest) -> Result<Usage, ProviderError> {
let route = self.route(&req.model.r#ref.id).await;
self.adapter(route).warm_cache(req).await
}
}
/// The host Copilot answers on: the credential's own, else the configured one, else the default.
fn endpoint(credential: Option<&str>, configured: Option<&str>) -> String {
credential.or(configured).unwrap_or(DEFAULT_BASE_URL).trim_end_matches('/').to_string()
}
/// Auth for the Messages adapter: Copilot's own credential and headers, pointed at `/v1`.
///
/// The Anthropic adapter appends `/messages` to its base, the way Anthropic's own API is laid out,
/// while Copilot keeps Messages under `/v1` on a host that serves chat completions at its root. The
/// host comes from the credential (Copilot names a per-account endpoint), so the version segment has
/// to be added per request rather than baked into a URL at build time.
pub fn messages_auth(auth: Arc<dyn AuthSource>, base_url: Option<String>) -> Arc<dyn AuthSource> {
Arc::new(UnderV1 { auth, base_url })
}
#[derive(Debug)]
struct UnderV1 {
auth: Arc<dyn AuthSource>,
base_url: Option<String>,
}
#[async_trait::async_trait]
impl AuthSource for UnderV1 {
async fn request_auth(&self) -> Result<RequestAuth, ProviderError> {
let mut auth = self.auth.request_auth().await?;
let host = endpoint(auth.base_url.as_deref(), self.base_url.as_deref());
auth.base_url = Some(format!("{host}/v1"));
Ok(auth)
}
}
/// Copilot's per-request headers: who started the call, what it is for, and whether it carries an
/// image.
///
/// Copilot expects the signals an editor's chat client sends, whichever wire API it is spoken in,
/// so every adapter that talks to it sends these from here and the three cannot drift. A call whose
/// last message is a tool result or an assistant reply is the agent continuing; anything else is the
/// person asking.
pub(crate) fn turn_headers(req: &CompletionRequest) -> Vec<(&'static str, &'static str)> {
let initiator = match req.messages.last().map(|message| &message.role) {
Some(luxe_core::message::Role::User) | None => "user",
Some(_) => "agent",
};
let mut headers = vec![("X-Initiator", initiator), ("Openai-Intent", "conversation-edits")];
let has_images = req.messages.iter().any(|message| {
message.content.iter().any(|block| matches!(block, ContentBlock::Image { .. }))
});
if has_images {
headers.push(("Copilot-Vision-Request", "true"));
}
headers
}
/// Whether `known` should be fetched again before routing `model` at `now`: never fetched, an hour
/// old, or silent on this model and not asked for five minutes.
fn stale(known: Option<&Catalog>, model: &str, now: Instant) -> bool {
known.is_none_or(|known| {
let age = now.saturating_duration_since(known.asked);
age >= FRESH_FOR || (!known.routes.contains_key(model) && age >= RECHECK_UNKNOWN_AFTER)
})
}
/// Each model's route, read off a `/models` body.
///
/// Each model goes to the richest protocol it takes. `/v1/messages` is Claude's, and the Anthropic
/// adapter keeps its thinking and cache breakpoints, which chat completions drops. `/responses`
/// carries a GPT's reasoning controls and its encrypted reasoning across tool calls, which is why
/// the two GPTs that take both go there. Chat completions is for the models that take nothing
/// else. A model naming none of them is left out and so stays on chat.
pub fn routes(body: &Value) -> HashMap<String, Route> {
rows(body)
.filter_map(|row| {
let id = row.get("id").and_then(Value::as_str)?;
let endpoints: Vec<&str> = row
.get("supported_endpoints")
.and_then(Value::as_array)?
.iter()
.filter_map(Value::as_str)
.collect();
let takes = |endpoint: &str| endpoints.contains(&endpoint);
let route = if takes("/v1/messages") {
Route::Messages
} else if takes("/responses") {
Route::Responses
} else if takes("/chat/completions") {
Route::Chat
} else {
return None;
};
Some((id.to_string(), route))
})
.collect()
}
/// The `reasoning_effort` values each model lists, read off a `/models` body.
pub fn efforts(body: &Value) -> HashMap<String, Vec<String>> {
rows(body)
.filter_map(|row| {
let id = row.get("id").and_then(Value::as_str)?;
let values: Vec<String> = row
.pointer("/capabilities/supports/reasoning_effort")
.and_then(Value::as_array)?
.iter()
.filter_map(Value::as_str)
.map(str::to_string)
.collect();
(!values.is_empty()).then(|| (id.to_string(), values))
})
.collect()
}
fn rows(body: &Value) -> impl Iterator<Item = &Value> {
body.get("data").and_then(Value::as_array).into_iter().flatten()
}
/// Holds `model`'s reasoning levels to the `reasoning_effort` values Copilot lists for it.
///
/// Copilot refuses any other value outright (`"medium" is not supported by model kimi-k3;
/// supported values: [low high max]`), and its list is the account's own and current, where the
/// catalog's may be neither. A level the list lacks clamps to one it has, the same way a catalog's
/// closed set does; `none` in the list is what says thinking can be switched off.
fn adopt_efforts(model: &mut ModelInfo, efforts: &[String]) {
let offered = |wire: &str| efforts.iter().any(|value| value == wire);
model.thinking_level_map = ThinkingLevel::ALL
.iter()
.filter(|level| **level != ThinkingLevel::Off)
.map(|level| {
let wire = match level {
ThinkingLevel::Ultra => "max",
other => other.as_str(),
};
(level.as_str().to_string(), offered(wire).then(|| wire.to_string()))
})
.collect();
model.reasoning = true;
model.thinking_controls.effort = true;
model.thinking_controls.can_disable = offered("none");
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,759 @@
{
"data": [
{
"billing": {
"restricted_to": [
"pro",
"pro_plus",
"individual_trial",
"edu",
"business",
"enterprise",
"max"
],
"token_prices": {
"batch_size": 1000000,
"default": {
"cache_price": 7,
"cache_write_price": 0,
"context_max": 272000,
"input_price": 75,
"output_price": 450
}
}
},
"capabilities": {
"family": "gpt-5.4-mini",
"limits": {
"max_context_window_tokens": 400000,
"max_output_tokens": 128000,
"max_prompt_tokens": 272000,
"vision": {
"max_prompt_image_size": 3145728,
"max_prompt_images": 1,
"supported_media_types": [
"image/jpeg",
"image/png",
"image/webp",
"image/gif",
"application/pdf"
]
}
},
"object": "model_capabilities",
"supports": {
"parallel_tool_calls": true,
"reasoning_effort": [
"none",
"low",
"medium",
"high",
"xhigh"
],
"streaming": true,
"structured_outputs": true,
"tool_calls": true,
"vision": true
},
"tokenizer": "o200k_base",
"type": "chat"
},
"id": "gpt-5.4-mini",
"info_messages": [
{
"code": "model_pending_deprecation",
"message": "GPT-5.4 mini has a planned deprecation date of 2026-10-19."
}
],
"is_chat_default": false,
"is_chat_fallback": false,
"model_picker_category": "lightweight",
"model_picker_enabled": true,
"model_picker_price_category": "low",
"name": "GPT-5.4 mini",
"object": "model",
"policy": {
"state": "enabled",
"terms": "Enable access to the latest GPT-5.4 mini model from OpenAI. [Learn more about how GitHub Copilot serves GPT-5.4 mini](https://gh.io/copilot-openai)."
},
"preview": false,
"supported_endpoints": [
"/responses",
"ws:/responses"
],
"vendor": "OpenAI",
"version": "gpt-5.4-mini",
"warning_messages": [
{
"code": "client_version_deprecated",
"message": "Your billing plan has changed to usage-based billing and model multipliers no longer apply. Please update your client to the latest version to see the new billing information."
}
]
},
{
"billing": {
"restricted_to": [
"pro",
"pro_plus",
"business",
"enterprise",
"max"
],
"token_prices": {
"batch_size": 1000000,
"default": {
"cache_price": 50,
"cache_write_price": 0,
"context_max": 200000,
"input_price": 200,
"output_price": 600
},
"long_context": {
"cache_price": 100,
"cache_write_price": 0,
"context_max": 500000,
"input_price": 400,
"output_price": 1200
}
}
},
"capabilities": {
"family": "grok-4.5",
"limits": {
"max_context_window_tokens": 500000,
"max_output_tokens": 128000,
"max_prompt_tokens": 372000,
"vision": {
"max_prompt_image_size": 3145728,
"max_prompt_images": 1,
"supported_media_types": [
"image/jpeg",
"image/png"
]
}
},
"object": "model_capabilities",
"supports": {
"parallel_tool_calls": true,
"reasoning_effort": [
"low",
"medium",
"high"
],
"streaming": true,
"structured_outputs": true,
"tool_calls": true,
"vision": true
},
"tokenizer": "o200k_base",
"type": "chat"
},
"id": "grok-4.5",
"info_messages": [
{
"code": "model_pending_deprecation",
"message": "Grok 4.5 has a planned deprecation date of 2026-10-19."
}
],
"is_chat_default": false,
"is_chat_fallback": false,
"model_picker_category": "versatile",
"model_picker_enabled": true,
"model_picker_price_category": "medium",
"name": "Grok 4.5",
"object": "model",
"preview": false,
"supported_endpoints": [
"/responses"
],
"vendor": "xAI",
"version": "grok-4.5",
"warning_messages": [
{
"code": "client_version_deprecated",
"message": "Your billing plan has changed to usage-based billing and model multipliers no longer apply. Please update your client to the latest version to see the new billing information."
}
]
},
{
"billing": {
"token_prices": {
"batch_size": 1000000,
"default": {
"cache_price": 2,
"cache_write_price": 0,
"input_price": 25,
"output_price": 200
}
}
},
"capabilities": {
"family": "gpt-5-mini",
"limits": {
"max_context_window_tokens": 264000,
"max_output_tokens": 64000,
"max_prompt_tokens": 128000,
"vision": {
"max_prompt_image_size": 3145728,
"max_prompt_images": 1,
"supported_media_types": [
"image/jpeg",
"image/png",
"image/webp",
"image/gif",
"application/pdf"
]
}
},
"object": "model_capabilities",
"supports": {
"parallel_tool_calls": true,
"reasoning_effort": [
"low",
"medium",
"high"
],
"streaming": true,
"structured_outputs": true,
"tool_calls": true,
"vision": true
},
"tokenizer": "o200k_base",
"type": "chat"
},
"id": "gpt-5-mini",
"info_messages": [
{
"code": "model_pending_deprecation",
"message": "GPT-5 mini has a planned deprecation date of 2026-10-19."
}
],
"is_chat_default": true,
"is_chat_fallback": false,
"model_picker_category": "lightweight",
"model_picker_enabled": true,
"model_picker_price_category": "low",
"name": "GPT-5 mini",
"object": "model",
"policy": {
"state": "enabled",
"terms": "Enable access to the latest GPT-5 mini model from OpenAI. [Learn more about how GitHub Copilot serves GPT-5 mini](https://gh.io/copilot-openai)."
},
"preview": false,
"supported_endpoints": [
"/chat/completions",
"/responses",
"ws:/responses"
],
"vendor": "Azure OpenAI",
"version": "gpt-5-mini",
"warning_messages": [
{
"code": "client_version_deprecated",
"message": "Your billing plan has changed to usage-based billing and model multipliers no longer apply. Please update your client to the latest version to see the new billing information."
}
]
},
{
"billing": {
"restricted_to": [
"pro",
"pro_plus",
"individual_trial",
"business",
"enterprise",
"max"
],
"token_prices": {
"batch_size": 1000000,
"default": {
"cache_price": 25,
"cache_write_price": 0,
"context_max": 272000,
"input_price": 250,
"output_price": 1500
},
"long_context": {
"cache_price": 50,
"cache_write_price": 0,
"context_max": 922000,
"input_price": 500,
"output_price": 2250
}
}
},
"capabilities": {
"family": "gpt-5.4",
"limits": {
"max_context_window_tokens": 1050000,
"max_output_tokens": 128000,
"max_prompt_tokens": 922000,
"vision": {
"max_prompt_image_size": 3145728,
"max_prompt_images": 1,
"supported_media_types": [
"image/jpeg",
"image/png",
"image/webp",
"image/gif",
"application/pdf"
]
}
},
"object": "model_capabilities",
"supports": {
"parallel_tool_calls": true,
"reasoning_effort": [
"none",
"low",
"medium",
"high",
"xhigh"
],
"streaming": true,
"structured_outputs": true,
"tool_calls": true,
"vision": true
},
"tokenizer": "o200k_base",
"type": "chat"
},
"id": "gpt-5.4",
"info_messages": [
{
"code": "model_pending_deprecation",
"message": "GPT-5.4 has a planned deprecation date of 2026-10-19."
}
],
"is_chat_default": false,
"is_chat_fallback": false,
"model_picker_category": "powerful",
"model_picker_enabled": true,
"model_picker_price_category": "medium",
"name": "GPT-5.4",
"object": "model",
"policy": {
"state": "enabled",
"terms": "Enable access to the latest GPT-5.4 model from OpenAI. [Learn more about how GitHub Copilot serves GPT-5.4](https://gh.io/copilot-openai)."
},
"preview": false,
"supported_endpoints": [
"/responses",
"/chat/completions",
"ws:/responses"
],
"vendor": "OpenAI",
"version": "gpt-5.4",
"warning_messages": [
{
"code": "client_version_deprecated",
"message": "Your billing plan has changed to usage-based billing and model multipliers no longer apply. Please update your client to the latest version to see the new billing information."
}
]
},
{
"billing": {
"restricted_to": [
"pro",
"pro_plus",
"business",
"enterprise",
"max"
],
"token_prices": {
"batch_size": 1000000,
"default": {
"cache_price": 20,
"cache_write_1h_price": 400,
"cache_write_price": 250,
"context_max": 200000,
"input_price": 200,
"output_price": 1000
},
"long_context": {
"cache_price": 20,
"cache_write_1h_price": 400,
"cache_write_price": 250,
"context_max": 936000,
"input_price": 200,
"output_price": 1000
}
}
},
"capabilities": {
"family": "claude-sonnet-5",
"limits": {
"max_context_window_tokens": 1000000,
"max_non_streaming_output_tokens": 16000,
"max_output_tokens": 64000,
"max_prompt_tokens": 936000,
"vision": {
"max_prompt_image_size": 3145728,
"max_prompt_images": 5,
"supported_media_types": [
"image/jpeg",
"image/png",
"image/webp",
"image/gif",
"application/pdf"
]
}
},
"object": "model_capabilities",
"supports": {
"adaptive_thinking": true,
"max_thinking_budget": 32000,
"min_thinking_budget": 1024,
"parallel_tool_calls": true,
"reasoning_effort": [
"low",
"medium",
"high",
"xhigh",
"max"
],
"streaming": true,
"structured_outputs": true,
"tool_calls": true,
"vision": true
},
"tokenizer": "o200k_base",
"type": "chat"
},
"id": "claude-sonnet-5",
"is_chat_default": false,
"is_chat_fallback": false,
"model_picker_category": "versatile",
"model_picker_enabled": true,
"model_picker_price_category": "medium",
"name": "Claude Sonnet 5",
"object": "model",
"policy": {
"state": "enabled",
"terms": "Enable access to the latest Claude model from Anthropic. [Learn more about how GitHub Copilot serves Claude](https://gh.io/copilot-claude-opus)."
},
"preview": false,
"supported_endpoints": [
"/v1/messages",
"/chat/completions"
],
"vendor": "Anthropic",
"version": "claude-sonnet-5",
"warning_messages": [
{
"code": "client_version_deprecated",
"message": "Your billing plan has changed to usage-based billing and model multipliers no longer apply. Please update your client to the latest version to see the new billing information."
}
]
},
{
"billing": {
"restricted_to": [
"pro",
"pro_plus",
"business",
"enterprise",
"max"
],
"token_prices": {
"batch_size": 1000000,
"default": {
"cache_price": 7,
"cache_write_price": 0,
"context_max": 200000,
"input_price": 75,
"output_price": 375
},
"long_context": {
"cache_price": 7,
"cache_write_price": 0,
"context_max": 983040,
"input_price": 75,
"output_price": 375
}
}
},
"capabilities": {
"family": "gemini-3.8-flash",
"limits": {
"max_context_window_tokens": 1048576,
"max_output_tokens": 65536,
"max_prompt_tokens": 983040,
"vision": {
"max_prompt_image_size": 3145728,
"max_prompt_images": 10,
"supported_media_types": [
"image/jpeg",
"image/png",
"image/webp",
"image/heic",
"image/heif",
"application/pdf"
]
}
},
"object": "model_capabilities",
"supports": {
"parallel_tool_calls": true,
"reasoning_effort": [
"low",
"medium",
"high"
],
"streaming": true,
"tool_calls": true,
"vision": true
},
"tokenizer": "o200k_base",
"type": "chat"
},
"id": "gemini-3.8-flash",
"is_chat_default": false,
"is_chat_fallback": false,
"model_picker_category": "versatile",
"model_picker_enabled": true,
"model_picker_price_category": "low",
"name": "Gemini 3.8 Flash",
"object": "model",
"policy": {
"state": "enabled",
"terms": "Enable access to the latest Gemini 3.8 Flash model from Google. [Learn more about how GitHub Copilot serves Gemini 3.8 Flash](https://docs.github.com/en/copilot/reference/ai-models/model-hosting#google-models)."
},
"preview": false,
"supported_endpoints": [
"/chat/completions"
],
"vendor": "Google",
"version": "gemini-3.8-flash",
"warning_messages": [
{
"code": "client_version_deprecated",
"message": "Your billing plan has changed to usage-based billing and model multipliers no longer apply. Please update your client to the latest version to see the new billing information."
}
]
},
{
"billing": {
"restricted_to": [
"pro_plus",
"business",
"enterprise",
"max"
],
"token_prices": {
"batch_size": 1000000,
"default": {
"cache_price": 40,
"cache_write_price": 500,
"context_max": 272000,
"input_price": 400,
"output_price": 2000
},
"long_context": {
"cache_price": 80,
"cache_write_price": 1000,
"context_max": 922000,
"input_price": 800,
"output_price": 3000
}
}
},
"capabilities": {
"family": "gpt-5.6-sol",
"limits": {
"max_context_window_tokens": 1050000,
"max_output_tokens": 128000,
"max_prompt_tokens": 922000,
"vision": {
"max_prompt_image_size": 3145728,
"max_prompt_images": 1,
"supported_media_types": [
"image/jpeg",
"image/png",
"image/webp",
"image/gif",
"application/pdf"
]
}
},
"object": "model_capabilities",
"supports": {
"parallel_tool_calls": true,
"reasoning_effort": [
"none",
"low",
"medium",
"high",
"xhigh",
"max"
],
"streaming": true,
"structured_outputs": true,
"tool_calls": true,
"vision": true
},
"tokenizer": "o200k_base",
"type": "chat"
},
"id": "gpt-5.6-sol",
"is_chat_default": false,
"is_chat_fallback": false,
"model_picker_category": "powerful",
"model_picker_enabled": false,
"model_picker_price_category": "high",
"name": "GPT-5.6 Sol",
"object": "model",
"policy": {
"state": "disabled",
"terms": "Enable access to the latest GPT-5.6 Sol model from OpenAI. [Learn more about how GitHub Copilot serves GPT-5.6 Sol](https://gh.io/copilot-openai)."
},
"preview": false,
"supported_endpoints": [
"/responses",
"ws:/responses"
],
"vendor": "OpenAI",
"version": "gpt-5.6-sol",
"warning_messages": [
{
"code": "client_version_deprecated",
"message": "Your billing plan has changed to usage-based billing and model multipliers no longer apply. Please update your client to the latest version to see the new billing information."
}
]
},
{
"billing": {
"token_prices": {
"batch_size": 0,
"default": {
"cache_price": 0,
"cache_write_price": 0,
"input_price": 0,
"output_price": 0
}
}
},
"capabilities": {
"family": "gpt-4o",
"limits": {
"max_context_window_tokens": 128000,
"max_output_tokens": 4096,
"max_prompt_tokens": 64000,
"vision": {
"max_prompt_image_size": 3145728,
"max_prompt_images": 1,
"supported_media_types": [
"image/jpeg",
"image/png",
"image/webp",
"image/gif"
]
}
},
"object": "model_capabilities",
"supports": {
"parallel_tool_calls": true,
"streaming": true,
"tool_calls": true,
"vision": true
},
"tokenizer": "o200k_base",
"type": "chat"
},
"id": "gpt-4o",
"is_chat_default": false,
"is_chat_fallback": false,
"model_picker_enabled": false,
"model_picker_price_category": "medium",
"name": "GPT-4o",
"object": "model",
"preview": false,
"vendor": "Azure OpenAI",
"version": "gpt-4o-2024-11-20",
"warning_messages": [
{
"code": "client_version_deprecated",
"message": "Your billing plan has changed to usage-based billing and model multipliers no longer apply. Please update your client to the latest version to see the new billing information."
}
]
},
{
"billing": {
"restricted_to": [
"free",
"pro",
"pro_plus",
"max"
],
"token_prices": {
"batch_size": 1000000,
"default": {
"cache_price": 30,
"cache_write_price": 0,
"context_max": 917504,
"input_price": 300,
"output_price": 1500
}
}
},
"capabilities": {
"family": "kimi-k3-base",
"limits": {
"max_context_window_tokens": 1048576,
"max_output_tokens": 131072,
"max_prompt_tokens": 917504,
"vision": {
"max_prompt_image_size": 3145728,
"max_prompt_images": 1,
"supported_media_types": [
"image/jpeg",
"image/png",
"image/webp",
"image/gif"
]
}
},
"object": "model_capabilities",
"supports": {
"parallel_tool_calls": true,
"reasoning_effort": [
"low",
"high",
"max"
],
"streaming": true,
"structured_outputs": true,
"tool_calls": true,
"vision": true
},
"tokenizer": "o200k_base",
"type": "chat"
},
"id": "kimi-k3-base",
"is_chat_default": false,
"is_chat_fallback": false,
"model_picker_category": "powerful",
"model_picker_enabled": false,
"model_picker_price_category": "medium",
"name": "Kimi K3 (GitHub)",
"object": "model",
"policy": {
"state": "enabled",
"terms": "Enable access to Kimi K3 from Moonshot AI."
},
"preview": false,
"supported_endpoints": [
"/chat/completions"
],
"vendor": "Experimental",
"version": "kimi-k3-base",
"warning_messages": [
{
"code": "client_version_deprecated",
"message": "Your billing plan has changed to usage-based billing and model multipliers no longer apply. Please update your client to the latest version to see the new billing information."
}
]
}
],
"object": "list"
}

View File

@@ -0,0 +1,483 @@
use super::*;
use crate::auth::RequestAuth;
use crate::test_server::{http_reply, read_http_request};
use luxe_core::provider::{ModelInfo, ModelRef};
use std::io::Write;
use std::sync::atomic::{AtomicUsize, Ordering};
/// Rows copied whole out of a live `GET /models` for a Copilot Pro account.
const MODELS: &str = include_str!("models.json");
/// Every shape the live list has: Responses only, both, chat and messages, chat only, a disabled
/// model, and a legacy one that names no endpoint at all. Claude lists Messages beside chat
/// completions and goes to Messages; a GPT that takes both chat and Responses goes to Responses.
#[test]
fn each_model_takes_the_route_copilot_lists_for_it() {
let routes = routes(&serde_json::from_str(MODELS).unwrap());
for (model, route) in [
("gpt-5.4-mini", Some(Route::Responses)),
("grok-4.5", Some(Route::Responses)),
("gpt-5.6-sol", Some(Route::Responses)),
("gpt-5-mini", Some(Route::Responses)),
("gpt-5.4", Some(Route::Responses)),
("claude-sonnet-5", Some(Route::Messages)),
("gemini-3.8-flash", Some(Route::Chat)),
("kimi-k3-base", Some(Route::Chat)),
("gpt-4o", None),
] {
assert_eq!(routes.get(model).copied(), route, "{model}");
}
}
/// A provider that only remembers which models it was asked for.
#[derive(Debug, Default)]
struct Recorder {
asked: std::sync::Mutex<Vec<String>>,
}
#[async_trait::async_trait]
impl Provider for Recorder {
fn name(&self) -> &str {
"recorder"
}
async fn stream(
&self,
req: CompletionRequest,
_cancel: tokio::sync::watch::Receiver<bool>,
) -> Result<BoxStream<'static, ProviderEvent>, ProviderError> {
self.asked.lock().unwrap().push(req.model.r#ref.id.clone());
Ok(Box::pin(futures::stream::empty()))
}
}
#[derive(Debug)]
struct At(String);
#[async_trait::async_trait]
impl AuthSource for At {
async fn request_auth(&self) -> Result<RequestAuth, ProviderError> {
Ok(RequestAuth { headers: Vec::new(), base_url: Some(self.0.clone()) })
}
}
/// Serves `/models` from [`MODELS`] on a local port, counting how often it is asked.
fn serve_models() -> (String, Arc<AtomicUsize>) {
serve(Vec::new())
}
/// Serves `/models`: each of `replies` once, as `(status, body)`, then [`MODELS`] from then on.
fn serve(replies: Vec<(u16, &'static str)>) -> (String, Arc<AtomicUsize>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let hits = Arc::new(AtomicUsize::new(0));
let counted = hits.clone();
std::thread::spawn(move || {
for socket in listener.incoming() {
let Ok(mut socket) = socket else { break };
assert!(read_http_request(&mut socket).starts_with("GET /models "));
let served = counted.fetch_add(1, Ordering::SeqCst);
let (status, body) = replies.get(served).copied().unwrap_or((200, MODELS));
let reply = http_reply(&format!("{status} X"), "application/json", body);
let _ = socket.write_all(reply.as_bytes());
}
});
(format!("http://127.0.0.1:{port}"), hits)
}
fn request(model: &str) -> CompletionRequest {
CompletionRequest {
model: ModelInfo { r#ref: ModelRef::new("github-copilot", model), ..Default::default() },
..Default::default()
}
}
async fn send(copilot: &CopilotProvider, model: &str) {
let (_cancel, cancelled) = tokio::sync::watch::channel(false);
let _ = copilot.stream(request(model), cancelled).await.unwrap();
}
/// Three recorders standing in for Copilot's three adapters.
struct Recorders {
chat: Arc<Recorder>,
responses: Arc<Recorder>,
messages: Arc<Recorder>,
}
impl Recorders {
fn new() -> Self {
Self {
chat: Arc::new(Recorder::default()),
responses: Arc::new(Recorder::default()),
messages: Arc::new(Recorder::default()),
}
}
fn copilot(&self, base: String) -> CopilotProvider {
let adapters = CopilotAdapters {
chat: self.chat.clone(),
responses: self.responses.clone(),
messages: self.messages.clone(),
};
CopilotProvider::new(adapters, Arc::new(At(base)), None)
}
}
/// Each model reaches the adapter for the richest endpoint it takes — Claude to Messages, GPT and
/// Grok to Responses, Gemini to chat — from one fetch of the list however many requests follow.
#[tokio::test]
async fn requests_reach_the_endpoint_their_model_takes() {
let (base, hits) = serve_models();
let recorders = Recorders::new();
let copilot = recorders.copilot(base);
let (chat, responses, messages) = (&recorders.chat, &recorders.responses, &recorders.messages);
for model in ["grok-4.5", "gpt-5-mini", "gpt-5.4-mini", "claude-sonnet-5", "gpt-5.4-mini"] {
send(&copilot, model).await;
}
assert_eq!(
*responses.asked.lock().unwrap(),
["grok-4.5", "gpt-5-mini", "gpt-5.4-mini", "gpt-5.4-mini"]
);
assert_eq!(*messages.asked.lock().unwrap(), ["claude-sonnet-5"]);
send(&copilot, "gemini-3.8-flash").await;
assert_eq!(*chat.asked.lock().unwrap(), ["gemini-3.8-flash"]);
assert_eq!(hits.load(Ordering::SeqCst), 1, "the list is fetched once, not per request");
// a model the list does not name stays on chat, and does not send Luxe straight back to ask
send(&copilot, "gpt-4o").await;
assert_eq!(chat.asked.lock().unwrap().last().map(String::as_str), Some("gpt-4o"));
assert_eq!(hits.load(Ordering::SeqCst), 1);
}
/// With no list to be had, every model goes where every Copilot model went before — Claude too,
/// which chat completions serves.
#[tokio::test]
async fn without_the_list_everything_stays_on_chat() {
let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}", closed.local_addr().unwrap());
drop(closed);
let recorders = Recorders::new();
let copilot = recorders.copilot(base);
send(&copilot, "grok-4.5").await;
send(&copilot, "claude-sonnet-5").await;
assert_eq!(*recorders.chat.asked.lock().unwrap(), ["grok-4.5", "claude-sonnet-5"]);
assert!(recorders.responses.asked.lock().unwrap().is_empty());
assert!(recorders.messages.asked.lock().unwrap().is_empty());
}
/// The list is trusted for an hour, and a model it does not name sends Luxe back to ask once it is
/// five minutes old, since that model may be new.
#[test]
fn the_list_is_asked_again_when_old_or_silent() {
use std::time::Duration;
let asked = Instant::now();
let routes = HashMap::from([("grok-4.5".into(), Route::Responses)]);
let known = Catalog { asked, routes, efforts: HashMap::new() };
let at = |minutes: u64| asked + Duration::from_secs(minutes * 60);
assert!(stale(None, "grok-4.5", asked), "never fetched");
assert!(!stale(Some(&known), "grok-4.5", at(59)));
assert!(stale(Some(&known), "grok-4.5", at(60)));
assert!(!stale(Some(&known), "new-model", at(4)), "not straight back for every unknown id");
assert!(stale(Some(&known), "new-model", at(5)));
}
/// A list that cannot be had when it is due again leaves the routes Luxe knew in place; an error
/// Copilot answers in JSON is not a list with nothing in it.
#[tokio::test]
async fn a_failed_refresh_keeps_the_routes_it_had() {
let (base, hits) = serve(vec![(200, MODELS), (500, r#"{"error":{"message":"try again"}}"#)]);
let copilot = Recorders::new().copilot(base);
let now = Instant::now();
assert_eq!(copilot.route_at("grok-4.5", now).await, Route::Responses);
let later = now + std::time::Duration::from_secs(2 * 60 * 60);
assert_eq!(copilot.route_at("grok-4.5", later).await, Route::Responses);
assert_eq!(hits.load(Ordering::SeqCst), 2, "it did ask again");
assert_eq!(copilot.name(), "github_copilot");
}
/// Messages lives under `/v1` on whichever host the credential names, else the configured one,
/// else Copilot's default.
#[tokio::test]
async fn messages_are_asked_for_under_v1_on_the_credentials_host() {
let base = |auth: Arc<dyn AuthSource>, configured: Option<&str>| {
let configured = configured.map(str::to_string);
async move { messages_auth(auth, configured).request_auth().await.unwrap().base_url }
};
let per_account = Arc::new(At("https://api.business.githubcopilot.com/".into()));
assert_eq!(
base(per_account, Some("https://ignored.example")).await.as_deref(),
Some("https://api.business.githubcopilot.com/v1")
);
let unnamed: Arc<dyn AuthSource> = crate::auth::StaticAuth::bearer(None).into_arc();
assert_eq!(
base(unnamed.clone(), Some("https://proxy.example")).await.as_deref(),
Some("https://proxy.example/v1")
);
assert_eq!(
base(unnamed, None).await.as_deref(),
Some("https://api.individual.githubcopilot.com/v1")
);
}
/// A Claude turn through Copilot, end to end through the real Anthropic adapter: the list is read,
/// the call goes to `/v1/messages` on the credential's host with Copilot's bearer and its turn
/// headers, and the body carries the cache breakpoints chat completions would have dropped.
#[tokio::test]
async fn claude_reaches_copilots_messages_endpoint_with_its_headers_and_breakpoints() {
use futures::StreamExt;
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let (seen_tx, seen_rx) = std::sync::mpsc::channel::<String>();
std::thread::spawn(move || {
for socket in listener.incoming() {
let Ok(mut socket) = socket else { break };
let request = read_http_request(&mut socket);
let (content_type, body) = if request.starts_with("GET /models ") {
("application/json", MODELS.to_string())
} else {
let _ = seen_tx.send(request);
(
"text/event-stream",
"event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n".to_string(),
)
};
let reply = http_reply("200 OK", content_type, &body);
let _ = socket.write_all(reply.as_bytes());
}
});
let auth: Arc<dyn AuthSource> = Arc::new(Copilot(base));
let compat = crate::auth::provider_descriptor("github-copilot").expect("in catalog").compat();
let messages = crate::config::anthropic_provider(
crate::config::ApiKey::default(),
None,
ModelInfo::default(),
compat,
)
.with_auth(messages_auth(auth.clone(), None));
let adapters = CopilotAdapters {
chat: Arc::new(Recorder::default()),
responses: Arc::new(Recorder::default()),
messages: Arc::new(messages),
};
let copilot = CopilotProvider::new(adapters, auth, None);
let mut turn = request("claude-sonnet-5");
turn.model.max_tokens = 1024;
turn.messages = vec![luxe_core::message::Message::user("hi")];
turn.system = Some("be brief".into());
let (_cancel, cancelled) = tokio::sync::watch::channel(false);
let mut events = copilot.stream(turn, cancelled).await.unwrap();
while events.next().await.is_some() {}
let sent = seen_rx.recv_timeout(std::time::Duration::from_secs(5)).expect("a request");
assert!(sent.starts_with("POST /v1/messages HTTP/1.1"), "{sent}");
let header = |name: &str| {
sent.lines().skip(1).take_while(|line| !line.trim().is_empty()).find_map(|line| {
let (key, value) = line.split_once(':')?;
key.trim().eq_ignore_ascii_case(name).then(|| value.trim().to_string())
})
};
assert_eq!(header("authorization").as_deref(), Some("Bearer copilot-token"), "{sent}");
assert_eq!(header("x-api-key"), None, "Copilot authenticates with its bearer");
assert_eq!(header("x-initiator").as_deref(), Some("user"), "{sent}");
assert_eq!(header("openai-intent").as_deref(), Some("conversation-edits"), "{sent}");
assert_eq!(header("anthropic-version").as_deref(), Some("2023-06-01"), "{sent}");
let body = sent.split("\r\n\r\n").nth(1).unwrap_or_default();
assert!(body.contains("\"cache_control\""), "breakpoints reach the wire: {body}");
}
/// Copilot's credential: a bearer and the host it names.
#[derive(Debug)]
struct Copilot(String);
#[async_trait::async_trait]
impl AuthSource for Copilot {
async fn request_auth(&self) -> Result<RequestAuth, ProviderError> {
Ok(RequestAuth::bearer(&crate::config::ApiKey::new("copilot-token"))
.with_base_url(self.0.clone()))
}
}
/// The effort values a model lists are the only ones Luxe sends it: Copilot refuses any other with
/// a 400. Values copied from the live list.
#[test]
fn a_models_reasoning_levels_are_the_ones_copilot_lists() {
let efforts = efforts(&serde_json::from_str(MODELS).unwrap());
let kimi = efforts.get("kimi-k3-base").expect("listed");
assert_eq!(kimi, &["low", "high", "max"]);
assert!(!efforts.contains_key("gpt-4o"), "a model listing none is left to the catalog");
let mut model = ModelInfo::default();
adopt_efforts(&mut model, kimi);
assert!(model.reasoning && model.thinking_controls.effort);
assert!(!model.thinking_controls.can_disable, "no `none`, so thinking cannot be switched off");
assert_eq!(model.thinking_level_value(ThinkingLevel::Ultra), Some("max"));
assert_eq!(model.effective_thinking_level(ThinkingLevel::Medium), ThinkingLevel::High);
assert_eq!(model.thinking_level_value(ThinkingLevel::Medium), None);
let mut gpt = ModelInfo::default();
adopt_efforts(&mut gpt, efforts.get("gpt-5.4").expect("listed"));
assert!(gpt.thinking_controls.can_disable, "`none` is listed");
assert_eq!(gpt.thinking_level_value(ThinkingLevel::XHigh), Some("xhigh"));
}
/// Effort reaches a chat-completions model only as a value it takes, and never as `none` to one
/// that cannot stop thinking.
#[test]
fn chat_completions_effort_is_held_to_the_models_list() {
let compat = crate::auth::provider_descriptor("github-copilot").expect("in catalog").compat();
let adapter =
crate::config::openai_compat_provider(crate::config::ProviderConfig::default(), compat);
let mut kimi = request("kimi-k3");
adopt_efforts(&mut kimi.model, &["low".into(), "high".into(), "max".into()]);
let body = |thinking| {
let mut turn = kimi.clone();
turn.thinking = thinking;
adapter.body_for_tests(&turn)
};
assert_eq!(body(ThinkingLevel::Ultra)["reasoning_effort"], "max");
assert_eq!(body(ThinkingLevel::Medium)["reasoning_effort"], "high");
assert!(body(ThinkingLevel::Off).get("reasoning_effort").is_none());
}
/// The plan's allowance is read once every five minutes however many requests a turn makes, and
/// not at all when switched off.
#[test]
fn the_plan_is_read_at_most_every_five_minutes() {
let copilot = Recorders::new().copilot("http://127.0.0.1:9".into());
let start = Instant::now();
let at = |minutes: u64| start + std::time::Duration::from_secs(minutes * 60);
assert!(copilot.plan_due(start), "never read");
assert!(!copilot.plan_due(at(1)));
assert!(!copilot.plan_due(at(4)));
assert!(copilot.plan_due(at(5)));
assert!(!copilot.plan_due(at(6)));
}
/// Serves the first `prompt` requests for the list at once, then holds each later one until
/// `release` says so.
fn serve_then_hold(prompt: usize) -> (String, Arc<AtomicUsize>, std::sync::mpsc::Sender<()>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let hits = Arc::new(AtomicUsize::new(0));
let counted = hits.clone();
let (release, released) = std::sync::mpsc::channel::<()>();
std::thread::spawn(move || {
for socket in listener.incoming() {
let Ok(mut socket) = socket else { break };
read_http_request(&mut socket);
if counted.fetch_add(1, Ordering::SeqCst) >= prompt {
let _ = released.recv();
}
let reply = http_reply("200 OK", "application/json", MODELS);
let _ = socket.write_all(reply.as_bytes());
}
});
(format!("http://127.0.0.1:{port}"), hits, release)
}
/// While the list is being fetched again, the routes already known still answer, and a second
/// request does not fetch it a second time.
///
/// The break this catches: the fetch ran under the catalog's lock, so for up to ten seconds the
/// cache warmer, which cannot wait, read no route at all and sent a Claude request to chat
/// completions.
#[tokio::test(flavor = "multi_thread")]
async fn a_refresh_in_flight_leaves_the_known_routes_readable() {
let (base, hits, release) = serve_then_hold(1);
let copilot = Arc::new(Recorders::new().copilot(base));
let now = Instant::now();
assert_eq!(copilot.route_at("claude-sonnet-5", now).await, Route::Messages);
let later = now + std::time::Duration::from_secs(2 * 60 * 60);
let refreshing = {
let copilot = copilot.clone();
tokio::spawn(async move { copilot.route_at("claude-sonnet-5", later).await })
};
while hits.load(Ordering::SeqCst) < 2 {
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
}
assert_eq!(copilot.known_route("claude-sonnet-5"), Route::Messages, "readable mid-fetch");
assert_eq!(copilot.route_at("claude-sonnet-5", later).await, Route::Messages);
release.send(()).unwrap();
assert_eq!(refreshing.await.unwrap(), Route::Messages);
assert_eq!(hits.load(Ordering::SeqCst), 2, "one refresh, not one per request");
}
/// Requests arriving while the first fetch of the list is under way wait for it, rather than
/// going down chat completions for want of a route.
///
/// The break this catches: the first request marked the list asked for and fetched it outside the
/// lock, so a second one found an empty list it was not due to refresh and sent Claude to chat.
#[tokio::test(flavor = "multi_thread")]
async fn requests_during_the_first_fetch_wait_for_its_routes() {
let (base, hits, release) = serve_then_hold(0);
let copilot = Arc::new(Recorders::new().copilot(base));
let now = Instant::now();
let first = {
let copilot = copilot.clone();
tokio::spawn(async move { copilot.route_at("claude-sonnet-5", now).await })
};
while hits.load(Ordering::SeqCst) < 1 {
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
}
let second = {
let copilot = copilot.clone();
tokio::spawn(async move { copilot.route_at("claude-sonnet-5", now).await })
};
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
assert!(!second.is_finished(), "it waits for the list rather than guessing");
release.send(()).unwrap();
assert_eq!(first.await.unwrap(), Route::Messages);
assert_eq!(second.await.unwrap(), Route::Messages);
assert_eq!(hits.load(Ordering::SeqCst), 1, "one fetch for both");
}
/// A fetch abandoned partway, as a cancelled turn abandons it, leaves the list due: a request
/// that was waiting on it fetches it rather than giving up, and so does the next one.
///
/// The break this catches: the "asked" mark went on before the fetch, so a cancelled first fetch
/// left an empty list marked fresh, and every request for five minutes went to chat completions.
#[tokio::test(flavor = "multi_thread")]
async fn an_abandoned_fetch_leaves_the_list_due() {
let (base, hits, release) = serve_then_hold(0);
let copilot = Arc::new(Recorders::new().copilot(base));
let now = Instant::now();
let spawn_route = || {
let copilot = copilot.clone();
tokio::spawn(async move { copilot.route_at("claude-sonnet-5", now).await })
};
let abandoned = spawn_route();
while hits.load(Ordering::SeqCst) < 1 {
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
}
let waiting = spawn_route();
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
abandoned.abort();
let _ = abandoned.await;
// the server answers one connection at a time: let the abandoned one go first
release.send(()).unwrap();
let asked_again = async {
while hits.load(Ordering::SeqCst) < 2 && !waiting.is_finished() {
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
}
};
tokio::time::timeout(std::time::Duration::from_secs(5), asked_again).await.unwrap();
release.send(()).unwrap();
assert_eq!(waiting.await.unwrap(), Route::Messages, "the waiter fetched it itself");
assert_eq!(copilot.route_at("claude-sonnet-5", now).await, Route::Messages);
assert_eq!(hits.load(Ordering::SeqCst), 2, "and nobody asked a third time");
}
/// A fetch that failed waits its turn: the next request does not ask again straight away.
#[tokio::test]
async fn a_failed_first_fetch_is_not_retried_at_once() {
let (base, hits) = serve(vec![(500, r#"{"error":{"message":"try again"}}"#)]);
let copilot = Recorders::new().copilot(base);
let now = Instant::now();
assert_eq!(copilot.route_at("grok-4.5", now).await, Route::Chat);
assert_eq!(copilot.route_at("grok-4.5", now).await, Route::Chat);
assert_eq!(hits.load(Ordering::SeqCst), 1);
}

View File

@@ -0,0 +1,233 @@
//! One HTTP client for the whole process.
//!
//! `reqwest::Client` owns a connection pool and a TLS configuration, so building one per request
//! throws away keep-alive and pays a fresh handshake every turn. It also stops being free once Luxe
//! registers an adapter per known provider: twenty pools for one active conversation.
//!
//! Cloning the handle is cheap and shares the pool, which is the intended usage.
use std::sync::OnceLock;
use std::time::Duration;
/// How long to wait for a connection to open. Covers TCP and TLS only: the wait for the response
/// to start is [`START_TIMEOUT`], and a stream that goes quiet is [`IDLE_TIMEOUT`]'s.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
/// How long a provider has to start answering a model request: its response headers.
///
/// Not a whole-request timeout, because a body streams for as long as the model talks. Without
/// it a provider that accepted the connection and then said nothing held the turn open for good.
pub(crate) const START_TIMEOUT: Duration = Duration::from_secs(60);
/// How long a model's stream may go without a byte before it counts as stalled.
///
/// Generous, because a reasoning model can think for a long while between events, and a stall
/// before the first event is retried rather than reported.
pub(crate) const IDLE_TIMEOUT: Duration = Duration::from_secs(180);
/// [`START_TIMEOUT`], or `LUXE_STREAM_START_TIMEOUT` in seconds; `0` waits forever.
pub(crate) fn start_timeout() -> Option<Duration> {
timeout_from_env("LUXE_STREAM_START_TIMEOUT", START_TIMEOUT)
}
/// [`IDLE_TIMEOUT`], or `LUXE_STREAM_IDLE_TIMEOUT` in seconds; `0` waits forever.
pub(crate) fn idle_timeout() -> Option<Duration> {
timeout_from_env("LUXE_STREAM_IDLE_TIMEOUT", IDLE_TIMEOUT)
}
fn timeout_from_env(name: &str, default: Duration) -> Option<Duration> {
let seconds = std::env::var(name).ok().and_then(|value| value.trim().parse::<u64>().ok());
match seconds {
Some(0) => None,
Some(seconds) => Some(Duration::from_secs(seconds)),
None => Some(default),
}
}
/// Sends a model request and waits for it to start answering, at most [`start_timeout`].
///
/// A timeout says "timed out", which is what classifies it as a transport failure worth trying
/// again rather than a request to change.
pub(crate) async fn send(
request: reqwest::RequestBuilder,
) -> Result<reqwest::Response, luxe_core::provider::ProviderError> {
let network = |error: reqwest::Error| {
luxe_core::provider::ProviderError::Other(format!(
"network error: {}",
luxe_core::provider::describe_error_chain(&error)
))
};
match start_timeout() {
None => request.send().await.map_err(network),
Some(limit) => match tokio::time::timeout(limit, request.send()).await {
Ok(sent) => sent.map_err(network),
Err(_) => Err(luxe_core::provider::ProviderError::Other(format!(
"network error: timed out after {}s waiting for the provider to start answering",
limit.as_secs()
))),
},
}
}
/// The error for a response that came back with a failing `status`, carrying both halves so the
/// status decides its kind rather than a search of the body.
pub(crate) fn status_error(
status: reqwest::StatusCode,
body: String,
) -> luxe_core::provider::ProviderError {
luxe_core::provider::ProviderError::Http { status: status.as_u16(), body }
}
/// What a provider's own error type or code says to do about it.
///
/// Read from the payload, so it never depends on the wording beside it. A type naming none of
/// these stays `Other`, which leaves the words to decide.
pub(crate) fn kind_of_error_type(error_type: &str) -> luxe_core::provider::ProviderErrorKind {
use luxe_core::provider::ProviderErrorKind as Kind;
match error_type {
"overloaded_error" | "api_error" | "server_error" | "service_unavailable" => {
Kind::Unavailable
}
"rate_limit_error" | "rate_limit_exceeded" => Kind::RateLimit,
"authentication_error" | "permission_error" | "invalid_api_key" => Kind::Auth,
"context_length_exceeded" => Kind::Overflow,
other => Kind::Other(other.to_string()),
}
}
/// What an error's `code` says: a name, like a type, or a number, read as the HTTP status it is.
///
/// Servers disagree: OpenAI sends `"context_length_exceeded"`, vLLM and llama.cpp send `429`.
pub(crate) fn kind_of_code(
code: &serde_json::Value,
message: &str,
) -> Option<luxe_core::provider::ProviderErrorKind> {
match code {
serde_json::Value::String(name) => Some(kind_of_error_type(name)),
serde_json::Value::Number(number) => {
let status = u16::try_from(number.as_u64()?).ok()?;
let body = message.to_string();
Some(luxe_core::provider::ProviderError::Http { status, body }.kind())
}
_ => None,
}
}
/// What an error frame's `type` and `code` say, whichever names something to do, since a proxy
/// may fill in either one; else the type's own name, else "unknown".
pub(crate) fn kind_of_frame(
error_type: Option<&str>,
code: Option<&serde_json::Value>,
message: &str,
) -> luxe_core::provider::ProviderErrorKind {
use luxe_core::provider::ProviderErrorKind as Kind;
let typed = error_type.map(kind_of_error_type);
let coded = code.and_then(|code| kind_of_code(code, message));
let kinds: Vec<Kind> = [typed, coded].into_iter().flatten().collect();
let named = kinds.iter().find(|kind| !matches!(kind, Kind::Other(_)));
named.or(kinds.first()).cloned().unwrap_or_else(|| Kind::Other("unknown".into()))
}
/// A JSON request with `headers` on it, `Content-Type` among them or not.
///
/// `json` sets `Content-Type` itself and `header` *appends*, so a request that sets both carries
/// the header twice. OpenAI tolerates that and a strict proxy does not: an HTTP/1.1 server is
/// entitled to refuse a duplicated `Content-Type` outright, and aiohttp does. One owner for the
/// shape, so no adapter can get it wrong again.
pub(crate) fn json_request(
request: reqwest::RequestBuilder,
headers: &[(&str, &str)],
body: &serde_json::Value,
) -> reqwest::RequestBuilder {
headers
.iter()
.filter(|(name, _)| !name.eq_ignore_ascii_case("content-type"))
.fold(request.json(body), |request, (name, value)| request.header(*name, *value))
}
pub(crate) fn shared_client() -> reqwest::Client {
static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
CLIENT
.get_or_init(|| {
reqwest::Client::builder()
.connect_timeout(CONNECT_TIMEOUT)
.user_agent(user_agent())
.build()
.unwrap_or_else(|error| {
// A client that can't be built means no TLS backend; every request would fail
// anyway, and a default client gives a clearer error at the call site.
tracing::error!(%error, "falling back to a default HTTP client");
reqwest::Client::new()
})
})
.clone()
}
/// `luxe/<version>` — what providers see in their logs.
pub(crate) fn user_agent() -> String {
format!("luxe/{}", luxe_core::version::VERSION)
}
#[cfg(test)]
mod json_request_tests {
use super::*;
/// One `Content-Type`, whoever asked for it: a duplicate is refused by strict servers.
#[test]
fn a_json_request_carries_one_content_type() {
let headers = [("Content-Type", "application/json"), ("Accept", "text/event-stream")];
let request = json_request(
reqwest::Client::new().post("http://127.0.0.1:9/x"),
&headers,
&serde_json::json!({"a": 1}),
)
.build()
.expect("a request");
assert_eq!(request.headers().get_all("content-type").iter().count(), 1);
assert_eq!(request.headers()["accept"], "text/event-stream");
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A server that takes the request and never answers: the wait ends at the start timeout,
/// saying "timed out", which is what makes it a failure worth trying again.
///
/// The clock is paused only once the request has arrived. Paused from the start, it jumped to
/// the next timer while the OS was still connecting, which on macOS is often the case, and the
/// connect timeout fired instead of the one under test.
#[tokio::test]
async fn a_provider_that_never_starts_answering_times_out() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("bind");
let address = listener.local_addr().expect("address");
let (arrived, heard) = tokio::sync::oneshot::channel();
let _held = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.expect("accept");
let mut buffer = [0u8; 64];
let _ = tokio::io::AsyncReadExt::read(&mut socket, &mut buffer).await;
let _ = arrived.send(());
std::future::pending::<()>().await;
});
let request = shared_client().post(format!("http://{address}/v1/messages")).body("{}");
let waiting = tokio::spawn(send(request));
heard.await.expect("the request arrived");
tokio::time::pause();
let error = waiting.await.expect("joined").expect_err("nothing came back");
let message = error.to_string();
assert!(message.contains("timed out after 60s"), "{message}");
assert!(error.kind().is_transient(), "{message}");
}
#[test]
fn handing_out_the_client_twice_costs_nothing_and_identifies_luxe() {
let first = shared_client();
let second = shared_client();
// Both handles are usable; the point of the OnceLock is that only one pool exists behind
// them, which isn't observable from the public API beyond "this doesn't panic or stall".
assert!(first.get("http://127.0.0.1:1/").build().is_ok());
assert!(second.get("http://127.0.0.1:1/").build().is_ok());
assert!(user_agent().starts_with("luxe/"));
}
}

View File

@@ -0,0 +1,79 @@
//! Learned — what a rejection taught an adapter about a model, kept for the session.
//!
//! A 400 can say which thinking encoding, output cap or tool-loading mode a model really accepts.
//! Remembering it keeps the correction to one wasted round trip per model per session instead of
//! one per turn. Keyed by model id, since one adapter serves every model behind its endpoint.
use std::collections::HashMap;
use std::sync::{Mutex, PoisonError};
/// A per-model memory, shared by every request the adapter sends.
///
/// A poisoned lock still answers: a panic elsewhere must not make the adapter forget, and a
/// forgotten correction costs a round trip on every turn.
#[derive(Debug)]
pub(crate) struct Learned<T> {
by_model: Mutex<HashMap<String, T>>,
}
impl<T> Default for Learned<T> {
fn default() -> Self {
Self { by_model: Mutex::new(HashMap::new()) }
}
}
impl<T: Clone> Learned<T> {
/// What was learned about `model`, if anything.
pub(crate) fn get(&self, model: &str) -> Option<T> {
self.by_model.lock().unwrap_or_else(PoisonError::into_inner).get(model).cloned()
}
/// Keep `value` for `model`, replacing what was there.
pub(crate) fn remember(&self, model: &str, value: T) {
self.by_model
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(model.to_string(), value);
}
/// Whether anything was learned about `model`, for a lesson that carries no value.
pub(crate) fn knows(&self, model: &str) -> bool {
self.by_model.lock().unwrap_or_else(PoisonError::into_inner).contains_key(model)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
#[test]
fn a_lesson_is_kept_for_its_model_alone() {
let learned = Learned::<u32>::default();
assert_eq!(learned.get("a"), None);
learned.remember("a", 64_000);
learned.remember("a", 32_000);
assert_eq!(learned.get("a"), Some(32_000), "the later lesson replaces the earlier");
assert_eq!(learned.get("b"), None);
assert!(learned.knows("a") && !learned.knows("b"));
}
/// A thread that panics holding the lock poisons it; reading that as having learned nothing
/// would send the corrected request's mistake again on every turn.
#[test]
fn a_poisoned_lock_still_remembers_and_still_learns() {
let learned = Arc::new(Learned::<u32>::default());
learned.remember("a", 1);
let holder = Arc::clone(&learned);
let _ = std::thread::spawn(move || {
let _held = holder.by_model.lock().unwrap();
panic!("poison the lock");
})
.join();
assert!(learned.by_model.is_poisoned(), "the setup poisoned it");
assert_eq!(learned.get("a"), Some(1));
assert!(learned.knows("a") && !learned.knows("b"));
learned.remember("b", 2);
assert_eq!(learned.get("b"), Some(2));
}
}

View File

@@ -0,0 +1,30 @@
//! luxe-providers — LLM provider adapters.
//!
//! Hand-rolled thin adapters for OpenAI-compatible APIs, Anthropic, and Gemini.
//! Depends on `luxe-core` for the `Provider` trait. [`catalog`] resolves what Luxe knows
//! about a model — layering the embedded models.dev snapshot, the refreshed cache, and the
//! user's config — so every entry point runs on the same metadata. [`auth`] owns credentials:
//! the curated provider catalog, the `0600` store, the OAuth flows, and the per-request auth the
//! adapters resolve on every call.
pub mod anthropic;
pub mod auth;
pub mod catalog;
mod chat_template;
pub mod config;
pub mod copilot;
mod http;
mod learned;
pub mod openai_compat;
pub mod openai_responses;
pub mod wire;
mod sampling;
mod sse;
mod wire_json;
#[cfg(test)]
mod provider_errors_tests;
#[cfg(test)]
mod test_server;

View File

@@ -0,0 +1,114 @@
//! OpenAI-compatible provider adapter.
//!
//! Implements the [`Provider`] trait for any API that speaks the OpenAI chat completions
//! format (OpenAI, Ollama, vLLM, LMStudio, etc.).
use crate::config::{CompatFlags, ProviderConfig};
use futures::stream::BoxStream as FBoxStream;
use luxe_core::provider::{CompletionRequest, Provider, ProviderError, ProviderEvent};
use tracing::debug;
mod request;
mod sse;
mod thinking;
pub(crate) use request::copilot_request_headers;
use request::request_headers;
pub(crate) use sse::CompatDecoder;
/// Default OpenAI API base URL.
const DEFAULT_BASE_URL: &str = "https://api.openai.com/v1";
/// OpenAI-compatible provider adapter.
#[derive(Debug, Clone)]
pub struct OpenaiCompatProvider {
/// Provider configuration.
config: ProviderConfig,
/// Compatibility flags.
compat: CompatFlags,
/// Optional base URL override.
base_url: Option<String>,
/// Where this call's auth comes from. Resolved per request so an OAuth token can refresh and a
/// mid-session `/login` takes effect without rebuilding the adapter.
auth: std::sync::Arc<dyn crate::auth::AuthSource>,
}
impl OpenaiCompatProvider {
/// Create a new adapter from configuration.
pub fn new(config: ProviderConfig, compat: CompatFlags) -> Self {
let auth = crate::auth::StaticAuth::bearer(config.api_key.clone()).into_arc();
Self { config, compat, base_url: None, auth }
}
/// Set a custom base URL (overrides config).
pub fn with_base_url(mut self, url: String) -> Self {
self.base_url = Some(url);
self
}
/// Resolve auth from a credential store instead of the fixed config key.
pub fn with_auth(mut self, auth: std::sync::Arc<dyn crate::auth::AuthSource>) -> Self {
self.auth = auth;
self
}
/// Get the effective base URL.
fn effective_base_url(&self) -> &str {
self.base_url
.as_deref()
.unwrap_or(self.config.base_url.as_deref().unwrap_or(DEFAULT_BASE_URL))
}
/// The flags this request is shaped by: the model's own when it resolved any, else the
/// provider's.
///
/// Read per request rather than held, because one adapter serves every model on its endpoint and
/// a local server hosting two builds is the ordinary case — the chat templates disagree about the
/// `developer` role and about how thinking is asked for, and the adapter is built once.
fn compat_for<'a>(&'a self, req: &'a CompletionRequest) -> &'a CompatFlags {
req.model.compat.as_ref().unwrap_or(&self.compat)
}
}
#[async_trait::async_trait]
impl Provider for OpenaiCompatProvider {
fn name(&self) -> &str {
"openai_compat"
}
async fn stream(
&self,
req: CompletionRequest,
cancel: tokio::sync::watch::Receiver<bool>,
) -> Result<FBoxStream<'static, ProviderEvent>, ProviderError> {
// Auth first: a missing credential is a question for the user, not a request to send.
let auth = self.auth.request_auth().await?;
// `base_url` already includes the API version segment (e.g. `.../v1`). A credential may pin
// its own endpoint (GitHub Copilot's per-account proxy), which wins over the default.
let base = auth.base_url.clone().unwrap_or_else(|| self.effective_base_url().to_string());
let url = format!("{}/chat/completions", base.trim_end_matches('/'));
let body = self.build_request_body(&req);
debug!(url = %url, model = %req.model.r#ref.id, "sending completion request");
let mut headers = vec![("Content-Type", "application/json")];
headers.extend(request_headers(self.compat_for(&req), &req));
let request =
crate::http::json_request(crate::http::shared_client().post(&url), &headers, &body);
crate::wire::record_request(self.name(), &url, &headers, &body);
let response = crate::http::send(auth.apply(request)).await?;
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(crate::http::status_error(status, body));
}
// Decode the SSE body as it arrives so text and reasoning reach the UI while the model is
// still producing them, and a cancel can drop the connection mid-call.
Ok(crate::sse::decode(response.bytes_stream(), cancel, CompatDecoder::default()))
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,370 @@
//! Chat-completions request building — core messages to `POST /chat/completions` wire JSON.
use std::collections::HashMap;
use luxe_core::message::ContentBlock;
use luxe_core::provider::CompletionRequest;
use super::thinking::apply_thinking_config;
use super::OpenaiCompatProvider;
use crate::config::CompatFlags;
use crate::wire_json::data_url;
impl OpenaiCompatProvider {
/// The body a request would go out with, for tests elsewhere in the crate.
#[cfg(test)]
pub(crate) fn body_for_tests(&self, req: &CompletionRequest) -> serde_json::Value {
self.build_request_body(req)
}
/// Build the JSON request body for `POST /chat/completions`.
pub(super) fn build_request_body(&self, req: &CompletionRequest) -> serde_json::Value {
let compat = self.compat_for(req);
// Empty unless this endpoint needs the name, which is the only reason to walk the transcript
// for it — an absent entry then simply means no name to attach.
let tool_names = match compat.requires_tool_result_name {
true => tool_names_by_call(&req.messages),
false => HashMap::new(),
};
let mut messages: Vec<serde_json::Value> = Vec::with_capacity(req.messages.len());
// A `tool` message has nowhere to put an image — this schema allows content parts only on
// a `user` message — and a `user` message may not be interleaved between two `tool`
// messages. Luxe emits consecutive tool messages routinely (refusals, then results, plus a
// synthesized repair), so the pixels are collected across the whole *run* and handed over
// once, after every tool message in it.
let accepts_images = req.model.input.contains(&luxe_core::provider::Modality::Image);
let mut index = 0;
while index < req.messages.len() {
if req.messages[index].role != luxe_core::message::Role::Tool {
push_wire_messages(
&req.messages[index],
&mut messages,
&tool_names,
compat.copilot_headers,
);
index += 1;
continue;
}
let mut images: Vec<(String, String)> = Vec::new();
while index < req.messages.len()
&& req.messages[index].role == luxe_core::message::Role::Tool
{
push_tool_messages(
&req.messages[index],
&mut messages,
accepts_images.then_some(&mut images),
&tool_names,
);
index += 1;
}
if let Some(carrier) = image_carrier_message(&images) {
messages.push(carrier);
}
}
if let Some(system) = &req.system {
// `developer` is the newer OpenAI spelling of the system turn. The flag parsed,
// resolved and displayed while this line said `system` regardless, which is a setting
// that reads back what you set and does nothing.
//
// Honored rather than dropped because the local backends it defaults on for all take
// it: Ollama forwards the role verbatim, llama.cpp accepts it and folds it into
// `system` for ordinary templates while keeping the two distinct for GPT-OSS/Harmony,
// where the difference is real, and LM Studio serves it fine.
let role = if compat.supports_developer_role { "developer" } else { "system" };
messages.insert(0, serde_json::json!({"role": role, "content": system}));
}
let mut body = serde_json::json!({
"model": req.model.r#ref.id,
"messages": serde_json::Value::Null,
"stream": true,
});
body["messages"] = serde_json::Value::Array(messages); // moved in; `json!` would clone it
// Ask for usage in the streamed response so token/cost/context accounting works. Most
// OpenAI-compatible servers require this opt-in; without it the stream omits usage.
if compat.supports_usage_in_streaming {
body["stream_options"] = serde_json::json!({ "include_usage": true });
}
if !req.tools.is_empty() {
body["tools"] = serde_json::Value::Array(
req.tools
.iter()
.map(|t| {
serde_json::json!({
"type": "function",
"function": {
"name": t.name,
"description": t.description,
"parameters": t.parameters
}
})
})
.collect::<Vec<_>>(),
);
}
if let Some(max_tokens) = req.max_tokens {
let field = if compat.max_tokens_field == "max_completion_tokens" {
"max_completion_tokens"
} else {
"max_tokens"
};
body[field] = max_tokens.into();
}
apply_thinking_config(&mut body, req, compat);
apply_cache_control(&mut body, compat, req.reuse);
// Last, so the model's own recipe outranks every field above it.
crate::sampling::apply(&mut body, &req.model.sampling_params);
body
}
}
/// Ask a gateway that supports it to serve the stable prefix of this turn from cache.
///
/// Only OpenRouter's spelling lives here, and it is one field: the gateway places the breakpoint on
/// the last cacheable block itself and advances it as the conversation grows, which is exactly the
/// shape an agentic session wants and the reason not to hand-place markers the way the Anthropic
/// adapter must. Worth it by a wide margin — a Claude turn through OpenRouter costs ~10x less from
/// the second turn on — and the models that don't cache this way ignore the field rather than
/// refusing it, so it needs no per-model gate. Anthropic is the one that needs asking: OpenRouter
/// does *not* cache Claude implicitly, so without this every turn re-reads the whole transcript at
/// full price.
fn apply_cache_control(
body: &mut serde_json::Value,
compat: &CompatFlags,
reuse: luxe_core::provider::PromptReuse,
) {
// A one-off prompt is never read back, so a breakpoint on it only buys the write premium.
if compat.cache_control_format.as_deref() == Some("openrouter") && reuse.worth_caching() {
body["cache_control"] = serde_json::json!({"type": "ephemeral"});
}
}
/// Convert one core [`Message`](luxe_core::message::Message) into one or more OpenAI wire
/// messages, appending them to `out`.
///
/// A `Tool` message fans out to one `{role:"tool", tool_call_id, content}` per result block
/// (OpenAI requires the id to pair a result with its call). Assistant tool calls become the
/// `tool_calls` array; when the assistant only called tools its `content` is `null`.
///
/// `copilot` replays the reasoning Copilot handed back with the message (`reasoning_text` and
/// `reasoning_opaque`), which no other chat-completions server knows.
pub(super) fn push_wire_messages(
msg: &luxe_core::message::Message,
out: &mut Vec<serde_json::Value>,
tool_names: &HashMap<&str, &str>,
copilot: bool,
) {
use luxe_core::message::Role;
if msg.role == Role::Tool {
push_tool_messages(msg, out, None, tool_names);
return;
}
let mut text_parts: Vec<String> = Vec::new();
let mut tool_calls = Vec::new();
let mut image_blocks: Vec<(String, String)> = Vec::new(); // (mime, base64_data)
let mut reasoning: Option<(String, String)> = None; // (text, opaque)
for block in &msg.content {
match block {
ContentBlock::Text(text) => {
text_parts.push(text.clone());
}
// Copilot's own reasoning goes back in its own fields, the way it came, so the model
// keeps the thread of a multi-step call (Gemini's thought signatures ride in
// `reasoning_opaque`)
ContentBlock::Thinking { text, opaque: Some(opaque), .. } if copilot => {
let (texts, opaques) = reasoning.get_or_insert_with(Default::default);
texts.push_str(text);
opaques.push_str(opaque);
}
// Anything else is transient on the chat-completions path: replaying it as assistant
// text wastes tokens, breaks prefix caching, and isn't the shape this API expects.
// Reasoning-capable models regenerate their own reasoning server-side.
ContentBlock::Thinking { .. } | ContentBlock::RedactedThinking { .. } => {}
ContentBlock::ToolCall { id, name, arguments } => {
tool_calls.push(serde_json::json!({
"id": id,
"type": "function",
"function": { "name": name, "arguments": arguments.to_string() }
}));
}
ContentBlock::ToolResult { content, .. } => {
// A tool result nested inside a non-tool message has no run to be carried
// alongside, so its images stay a marker.
let text = tool_result_text(content, false);
if !text.is_empty() {
text_parts.push(text);
}
}
ContentBlock::Image { data, mime, .. } => {
image_blocks.push((mime.clone(), data.clone()));
}
}
}
let mut m = serde_json::json!({ "role": msg.role });
if !image_blocks.is_empty() {
// Image content: use array form with mixed text and image_url objects.
let mut arr: Vec<serde_json::Value> = text_parts
.into_iter()
.map(|t| serde_json::json!({ "type": "text", "text": t }))
.collect();
for (mime, data) in &image_blocks {
arr.push(serde_json::json!({
"type": "image_url",
"image_url": { "url": data_url(mime, data) }
}));
}
m["content"] = serde_json::Value::Array(arr);
if !tool_calls.is_empty() {
m["tool_calls"] = serde_json::Value::Array(tool_calls);
}
} else if tool_calls.is_empty() {
// No tool calls: use string content.
m["content"] = serde_json::Value::String(text_parts.join("\n"));
} else {
// Tool calls present: use string content if there's text, null otherwise.
let text = text_parts.join("\n");
m["content"] =
if text.is_empty() { serde_json::Value::Null } else { serde_json::Value::String(text) };
m["tool_calls"] = serde_json::Value::Array(tool_calls);
}
if let Some((text, opaque)) = reasoning {
if !text.is_empty() {
m["reasoning_text"] = serde_json::Value::String(text);
}
m["reasoning_opaque"] = serde_json::Value::String(opaque);
}
out.push(m);
}
/// The headers this endpoint wants beyond `Content-Type`, gathered in one place so the call site
/// stays one line however many providers grow one.
pub(super) fn request_headers(
compat: &CompatFlags,
req: &CompletionRequest,
) -> Vec<(&'static str, &'static str)> {
let mut headers = copilot_request_headers(compat, req);
if compat.openrouter_headers {
headers.extend([("HTTP-Referer", LUXE_HOME), ("X-Title", "Luxe")]);
}
headers
}
/// Where OpenRouter's attribution header points a reader who wants to know what called it.
pub(super) const LUXE_HOME: &str = "https://luxe.dev";
/// GitHub Copilot's per-request headers, empty for every other provider.
///
/// Whichever wire API Copilot is spoken in, so the Responses adapter sends them too; the headers
/// themselves are [`crate::copilot::turn_headers`].
pub(crate) fn copilot_request_headers(
compat: &CompatFlags,
req: &CompletionRequest,
) -> Vec<(&'static str, &'static str)> {
match compat.copilot_headers {
true => crate::copilot::turn_headers(req),
false => Vec::new(),
}
}
/// Which tool produced each result, read off the calls in the same request.
///
/// A result carries the id of the call it answers, never the tool's name — so for an endpoint that
/// wants `name` on a tool message, the name has to come from the assistant turn that made the call.
/// Safe to read from the outgoing transcript: a call and its result are one unit that is never
/// separated (`tool_pairing::repair` guarantees it on this copy), so the call is present whenever
/// its result is.
fn tool_names_by_call(messages: &[luxe_core::message::Message]) -> HashMap<&str, &str> {
messages
.iter()
.flat_map(|message| &message.content)
.filter_map(|block| match block {
ContentBlock::ToolCall { id, name, .. } => Some((id.as_str(), name.as_str())),
_ => None,
})
.collect()
}
/// Emit one `tool` message per result block, draining any images into `images` when given.
///
/// `images` is `Some` only when the model declares it takes them; a text-only endpoint is billed
/// for every base64 byte it is sent and the strict ones answer 400, so a model that cannot see is
/// never handed pixels.
fn push_tool_messages(
msg: &luxe_core::message::Message,
out: &mut Vec<serde_json::Value>,
mut images: Option<&mut Vec<(String, String)>>,
tool_names: &HashMap<&str, &str>,
) {
let mut emitted = false;
for block in &msg.content {
if let ContentBlock::ToolResult { call_id, content, .. } = block {
if let Some(collected) = images.as_deref_mut() {
collected.extend(
luxe_core::ToolOutput::images(content)
.map(|(mime, data)| (mime.to_string(), data.to_string())),
);
}
let mut message = serde_json::json!({
"role": "tool",
"tool_call_id": call_id,
"content": tool_result_text(content, images.is_some()),
});
// Only where the endpoint asks for it, and only when the call that produced this result
// is in the same request — a name guessed from anywhere else would be worse than none.
if let Some(name) = tool_names.get(call_id.as_str()) {
message["name"] = serde_json::Value::String((*name).to_string());
}
out.push(message);
emitted = true;
}
}
// Defensive: a Tool message with no ToolResult blocks still needs a turn.
if !emitted {
out.push(serde_json::json!({ "role": "tool", "content": "" }));
}
}
/// The one `user` message carrying every image a run of tool results produced.
///
/// It leads with a line of text on purpose: several OpenAI-compatible servers reject a content
/// array with no text part, and a bare wall of base64 tells the model nothing about where the
/// pixels came from.
fn image_carrier_message(images: &[(String, String)]) -> Option<serde_json::Value> {
if images.is_empty() {
return None;
}
let mut parts = vec![serde_json::json!({
"type": "text",
"text": "Attached image(s) from tool result:",
})];
parts.extend(images.iter().map(|(mime, data)| {
let url = data_url(mime, data);
serde_json::json!({ "type": "image_url", "image_url": { "url": url } })
}));
Some(serde_json::json!({ "role": "user", "content": parts }))
}
/// Join a tool result's outputs into a single text blob for the OpenAI `content` field.
///
/// `carried` says the images are being sent alongside, which changes what the text owes the model:
/// a pointer to something it is about to receive, rather than a marker standing in for something it
/// never will. A result with text of its own needs neither.
fn tool_result_text(content: &[luxe_core::ToolOutput], carried: bool) -> String {
let text = luxe_core::ToolOutput::joined_text(content);
if !text.is_empty() {
return text;
}
let images = luxe_core::ToolOutput::images(content).next().is_some();
match (images, carried) {
(true, true) => "(see attached image)".to_string(),
(true, false) => "[image]".to_string(),
_ => text,
}
}

View File

@@ -0,0 +1,309 @@
//! Chat-completions SSE decoding — `data:` records to [`ProviderEvent`]s.
use luxe_core::provider::{ProviderEvent, StopReason, Usage};
use serde::Deserialize;
use tracing::warn;
/// SSE event from the OpenAI API.
#[derive(Debug, Deserialize)]
pub(super) struct SseEvent {
#[serde(default)]
choices: Option<Vec<SseChoice>>,
#[serde(default)]
usage: Option<SseUsage>,
#[serde(default)]
error: Option<SseError>,
}
/// A choice in an SSE event.
#[derive(Debug, Deserialize)]
struct SseChoice {
#[serde(default)]
index: Option<usize>,
#[serde(default)]
delta: Option<SseDelta>,
#[serde(default)]
finish_reason: Option<String>,
}
/// Delta in a streaming response.
#[derive(Debug, Deserialize, Default)]
struct SseDelta {
#[serde(default)]
role: Option<String>,
#[serde(default)]
content: Option<String>,
/// Reasoning text, DeepSeek/Qwen/LM Studio spelling.
#[serde(default)]
reasoning_content: Option<String>,
/// Reasoning text, OpenRouter/Together spelling.
#[serde(default)]
reasoning: Option<String>,
/// Reasoning text, GitHub Copilot spelling.
#[serde(default)]
reasoning_text: Option<String>,
/// GitHub Copilot's reasoning state, replayed with the message it came on.
#[serde(default)]
reasoning_opaque: Option<String>,
#[serde(default)]
tool_calls: Option<Vec<SseToolCall>>,
}
impl SseDelta {
/// The reasoning fragment in this delta, whichever field the server chose to put it in.
///
/// There is no standard: DeepSeek-lineage servers (and LM Studio proxying them) send
/// `reasoning_content`, OpenRouter and Together send `reasoning`, GitHub Copilot sends
/// `reasoning_text`. All three mean the same thing.
fn reasoning_delta(&self) -> Option<&str> {
self.reasoning_content
.as_deref()
.or(self.reasoning.as_deref())
.or(self.reasoning_text.as_deref())
.filter(|text| !text.is_empty())
}
}
/// A tool call in a streaming response.
#[derive(Debug, Deserialize)]
struct SseToolCall {
#[serde(default)]
index: Option<usize>,
#[serde(default)]
id: Option<String>,
#[serde(default)]
function: Option<SseFunction>,
}
/// A function call in a streaming response.
#[derive(Debug, Deserialize, Default)]
struct SseFunction {
#[serde(default)]
name: Option<String>,
#[serde(default)]
arguments: Option<String>,
}
/// Usage statistics from the API.
#[derive(Debug, Deserialize, Default)]
struct SseUsage {
#[serde(default)]
prompt_tokens: Option<u32>,
#[serde(default)]
completion_tokens: Option<u32>,
#[serde(default)]
total_tokens: Option<u32>,
/// Cached-input breakdown; `prompt_tokens` already includes these.
#[serde(default)]
prompt_tokens_details: Option<TokenDetails>,
/// Reasoning-output breakdown; `completion_tokens` already includes these.
#[serde(default)]
completion_tokens_details: Option<TokenDetails>,
/// Reasoning tokens reported beside the counts rather than inside a breakdown, as GitHub
/// Copilot does.
#[serde(default)]
reasoning_tokens: Option<u32>,
}
/// The `*_tokens_details` sub-object (OpenAI reports cached/reasoning subsets here).
#[derive(Debug, Deserialize, Default)]
struct TokenDetails {
#[serde(default)]
cached_tokens: Option<u32>,
/// Tokens written to the cache, which OpenRouter reports and bills at a premium. Counted
/// inside `prompt_tokens` like the read side, so it needs no adjustment to fit [`Usage`].
#[serde(default)]
cache_write_tokens: Option<u32>,
#[serde(default)]
reasoning_tokens: Option<u32>,
}
/// Error from the API.
#[derive(Debug, Deserialize)]
struct SseError {
message: String,
#[serde(default)]
r#type: Option<String>,
#[serde(default)]
code: Option<serde_json::Value>,
}
/// Translate one decoded chat-completions chunk into `ProviderEvent`s.
pub(super) fn push_sse_events(event: &SseEvent, events: &mut Vec<ProviderEvent>) {
if let Some(error) = &event.error {
let (named, code) = (error.r#type.as_deref(), error.code.as_ref());
let kind = crate::http::kind_of_frame(named, code, &error.message);
events.push(ProviderEvent::Error { message: error.message.clone(), kind });
return;
}
// Emit usage BEFORE the choices' `Done` (the engine stops the stream on `Done`, so a trailing
// usage would be missed). Also covers usage-only final chunks with no choices.
if let Some(usage) = &event.usage {
events.push(usage_event(usage));
}
for choice in event.choices.iter().flatten() {
let index = choice.index.unwrap_or(0);
if let Some(delta) = &choice.delta {
push_delta_events(index, delta, events);
}
if let Some(finish_reason) = &choice.finish_reason {
push_finish_events(index, finish_reason, events);
}
}
}
/// One usage chunk as the normalized [`Usage`] the engine counts.
fn usage_event(usage: &SseUsage) -> ProviderEvent {
let prompt_details = usage.prompt_tokens_details.as_ref();
let cache_read = prompt_details.and_then(|d| d.cached_tokens).unwrap_or(0);
let cache_write = prompt_details.and_then(|d| d.cache_write_tokens).unwrap_or(0);
let reasoning = usage
.completion_tokens_details
.as_ref()
.and_then(|d| d.reasoning_tokens)
.or(usage.reasoning_tokens)
.unwrap_or(0);
let prompt = usage.prompt_tokens.unwrap_or(0);
let total = usage.total_tokens.unwrap_or(0);
// Reasoning is output, and inside `completion_tokens` by convention. Copilot's Gemini
// leaves it out and puts it in the total instead (19 prompt + 1 completion of a total of
// 1,460, with 1,440 reasoning), which priced a turn's output at a fraction of what it was.
// Only a total that holds the reasoning on top of both counts says so
let mut completion = usage.completion_tokens.unwrap_or(0);
if reasoning > 0
&& u64::from(total) >= u64::from(prompt) + u64::from(completion) + u64::from(reasoning)
{
completion += reasoning;
}
ProviderEvent::Usage(Usage {
prompt_tokens: prompt,
completion_tokens: completion,
total_tokens: total,
cache_read_tokens: cache_read,
cache_write_tokens: cache_write,
reasoning_tokens: reasoning,
cache_write_1h_tokens: 0,
})
}
fn push_delta_events(index: usize, delta: &SseDelta, events: &mut Vec<ProviderEvent>) {
// Role delta (usually first event).
if delta.role.is_some() {
events.push(ProviderEvent::TextStart { index });
}
// Reasoning delta, before the content delta of the same chunk: a server that packs
// both into one chunk produced the reasoning first.
if let Some(reasoning) = delta.reasoning_delta() {
events.push(ProviderEvent::ThinkingDelta { index, delta: reasoning.to_string() });
}
if let Some(opaque) = delta.reasoning_opaque.as_ref().filter(|opaque| !opaque.is_empty()) {
events.push(ProviderEvent::ReasoningOpaque { index, opaque: opaque.clone() });
}
if let Some(content) = &delta.content {
events.push(ProviderEvent::TextDelta { index, delta: content.clone() });
}
for call in delta.tool_calls.iter().flatten() {
push_tool_call_events(call, events);
}
}
fn push_tool_call_events(call: &SseToolCall, events: &mut Vec<ProviderEvent>) {
let index = call.index.unwrap_or(0);
if let Some(id) = &call.id {
events.push(ProviderEvent::ToolCallStart { index, id: id.clone(), name: String::new() });
}
let Some(function) = &call.function else { return };
// The name arrives on the same chunk as the id, so it patches the `ToolCallStart` just
// pushed rather than emitting an event of its own.
if let Some(name) = &function.name {
if let Some(ProviderEvent::ToolCallStart { name: slot, .. }) = events.last_mut() {
*slot = name.clone();
}
}
if let Some(arguments) = &function.arguments {
events.push(ProviderEvent::ToolCallDelta { index, json_delta: arguments.clone() });
}
}
/// A tool-call finish ends the turn too, and says why. Emitting only `ToolCallEnd` left the
/// decoder with nothing deferred, so a body that then ended without `[DONE]` terminated the turn
/// with no `Done` at all — and every tool-call turn that *did* get one reported `EndTurn`, while
/// the Anthropic and Responses adapters reported `ToolCall` for the identical model.
fn push_finish_events(index: usize, finish_reason: &str, events: &mut Vec<ProviderEvent>) {
let reason = match finish_reason {
"tool_calls" => {
events.push(ProviderEvent::ToolCallEnd { index });
StopReason::ToolCall
}
other => {
events.push(ProviderEvent::TextEnd { index });
match other {
"stop" => StopReason::EndTurn,
"length" => StopReason::Length,
"content_filter" => StopReason::ContentFilter,
_ => StopReason::Other(finish_reason.to_string()),
}
}
};
events.push(ProviderEvent::Done { reason });
}
/// Record-at-a-time decoder for the chat-completions SSE shape.
///
/// `Done` is held back until the `[DONE]` sentinel (or the end of the body) because
/// OpenAI-compatible servers report `include_usage` in a chunk *after* the `finish_reason` chunk,
/// and the turn loop stops on the first `Done` — emitting it eagerly loses the turn's usage.
#[derive(Default)]
pub(crate) struct CompatDecoder {
deferred_done: Option<StopReason>,
done_emitted: bool,
}
impl CompatDecoder {
fn flush_done(&mut self, out: &mut Vec<ProviderEvent>) {
if self.done_emitted {
return;
}
self.done_emitted = true;
out.push(ProviderEvent::Done {
reason: self.deferred_done.take().unwrap_or(StopReason::EndTurn),
});
}
}
impl crate::sse::SseDecoder for CompatDecoder {
fn record(&mut self, record: &str, out: &mut Vec<ProviderEvent>) {
for line in record.lines() {
let Some(data) = line.trim().strip_prefix("data:").map(str::trim) else { continue };
if data == "[DONE]" {
return self.flush_done(out);
}
match serde_json::from_str::<SseEvent>(data) {
Ok(event) => {
let mut decoded = Vec::new();
push_sse_events(&event, &mut decoded);
for event in decoded {
match event {
ProviderEvent::Done { reason } => self.deferred_done = Some(reason),
other => out.push(other),
}
}
}
Err(error) => warn!(error = %error, data = %data, "failed to parse SSE event"),
}
}
}
fn finish(&mut self, out: &mut Vec<ProviderEvent>) {
// A body that ended without `[DONE]` still finished the turn — unconditionally, because
// the caller cannot tell "the stream ended" from "the stream stopped" and a turn that
// never terminates leaves the engine with no stop reason to report. A transport failure
// does not come through here: it is a terminal `Error` event instead.
self.flush_done(out);
}
}

View File

@@ -0,0 +1,18 @@
#![allow(clippy::unwrap_used, clippy::collapsible_match)]
use super::{
request::{push_wire_messages, LUXE_HOME},
sse::{push_sse_events, SseEvent},
*,
};
use crate::sse::SseDecoder;
use luxe_core::message::{ContentBlock, Message, Role, ToolOutput};
use luxe_core::provider::{ModelInfo, ModelRef, StopReason, ThinkingLevel};
use std::collections::HashMap;
mod request;
mod stream;
mod wire;
use request::*;
use stream::*;

View File

@@ -0,0 +1,367 @@
//! Request — thinking, caching, sampling and templates in the body.
use super::*;
pub(super) fn thinking_request(model: ModelInfo, thinking: ThinkingLevel) -> CompletionRequest {
CompletionRequest {
model,
messages: vec![Message::user("Hello")],
system: None,
tools: vec![],
thinking,
max_tokens: Some(4096),
..Default::default()
}
}
pub(super) fn provider(compat: CompatFlags) -> OpenaiCompatProvider {
OpenaiCompatProvider::new(ProviderConfig::default(), compat)
}
/// Copilot's chat completions carries reasoning in fields of its own. Its text is shown, its
/// opaque state is kept, and both go back with the message they came on — to Copilot only.
/// The records are copied from live Gemini and Kimi streams.
#[test]
fn copilots_reasoning_is_read_kept_and_replayed() {
let events = decode_records(&[
r#"data: {"choices":[{"index":0,"delta":{"role":"assistant","reasoning_text":"Checking divisors"}}]}"#,
r#"data: {"choices":[{"index":0,"delta":{"reasoning_opaque":"CpcBAb4+9vs"}}]}"#,
r#"data: {"choices":[{"index":0,"delta":{"content":"No."},"finish_reason":"stop"}]}"#,
]);
assert!(events.iter().any(|event| matches!(
event,
ProviderEvent::ThinkingDelta { delta, .. } if delta == "Checking divisors"
)));
assert!(events.iter().any(|event| matches!(
event,
ProviderEvent::ReasoningOpaque { opaque, .. } if opaque == "CpcBAb4+9vs"
)));
let replayed = Message {
role: luxe_core::message::Role::Assistant,
content: vec![
ContentBlock::Thinking {
text: "Checking divisors".into(),
signature: None,
id: None,
encrypted: None,
opaque: Some("CpcBAb4+9vs".into()),
},
ContentBlock::ToolCall {
id: "call_1".into(),
name: "read".into(),
arguments: serde_json::json!({}),
},
],
};
let mut copilot = Vec::new();
push_wire_messages(&replayed, &mut copilot, &HashMap::new(), true);
assert_eq!(copilot[0]["reasoning_opaque"], "CpcBAb4+9vs");
assert_eq!(copilot[0]["reasoning_text"], "Checking divisors");
let mut elsewhere = Vec::new();
push_wire_messages(&replayed, &mut elsewhere, &HashMap::new(), false);
assert!(elsewhere[0].get("reasoning_opaque").is_none(), "{}", elsewhere[0]);
assert!(elsewhere[0].get("reasoning_text").is_none());
}
/// Reasoning is output. Copilot reports it beside the counts, and for Gemini leaves it out of
/// `completion_tokens` while the total holds it; for Kimi it is inside. Both live usage blocks.
#[test]
fn copilots_reasoning_tokens_count_as_output_once() {
let usage_of = |record: &str| {
decode_records(&[record])
.into_iter()
.find_map(|event| match event {
ProviderEvent::Usage(usage) => Some(usage),
_ => None,
})
.expect("a usage event")
};
let gemini = usage_of(
r#"data: {"choices":[],"usage":{"completion_tokens":1,"prompt_tokens":19,"prompt_tokens_details":{"cached_tokens":0},"total_tokens":1460,"reasoning_tokens":1440}}"#,
);
assert_eq!((gemini.completion_tokens, gemini.reasoning_tokens), (1441, 1440));
let kimi = usage_of(
r#"data: {"choices":[],"usage":{"completion_tokens":1500,"completion_tokens_details":{},"prompt_tokens":103,"prompt_tokens_details":{"cached_tokens":0},"total_tokens":1603,"reasoning_tokens":1500}}"#,
);
assert_eq!((kimi.completion_tokens, kimi.reasoning_tokens), (1500, 1500));
}
#[test]
fn stream_options_requests_usage_when_supported() {
let req = thinking_request(ModelInfo::default(), ThinkingLevel::Off);
// Default compat has usage-in-streaming on → the request opts into streamed usage.
let on = provider(CompatFlags::default()).build_request_body(&req);
assert_eq!(on["stream_options"]["include_usage"], true);
// Explicit opt-out omits the field entirely (for strict servers).
let off_flags = CompatFlags { supports_usage_in_streaming: false, ..Default::default() };
let off = provider(off_flags).build_request_body(&req);
assert!(off.get("stream_options").is_none());
}
#[test]
fn openai_effort_uses_model_specific_values_and_ultra_alias() {
let model = ModelInfo {
r#ref: ModelRef::new("openai", "gpt-5.6-sol"),
reasoning: true,
thinking_level_map: HashMap::from([
("minimal".to_string(), Some("low".to_string())),
("xhigh".to_string(), Some("xhigh".to_string())),
("max".to_string(), Some("max".to_string())),
]),
..Default::default()
};
let compat = CompatFlags {
supports_reasoning_effort: true,
thinking_format: Some("openai".to_string()),
..Default::default()
};
let provider = provider(compat);
let minimal =
provider.build_request_body(&thinking_request(model.clone(), ThinkingLevel::Minimal));
let ultra = provider.build_request_body(&thinking_request(model.clone(), ThinkingLevel::Ultra));
let off = provider.build_request_body(&thinking_request(model, ThinkingLevel::Off));
assert_eq!(minimal["reasoning_effort"], "low");
assert_eq!(ultra["reasoning_effort"], "max");
assert_eq!(off["reasoning_effort"], "none");
}
/// A models.dev entry for OpenRouter, with the reasoning dials it declares.
pub(super) fn openrouter_model(
id: &str,
controls: luxe_core::provider::ThinkingControls,
) -> ModelInfo {
ModelInfo {
r#ref: ModelRef::new("openrouter", id),
reasoning: true,
thinking_controls: controls,
thinking_level_map: HashMap::from([
("low".to_string(), Some("low".to_string())),
("medium".to_string(), Some("medium".to_string())),
("high".to_string(), Some("high".to_string())),
]),
..Default::default()
}
}
/// The reported failure: OpenRouter answers 400 "Reasoning is mandatory for this endpoint and
/// cannot be disabled" to `effort: "none"` on roughly a fifth of its catalog — grok-4.x,
/// gemini-3.x, the thinking Qwens, deepseek-r1 — and off is the level a session starts on, so
/// every turn on those models failed. Asking for nothing is the only spelling they accept.
#[test]
fn openrouter_asks_a_mandatory_reasoning_endpoint_for_nothing_rather_than_for_none() {
let provider = provider(CompatFlags {
supports_reasoning_effort: true,
thinking_format: Some("openrouter".to_string()),
..Default::default()
});
let toggleable = luxe_core::provider::ThinkingControls {
effort: true,
can_disable: true,
..Default::default()
};
let mandatory = luxe_core::provider::ThinkingControls { effort: true, ..Default::default() };
let off_where_allowed = provider.build_request_body(&thinking_request(
openrouter_model("anthropic/claude-sonnet-5", toggleable),
ThinkingLevel::Off,
));
let off_where_mandatory = provider.build_request_body(&thinking_request(
openrouter_model("x-ai/grok-4.6", mandatory),
ThinkingLevel::Off,
));
let on_where_mandatory = provider.build_request_body(&thinking_request(
openrouter_model("x-ai/grok-4.6", mandatory),
ThinkingLevel::High,
));
assert_eq!(off_where_allowed["reasoning"]["effort"], "none");
assert!(
off_where_mandatory.get("reasoning").is_none(),
"a mandatory endpoint 400s on every way of asking it to stop: {off_where_mandatory}"
);
assert_eq!(on_where_mandatory["reasoning"]["effort"], "high");
}
/// OpenRouter does not cache Claude implicitly, so without this an agentic session re-reads its
/// whole transcript at full price every turn. One field, and only for the gateway that reads it.
#[test]
fn only_the_openrouter_format_asks_for_prompt_caching() {
let req = thinking_request(ModelInfo::default(), ThinkingLevel::Off);
let asked = provider(CompatFlags {
cache_control_format: Some("openrouter".to_string()),
..Default::default()
})
.build_request_body(&req);
let anthropics_own = provider(CompatFlags {
cache_control_format: Some("anthropic".to_string()),
..Default::default()
})
.build_request_body(&req);
let plain = provider(CompatFlags::default()).build_request_body(&req);
assert_eq!(asked["cache_control"]["type"], "ephemeral");
assert!(
anthropics_own.get("cache_control").is_none(),
"per-block markers belong to the Messages adapter, not this one"
);
assert!(plain.get("cache_control").is_none());
// A prompt nothing will read back is not worth the write premium, whatever the gateway.
let mut one_off = thinking_request(ModelInfo::default(), ThinkingLevel::Off);
one_off.reuse = luxe_core::provider::PromptReuse::OneOff;
let summarizing = provider(CompatFlags {
cache_control_format: Some("openrouter".to_string()),
..Default::default()
})
.build_request_body(&one_off);
assert!(summarizing.get("cache_control").is_none(), "{summarizing}");
}
/// The headers a request carries beyond `Content-Type` are opt-in per provider, and one
/// provider's must never ride along on another's.
#[test]
fn attribution_headers_go_only_where_they_were_asked_for() {
let req = thinking_request(ModelInfo::default(), ThinkingLevel::Off);
let named =
request_headers(&CompatFlags { openrouter_headers: true, ..Default::default() }, &req);
assert_eq!(named, vec![("HTTP-Referer", LUXE_HOME), ("X-Title", "Luxe")]);
assert!(request_headers(&CompatFlags::default(), &req).is_empty());
assert!(
!request_headers(&CompatFlags { copilot_headers: true, ..Default::default() }, &req)
.iter()
.any(|(name, _)| *name == "X-Title"),
"Copilot has no use for OpenRouter's attribution"
);
}
/// Cache writes are billed at a premium and counted inside `prompt_tokens`, so reporting them
/// as zero understates a turn's cost. OpenRouter sends them; this used to drop them.
#[test]
fn a_cache_write_is_read_off_the_usage_chunk_rather_than_assumed_absent() {
let events = decode_records(&[
r#"data: {"choices":[],"usage":{"prompt_tokens":9731,"completion_tokens":49,"total_tokens":9780,"prompt_tokens_details":{"cached_tokens":0,"cache_write_tokens":9729},"completion_tokens_details":{"reasoning_tokens":7}}}"#,
"data: [DONE]",
]);
let usage = events
.iter()
.find_map(|event| match event {
ProviderEvent::Usage(usage) => Some(usage),
_ => None,
})
.expect("usage decoded");
assert_eq!(usage.cache_write_tokens, 9729);
assert_eq!(usage.cache_read_tokens, 0);
assert_eq!(usage.reasoning_tokens, 7);
assert_eq!(usage.prompt_tokens, 9731, "writes are counted inside the prompt, not beside it");
}
#[test]
fn qwen_formats_use_boolean_thinking_after_level_clamping() {
let model = ModelInfo {
r#ref: ModelRef::new("dashscope", "qwen3.7-max-2026-06-08"),
reasoning: true,
thinking_level_map: HashMap::from([
("off".to_string(), Some("off".to_string())),
("minimal".to_string(), None),
("low".to_string(), None),
("medium".to_string(), None),
("high".to_string(), Some("on".to_string())),
("xhigh".to_string(), Some("on".to_string())),
]),
..Default::default()
};
let qwen =
provider(CompatFlags { thinking_format: Some("qwen".to_string()), ..Default::default() });
let local = provider(CompatFlags {
thinking_format: Some("qwen-chat-template".to_string()),
..Default::default()
});
let clamped = qwen.build_request_body(&thinking_request(model.clone(), ThinkingLevel::Low));
let off = qwen.build_request_body(&thinking_request(model.clone(), ThinkingLevel::Off));
let local_high = local.build_request_body(&thinking_request(model, ThinkingLevel::High));
assert_eq!(clamped["enable_thinking"], true);
assert_eq!(off["enable_thinking"], false);
assert_eq!(local_high["chat_template_kwargs"]["enable_thinking"], true);
assert_eq!(local_high["chat_template_kwargs"]["preserve_thinking"], true);
}
/// A template's thinking vocabulary is the template's, not Luxe's: Qwen3.8 takes a
/// `reasoning_effort` argument and can be told *not* to preserve thinking, neither of which
/// the fixed two-key object could express.
#[test]
fn a_configured_chat_template_describes_its_own_arguments() {
let model = ModelInfo {
r#ref: ModelRef::new("llama-server", "qwen3.8-27b"),
reasoning: true,
thinking_level_map: HashMap::from([
("off".to_string(), Some("none".to_string())),
("high".to_string(), Some("high".to_string())),
]),
..Default::default()
};
let configured = provider(CompatFlags {
// Pi's spelling of the format, so an entry can be carried across unchanged.
thinking_format: Some("chat-template".to_string()),
chat_template_kwargs: match serde_json::json!({
"enable_thinking": { "$var": "thinking.enabled" },
"preserve_thinking": false,
"reasoning_effort": { "$var": "thinking.level", "omit_when_off": true },
}) {
serde_json::Value::Object(map) => map,
_ => unreachable!("fixture is an object"),
},
..Default::default()
});
let high = configured.build_request_body(&thinking_request(model.clone(), ThinkingLevel::High));
assert_eq!(high["chat_template_kwargs"]["enable_thinking"], true);
assert_eq!(high["chat_template_kwargs"]["preserve_thinking"], false);
assert_eq!(high["chat_template_kwargs"]["reasoning_effort"], "high");
let off = configured.build_request_body(&thinking_request(model, ThinkingLevel::Off));
assert_eq!(off["chat_template_kwargs"]["enable_thinking"], false);
assert!(
off["chat_template_kwargs"].get("reasoning_effort").is_none(),
"an effort argument is meaningless with thinking off"
);
}
/// The acceptance case from the spec: a model carrying Qwen's thinking-mode recipe puts all
/// seven keys on the wire, and each one beats the field the adapter would otherwise have sent.
#[test]
fn a_models_sampling_recipe_reaches_the_body_and_outranks_the_adapter() {
let recipe = serde_json::json!({
"temperature": 1.0, "top_p": 0.95, "top_k": 20, "min_p": 0.0,
"presence_penalty": 0.0, "frequency_penalty": 0.0, "repeat_penalty": 1.0,
});
let model = ModelInfo {
r#ref: ModelRef::new("lmstudio", "qwen3.8-27b"),
reasoning: true,
sampling_params: match recipe.clone() {
serde_json::Value::Object(map) => map,
_ => unreachable!("fixture is an object"),
},
thinking_level_map: HashMap::from([("off".to_string(), Some("none".to_string()))]),
..Default::default()
};
let compat = CompatFlags {
supports_reasoning_effort: true,
thinking_format: Some("openai".to_string()),
..Default::default()
};
let body = provider(compat).build_request_body(&thinking_request(model, ThinkingLevel::Off));
for (key, value) in recipe.as_object().expect("fixture is an object") {
assert_eq!(&body[key.as_str()], value, "{key} must reach the body verbatim");
}
// Nothing else about the request moved.
assert_eq!(body["model"], "qwen3.8-27b");
assert_eq!(body["stream"], true);
assert_eq!(body["reasoning_effort"], "none");
assert_eq!(body["max_tokens"], 4096);
}

View File

@@ -0,0 +1,184 @@
//! Stream — copilot headers, termination and reasoning deltas.
use super::*;
/// Drives the decoder the way the live reader does: one record at a time, in arrival order.
pub(super) fn decode_records(records: &[&str]) -> Vec<ProviderEvent> {
let mut decoder = CompatDecoder::default();
let mut events = Vec::new();
for record in records {
decoder.record(record, &mut events);
}
decoder.finish(&mut events);
events
}
pub(super) fn request_with(messages: Vec<Message>) -> CompletionRequest {
CompletionRequest {
model: luxe_core::provider::ModelInfo::default(),
messages,
system: None,
tools: vec![],
thinking: ThinkingLevel::Off,
max_tokens: None,
..Default::default()
}
}
/// Copilot's endpoint expects to be told whether a request is the person asking or the agent
/// continuing. Getting it backwards is invisible locally and shows up as throttling.
#[test]
fn copilot_headers_report_who_initiated_the_turn() {
let compat = CompatFlags { copilot_headers: true, ..CompatFlags::default() };
let asked = request_with(vec![Message::user("hi")]);
let headers = copilot_request_headers(&compat, &asked);
assert!(headers.contains(&("X-Initiator", "user")), "{headers:?}");
assert!(headers.contains(&("Openai-Intent", "conversation-edits")));
// A tool result means the agent is continuing on its own.
let continuing =
request_with(vec![Message::user("hi"), Message::tool_result("call-1", "output", false)]);
let headers = copilot_request_headers(&compat, &continuing);
assert!(headers.contains(&("X-Initiator", "agent")), "{headers:?}");
// So does an assistant turn being extended.
let assistant = request_with(vec![Message::assistant("thinking…")]);
assert!(copilot_request_headers(&compat, &assistant).contains(&("X-Initiator", "agent")));
}
#[test]
fn copilot_flags_a_turn_that_carries_an_image() {
let compat = CompatFlags { copilot_headers: true, ..CompatFlags::default() };
let with_image = request_with(vec![Message {
role: luxe_core::message::Role::User,
content: vec![ContentBlock::Image {
data: "…".into(),
mime: "image/png".into(),
name: None,
}],
}]);
assert!(
copilot_request_headers(&compat, &with_image).contains(&("Copilot-Vision-Request", "true"))
);
let text_only = request_with(vec![Message::user("hi")]);
assert!(!copilot_request_headers(&compat, &text_only)
.iter()
.any(|(name, _)| *name == "Copilot-Vision-Request"));
}
/// Every other provider must see none of this.
#[test]
fn copilot_headers_are_absent_for_everyone_else() {
let headers =
copilot_request_headers(&CompatFlags::default(), &request_with(vec![Message::user("hi")]));
assert!(headers.is_empty(), "{headers:?}");
}
/// `include_usage` puts the token counts in a chunk *after* `finish_reason`, and the turn loop
/// stops on the first `Done` — so `Done` has to wait for `[DONE]`.
#[test]
fn trailing_usage_still_arrives_before_done() {
let events = decode_records(&[
r#"data: {"choices":[{"index":0,"delta":{"content":"hi"}}]}"#,
r#"data: {"choices":[{"index":0,"finish_reason":"stop"}]}"#,
r#"data: {"choices":[],"usage":{"prompt_tokens":100,"completion_tokens":5,"total_tokens":105}}"#,
"data: [DONE]",
]);
let done = events.iter().position(|e| matches!(e, ProviderEvent::Done { .. })).unwrap();
let usage = events.iter().position(|e| matches!(e, ProviderEvent::Usage(_))).unwrap();
assert!(usage < done, "usage must precede Done so the engine processes it: {events:?}");
assert_eq!(
events.iter().filter(|e| matches!(e, ProviderEvent::Done { .. })).count(),
1,
"exactly one Done: {events:?}"
);
}
/// A body that ends without the `[DONE]` sentinel still has to terminate the turn.
#[test]
fn a_body_without_the_done_sentinel_still_terminates() {
let events = decode_records(&[
r#"data: {"choices":[{"index":0,"delta":{"content":"hi"}}]}"#,
r#"data: {"choices":[{"index":0,"finish_reason":"length"}]}"#,
]);
assert!(
matches!(events.last(), Some(ProviderEvent::Done { reason: StopReason::Length })),
"{events:?}"
);
}
/// The reported failure, in the one shape that produced it: a **tool-call** turn whose body
/// ends without `[DONE]`.
///
/// A `tool_calls` finish used to emit `ToolCallEnd` and nothing else, so the decoder had no
/// deferred `Done` to flush and the stream simply stopped. The engine reads its stop reason
/// off that event, so the turn ended reporting *nothing* — and the truncation warning, the
/// only thing that reads the reason, could not fire on the turn that needed it. Every stream
/// terminates now, whatever the body does.
#[test]
fn a_tool_call_turn_terminates_however_its_body_ends() {
let call = r#"data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"c1","type":"function","function":{"name":"read","arguments":"{}"}}]}}]}"#;
let finish = r#"data: {"choices":[{"index":0,"finish_reason":"tool_calls"}]}"#;
for (label, records) in [
("no sentinel", vec![call, finish]),
("with sentinel", vec![call, finish, "data: [DONE]"]),
// OpenRouter repeats the finish chunk to carry usage; one turn is still one `Done`.
("repeated finish", vec![call, finish, finish, "data: [DONE]"]),
] {
let events = decode_records(&records);
let dones: Vec<_> = events
.iter()
.filter_map(|event| match event {
ProviderEvent::Done { reason } => Some(reason.clone()),
_ => None,
})
.collect();
assert_eq!(dones, vec![StopReason::ToolCall], "{label}: {events:?}");
}
}
/// The same model reached three ways must report the same reason. Anthropic Messages and the
/// Responses API both answer `ToolCall`; this adapter answered `EndTurn`, so a front-end
/// reading the stop reason saw the provider, not the turn.
#[test]
fn a_tool_call_finish_reports_a_tool_call_not_an_end_of_turn() {
let events = decode_records(&[
r#"data: {"choices":[{"index":0,"finish_reason":"tool_calls"}]}"#,
"data: [DONE]",
]);
assert!(
matches!(events.last(), Some(ProviderEvent::Done { reason: StopReason::ToolCall })),
"{events:?}"
);
}
/// An empty body is still a finished call — the engine has to be able to stop waiting.
#[test]
fn a_body_with_nothing_in_it_still_terminates() {
let events = decode_records(&[]);
assert!(
matches!(events.as_slice(), [ProviderEvent::Done { reason: StopReason::EndTurn }]),
"{events:?}"
);
}
/// Reasoning has no standard field name on this API; both spellings map to thinking.
#[test]
fn reasoning_deltas_are_decoded_under_either_field_name() {
let deepseek =
decode_records(&[r#"data: {"choices":[{"delta":{"reasoning_content":"pondering"}}]}"#]);
let openrouter =
decode_records(&[r#"data: {"choices":[{"delta":{"reasoning":"pondering"}}]}"#]);
for events in [deepseek, openrouter] {
assert!(
events.iter().any(|event| matches!(
event,
ProviderEvent::ThinkingDelta { delta, .. } if delta == "pondering"
)),
"{events:?}"
);
}
}

View File

@@ -0,0 +1,519 @@
//! Wire — message expansion, SSE events and images.
use super::*;
#[test]
fn tool_message_expands_with_tool_call_id() {
let msg = Message {
role: Role::Tool,
content: vec![
ContentBlock::ToolResult {
call_id: "call_1".into(),
content: vec![ToolOutput::Text("result A".into())],
is_error: false,
},
ContentBlock::ToolResult {
call_id: "call_2".into(),
content: vec![ToolOutput::Text("result B".into())],
is_error: false,
},
],
};
let mut out = Vec::new();
push_wire_messages(&msg, &mut out, &HashMap::new(), false);
// One tool message per result block, each carrying its own tool_call_id.
assert_eq!(out.len(), 2);
assert_eq!(out[0]["role"], "tool");
assert_eq!(out[0]["tool_call_id"], "call_1");
assert_eq!(out[0]["content"], "result A");
assert_eq!(out[1]["tool_call_id"], "call_2");
assert_eq!(out[1]["content"], "result B");
}
#[test]
fn reasoning_blocks_are_not_replayed_as_assistant_text() {
let msg = Message {
role: Role::Assistant,
content: vec![
ContentBlock::Thinking {
text: "secret reasoning".into(),
signature: None,
id: None,
encrypted: None,
opaque: None,
},
ContentBlock::RedactedThinking { data: "ENC==".into() },
ContentBlock::Text("the answer".into()),
],
};
let mut out = Vec::new();
push_wire_messages(&msg, &mut out, &HashMap::new(), false);
assert_eq!(out.len(), 1);
let content = out[0]["content"].as_str().unwrap_or_default();
assert_eq!(content, "the answer", "only the answer text is replayed");
assert!(!content.contains("secret reasoning"), "reasoning is never inlined as text");
assert!(!content.contains("thinking"), "no <thinking> wrapper leaks into the wire message");
}
#[test]
fn assistant_tool_call_only_sends_null_content() {
let msg = Message {
role: Role::Assistant,
content: vec![ContentBlock::ToolCall {
id: "call_1".into(),
name: "echo".into(),
arguments: serde_json::json!({"x": 1}),
}],
};
let mut out = Vec::new();
push_wire_messages(&msg, &mut out, &HashMap::new(), false);
assert_eq!(out.len(), 1);
assert_eq!(out[0]["role"], "assistant");
assert!(out[0]["content"].is_null(), "tool-call-only assistant must send null content");
assert_eq!(out[0]["tool_calls"][0]["id"], "call_1");
assert_eq!(out[0]["tool_calls"][0]["function"]["name"], "echo");
// Arguments are serialized as a JSON string, per the OpenAI schema.
assert!(out[0]["tool_calls"][0]["function"]["arguments"].is_string());
}
#[test]
fn assistant_text_with_tool_call_keeps_text() {
let msg = Message {
role: Role::Assistant,
content: vec![
ContentBlock::Text("let me check".into()),
ContentBlock::ToolCall {
id: "c1".into(),
name: "echo".into(),
arguments: serde_json::json!({}),
},
],
};
let mut out = Vec::new();
push_wire_messages(&msg, &mut out, &HashMap::new(), false);
assert_eq!(out[0]["content"], "let me check");
assert!(out[0]["tool_calls"].is_array());
}
#[test]
fn parse_sse_event_text_delta() {
let sse_json = r#"{"choices":[{"index":0,"delta":{"role":"assistant","content":"Hello"},"finish_reason":null}],"usage":null}"#;
let event: SseEvent = serde_json::from_str(sse_json).unwrap();
let mut events = Vec::new();
push_sse_events(&event, &mut events);
assert_eq!(events.len(), 2); // TextStart + TextDelta
assert!(matches!(&events[0], ProviderEvent::TextStart { index: 0 }));
assert!(matches!(&events[1], ProviderEvent::TextDelta { index: 0, delta } if delta == "Hello"));
}
#[test]
fn parse_sse_event_tool_call() {
let sse_json = r#"{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"read","arguments":"{\"path\":\"test.rs\"}"}}]},"finish_reason":null}],"usage":null}"#;
let event: SseEvent = serde_json::from_str(sse_json).unwrap();
let mut events = Vec::new();
push_sse_events(&event, &mut events);
assert_eq!(events.len(), 2); // ToolCallStart + ToolCallDelta (no ToolCallEnd without finish_reason)
assert!(matches!(&events[0], ProviderEvent::ToolCallStart { id, .. } if id == "call_1"));
assert!(
matches!(&events[1], ProviderEvent::ToolCallDelta { json_delta, .. } if json_delta.contains("test.rs"))
);
}
#[test]
fn parse_sse_event_done() {
let sse_json = r#"{"choices":[{"index":0,"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}}"#;
let event: SseEvent = serde_json::from_str(sse_json).unwrap();
let mut events = Vec::new();
push_sse_events(&event, &mut events);
assert_eq!(events.len(), 3); // Usage + TextEnd + Done (usage precedes Done)
assert!(
matches!(&events[0], ProviderEvent::Usage(u) if u.prompt_tokens == 10 && u.completion_tokens == 5 && u.total_tokens == 15)
);
assert!(matches!(&events[1], ProviderEvent::TextEnd { index: 0 }));
assert!(matches!(&events[2], ProviderEvent::Done { reason: StopReason::EndTurn }));
}
#[test]
fn parse_sse_usage_captures_cache_and_reasoning_details() {
let sse_json = r#"{"choices":[],"usage":{"prompt_tokens":1000,"completion_tokens":200,"total_tokens":1200,"prompt_tokens_details":{"cached_tokens":768},"completion_tokens_details":{"reasoning_tokens":150}}}"#;
let event: SseEvent = serde_json::from_str(sse_json).unwrap();
let mut events = Vec::new();
push_sse_events(&event, &mut events);
let usage = events.iter().find_map(|e| match e {
ProviderEvent::Usage(u) => Some(u),
_ => None,
});
let usage = usage.expect("a Usage event");
assert_eq!(usage.prompt_tokens, 1000); // cache-inclusive
assert_eq!(usage.cache_read_tokens, 768);
assert_eq!(usage.reasoning_tokens, 150);
}
#[test]
fn parse_sse_event_error() {
let sse_json = r#"{"error":{"message":"Rate limit exceeded","type":"rate_limit_exceeded"}}"#;
let event: SseEvent = serde_json::from_str(sse_json).unwrap();
let mut events = Vec::new();
push_sse_events(&event, &mut events);
assert_eq!(events.len(), 1);
assert!(
matches!(&events[0], ProviderEvent::Error { message, .. } if message == "Rate limit exceeded")
);
}
#[test]
fn parse_sse_event_empty_choices() {
let sse_json = r#"{"choices":[]}"#;
let event: SseEvent = serde_json::from_str(sse_json).unwrap();
let mut events = Vec::new();
push_sse_events(&event, &mut events);
assert!(events.is_empty());
}
#[test]
fn parse_multiline_sse_fixture() {
let events = decode_records(&[
r#"data: {"choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}"#,
r#"data: {"choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}"#,
r#"data: {"choices":[{"index":0,"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}}"#,
"data: [DONE]",
]);
assert_eq!(events.len(), 5, "{events:?}");
assert!(matches!(&events[0], ProviderEvent::TextStart { index: 0 }));
assert!(matches!(&events[1], ProviderEvent::TextDelta { index: 0, delta } if delta == "Hello"));
assert!(matches!(&events[2], ProviderEvent::Usage(u) if u.total_tokens == 15));
assert!(matches!(&events[3], ProviderEvent::TextEnd { index: 0 }));
// One terminal `Done`, after the usage: the `[DONE]` sentinel releases the one the
// finish_reason chunk produced instead of adding a second.
assert!(matches!(&events[4], ProviderEvent::Done { reason: StopReason::EndTurn }));
}
/// A vision model that declares it takes images.
pub(super) fn seeing(id: &str) -> ModelInfo {
ModelInfo {
r#ref: ModelRef::new("lmstudio", id),
input: vec![luxe_core::provider::Modality::Text, luxe_core::provider::Modality::Image],
..Default::default()
}
}
/// One tool result carrying pixels, as `read` on an image or `screenshot` produces.
pub(super) fn tool_result_with_image(call_id: &str, text: &str) -> Message {
Message {
role: luxe_core::message::Role::Tool,
content: vec![ContentBlock::ToolResult {
call_id: call_id.into(),
content: vec![
luxe_core::ToolOutput::Text(text.into()),
luxe_core::ToolOutput::Image {
data: "QUJD".into(),
mime: "image/png".into(),
name: Some("quad.png".into()),
},
],
is_error: false,
}],
}
}
pub(super) fn request(model: ModelInfo, messages: Vec<Message>) -> CompletionRequest {
CompletionRequest {
model,
messages,
system: None,
tools: vec![],
thinking: ThinkingLevel::Off,
max_tokens: Some(4096),
..Default::default()
}
}
/// The whole point of the run grouping: this schema has no image content on a `tool` message,
/// so the pixels ride on a following `user` message — and that message may never land between
/// two `tool` messages, which every provider rejects.
#[test]
fn a_tool_produced_image_reaches_a_vision_model_after_its_tool_message() {
let body = provider(CompatFlags::default()).build_request_body(&request(
seeing("qwen3.8-27b"),
vec![Message::user("look at it"), tool_result_with_image("call-1", "quad.png: PNG")],
));
let messages = body["messages"].as_array().expect("messages");
let roles: Vec<&str> = messages.iter().filter_map(|m| m["role"].as_str()).collect();
assert_eq!(roles, ["user", "tool", "user"], "the carrier follows the tool message");
let carrier = messages.last().expect("carrier");
let parts = carrier["content"].as_array().expect("the carrier is a content array");
assert_eq!(
parts[0]["type"], "text",
"a text part leads: some servers reject an array without one"
);
assert_eq!(parts[1]["type"], "image_url");
assert_eq!(parts[1]["image_url"]["url"], "data:image/png;base64,QUJD");
// The tool message keeps its own text and never carries the bytes.
assert_eq!(messages[1]["content"], "quad.png: PNG");
}
/// Sending base64 to a text-only endpoint is a large silent bill and, on a strict server, a
/// 400. The declared modality is the gate, and nothing else.
#[test]
fn a_text_only_model_is_never_sent_the_bytes() {
let body = provider(CompatFlags::default()).build_request_body(&request(
ModelInfo::default(),
vec![Message::user("look at it"), tool_result_with_image("call-1", "quad.png: PNG")],
));
let rendered = body.to_string();
assert!(!rendered.contains("QUJD"), "no base64 anywhere in the body: {rendered}");
assert!(!rendered.contains("image_url"), "and no carrier message: {rendered}");
let roles: Vec<&str> =
body["messages"].as_array().unwrap().iter().filter_map(|m| m["role"].as_str()).collect();
assert_eq!(roles, ["user", "tool"]);
}
/// Luxe commits refusals and results as separate `Role::Tool` messages, and `tool_pairing` can
/// synthesize a third. One carrier for the whole run, after all of them — a carrier per message
/// would interleave a `user` turn between two `tool` turns and 400 the request.
#[test]
fn a_run_of_tool_messages_gets_exactly_one_carrier_after_all_of_them() {
let body = provider(CompatFlags::default()).build_request_body(&request(
seeing("qwen3.8-27b"),
vec![
Message::user("look"),
tool_result_with_image("call-1", "first"),
tool_result_with_image("call-2", "second"),
],
));
let messages = body["messages"].as_array().expect("messages");
let roles: Vec<&str> = messages.iter().filter_map(|m| m["role"].as_str()).collect();
assert_eq!(roles, ["user", "tool", "tool", "user"], "never tool, user, tool");
let parts = messages.last().unwrap()["content"].as_array().expect("array");
let images = parts.iter().filter(|part| part["type"] == "image_url").count();
assert_eq!(images, 2, "both results' pixels ride on the one carrier");
}
/// A result whose only output is an image would otherwise send empty content. It points at
/// what follows rather than shrugging — the model is about to receive it.
#[test]
fn an_image_only_result_points_at_what_is_attached() {
let mut message = tool_result_with_image("call-1", "");
if let ContentBlock::ToolResult { content, .. } = &mut message.content[0] {
content.retain(|output| matches!(output, luxe_core::ToolOutput::Image { .. }));
}
let body = provider(CompatFlags::default())
.build_request_body(&request(seeing("qwen3.8-27b"), vec![message.clone()]));
assert_eq!(body["messages"][0]["content"], "(see attached image)");
// With no way to send it, the marker stays a marker rather than a promise.
let blind = provider(CompatFlags::default())
.build_request_body(&request(ModelInfo::default(), vec![message]));
assert_eq!(blind["messages"][0]["content"], "[image]");
}
/// One endpoint, two builds, two differently shaped requests — from one adapter.
///
/// This is the whole point of per-model compat, and it could not work before: adapters are built
/// once per provider, so a `thinking_format` written on a model reached nothing. The real setup
/// it is for is a single LM Studio port serving two Qwen builds whose chat templates disagree —
/// one handles a `developer` role, the other raises on it — where the provider-level format has
/// to be whatever the model you are actually using wants.
#[test]
fn two_models_on_one_adapter_are_shaped_by_their_own_compat() {
// The endpoint's flags: OpenAI-style effort, and the newer role spelling.
let endpoint = CompatFlags {
supports_reasoning_effort: true,
thinking_format: Some("openai".into()),
supports_developer_role: true,
..Default::default()
};
let adapter = provider(endpoint.clone());
let reasoning_model = |id: &str, compat: Option<CompatFlags>| ModelInfo {
r#ref: ModelRef::new("lmstudio", id),
reasoning: true,
compat,
..Default::default()
};
let ask = |model: ModelInfo| {
adapter.build_request_body(&CompletionRequest {
model,
messages: vec![Message::user("hi")],
system: Some("be brief".into()),
tools: vec![],
thinking: ThinkingLevel::High,
max_tokens: Some(64),
..Default::default()
})
};
// The model with no opinion runs on the endpoint's flags, exactly as before.
let plain = ask(reasoning_model("qwen3.8-27b", None));
assert_eq!(plain["messages"][0]["role"], "developer");
assert_eq!(plain["reasoning_effort"], "high");
assert_eq!(plain["messages"][0]["content"], "be brief");
// The build with its own flags is shaped differently on the same adapter: its template takes
// thinking as a template argument and raises on a `developer` role.
let fable = reasoning_model(
"qwen3.6-27b-fable-fusion",
Some(CompatFlags {
thinking_format: Some("chat_template".into()),
supports_developer_role: false,
..endpoint.clone()
}),
);
let templated = ask(fable);
assert_eq!(templated["messages"][0]["role"], "system");
assert!(templated.get("reasoning_effort").is_none(), "{templated}");
assert_eq!(templated["chat_template_kwargs"]["enable_thinking"], true);
// And the adapter is unchanged by either request — the next model resolves for itself.
let again = ask(reasoning_model("qwen3.8-27b", None));
assert_eq!(again["messages"][0]["role"], "developer");
assert_eq!(again["reasoning_effort"], "high");
}
/// The other two flags a model can carry through the same path, each with a wire consequence.
#[test]
fn a_models_compat_decides_the_usage_opt_in_and_the_max_tokens_field() {
let strict = CompatFlags {
supports_usage_in_streaming: false,
max_tokens_field: "max_completion_tokens".into(),
..Default::default()
};
let adapter = provider(CompatFlags::default());
let model = ModelInfo {
r#ref: ModelRef::new("proxy", "strict"),
compat: Some(strict),
..<_>::default()
};
let body = adapter.build_request_body(&thinking_request(model, ThinkingLevel::Off));
assert!(body.get("stream_options").is_none(), "this model's server rejects the field");
assert_eq!(body["max_completion_tokens"], 4096);
assert!(body.get("max_tokens").is_none());
// The adapter's own flags still answer for every other model on the endpoint.
let sibling =
adapter.build_request_body(&thinking_request(ModelInfo::default(), ThinkingLevel::Off));
assert_eq!(sibling["stream_options"]["include_usage"], true);
assert_eq!(sibling["max_tokens"], 4096);
}
/// A tool result carries the *name* of the tool where the endpoint requires it.
///
/// Not decoration: `openai/harmony` — the format gpt-oss speaks — renders a tool message from
/// its author's name and bails with `Tools should have a name!` when there is none, which a
/// server reports as a 400. OpenAI itself ignores the field, so it stays opt-in.
///
/// The name has to be *found*: a result carries the id of the call it answers and nothing else,
/// so it is read off the assistant turn that made the call, in the same request. That the call
/// is there is guaranteed rather than hoped for — a call and its result are one unit, and the
/// outgoing copy is repaired before it is built.
#[test]
fn a_tool_result_names_its_tool_where_the_endpoint_needs_it() {
let call = |id: &str, name: &str| ContentBlock::ToolCall {
id: id.to_string(),
name: name.to_string(),
arguments: serde_json::json!({}),
};
let result = |id: &str, text: &str| ContentBlock::ToolResult {
call_id: id.to_string(),
content: vec![luxe_core::ToolOutput::Text(text.to_string())],
is_error: false,
};
let conversation = vec![
Message::user("read both files"),
Message {
role: luxe_core::message::Role::Assistant,
content: vec![call("call_1", "read"), call("call_2", "grep")],
},
Message {
role: luxe_core::message::Role::Tool,
// The third answers a call this request does not carry — a repaired half.
content: vec![
result("call_1", "fn main"),
result("call_2", "3 matches"),
result("call_orphan", "?"),
],
},
];
let request = |compat: Option<CompatFlags>| CompletionRequest {
model: ModelInfo { compat, ..Default::default() },
messages: conversation.clone(),
system: None,
tools: vec![],
thinking: ThinkingLevel::Off,
max_tokens: Some(64),
..Default::default()
};
let tool_messages = |body: &serde_json::Value| -> Vec<serde_json::Value> {
body["messages"]
.as_array()
.expect("messages")
.iter()
.filter(|message| message["role"] == "tool")
.cloned()
.collect()
};
// Off by default: OpenAI has no such field, and a strict server rejects what it does not
// model, so nothing is sent that was not asked for.
let plain = provider(CompatFlags::default()).build_request_body(&request(None));
for message in tool_messages(&plain) {
assert!(message.get("name").is_none(), "{message}");
}
// On, from the endpoint's own flags.
let flags = CompatFlags { requires_tool_result_name: true, ..Default::default() };
let named = provider(flags.clone()).build_request_body(&request(None));
let named = tool_messages(&named);
assert_eq!(named[0]["name"], "read", "each result names the call it answers");
assert_eq!(named[0]["tool_call_id"], "call_1");
assert_eq!(named[1]["name"], "grep");
assert_eq!(named[1]["tool_call_id"], "call_2");
assert!(
named[2].get("name").is_none(),
"a result with no call in this request gets no name rather than a guessed one: {}",
named[2]
);
// And on for one model on an endpoint whose other models do not want it — the same path
// every other flag takes.
let per_model = provider(CompatFlags::default()).build_request_body(&request(Some(flags)));
assert_eq!(tool_messages(&per_model)[0]["name"], "read");
}
/// A compat flag that parses, resolves and displays but changes nothing is worse than no flag:
/// it reads back whatever you set, so the setting looks honored while the wire says otherwise.
#[test]
fn the_developer_role_flag_reaches_the_wire() {
let request = CompletionRequest {
model: ModelInfo::default(),
messages: vec![Message::user("hi")],
system: Some("be brief".into()),
tools: vec![],
thinking: ThinkingLevel::Off,
max_tokens: Some(64),
..Default::default()
};
let default = provider(CompatFlags::default()).build_request_body(&request);
assert_eq!(default["messages"][0]["role"], "system", "unset stays the classic spelling");
let flags = CompatFlags { supports_developer_role: true, ..Default::default() };
let opted_in = provider(flags).build_request_body(&request);
assert_eq!(opted_in["messages"][0]["role"], "developer");
assert_eq!(opted_in["messages"][0]["content"], "be brief", "and carries the same prompt");
}

View File

@@ -0,0 +1,67 @@
//! Thinking — how each chat-completions dialect asks for reasoning.
use luxe_core::provider::{CompletionRequest, ThinkingLevel};
use crate::config::CompatFlags;
pub(super) fn apply_thinking_config(
body: &mut serde_json::Value,
req: &CompletionRequest,
compat: &CompatFlags,
) {
if !req.model.reasoning {
return;
}
let level = req.model.effective_thinking_level(req.thinking);
let enabled = level != ThinkingLevel::Off;
let effort = req.model.thinking_level_value(level).unwrap_or_else(|| match level {
ThinkingLevel::Off => "none",
ThinkingLevel::Ultra => "max",
_ => level.as_str(),
});
match compat.thinking_format.as_deref() {
Some("qwen") => body["enable_thinking"] = enabled.into(),
Some("qwen-chat-template" | "chat-template" | "chat_template") => {
if let Some(kwargs) =
crate::chat_template::kwargs(&compat.chat_template_kwargs, enabled, effort)
{
body["chat_template_kwargs"] = kwargs;
}
}
Some("deepseek") => {
body["thinking"] = serde_json::json!({
"type": if enabled { "enabled" } else { "disabled" },
});
if enabled && compat.supports_reasoning_effort {
body["reasoning_effort"] = effort.into();
}
}
Some("openrouter") => {
// A fifth of OpenRouter's catalog answers "Reasoning is mandatory for this endpoint"
// to `effort: "none"` *and* to `enabled: false`, and off is the level a session starts
// on — so those models would 400 on every turn. Omitting the key is the only spelling
// that always works, and the catalog is trusted to say off is reachable before we ask
// for it.
if enabled || req.model.thinking_controls.can_disable {
body["reasoning"] = serde_json::json!({"effort": effort});
}
}
Some("together") => {
body["reasoning"] = serde_json::json!({"enabled": enabled});
if enabled && compat.supports_reasoning_effort {
body["reasoning_effort"] = effort.into();
}
}
Some("openai") => body["reasoning_effort"] = effort.into(),
// `none` only where the model says it can stop thinking: Copilot answers it with a 400
// for every model that cannot, and leaving the key out gets the model's own default
None if compat.supports_reasoning_effort
&& (enabled || req.model.thinking_controls.can_disable) =>
{
body["reasoning_effort"] = effort.into();
}
_ => {}
}
}

View File

@@ -0,0 +1,183 @@
//! OpenAI Responses API adapter.
//!
//! Implements the [`Provider`] trait for the `/v1/responses` endpoint, which newer OpenAI
//! models (e.g. `gpt-5`, `gpt-5-codex`) require. The classic `/v1/chat/completions` endpoint
//! is rejected by those models with "use the v1/responses endpoint instead".
//!
//! # Wire format
//! - Request body: `model`, `stream: true`, `instructions` (system prompt), `max_output_tokens`,
//! `reasoning`, `tools` (flat — not nested under "function"), and `input` (array of items).
//! - SSE events identified by `event: <type>` / `data: <json>` pairs.
use crate::config::ProviderConfig;
use futures::stream::BoxStream as FBoxStream;
use luxe_core::provider::{CompletionRequest, Provider, ProviderError, ProviderEvent};
use tracing::{debug, warn};
use crate::learned::Learned;
mod plan;
mod request;
mod sse;
pub use plan::plan_usage_from_headers;
use request::refuses_in_place_loading;
#[cfg(test)]
pub(crate) use sse::parse_responses_sse;
use sse::ResponsesDecoder;
/// Default OpenAI API base URL.
const DEFAULT_BASE_URL: &str = "https://api.openai.com/v1";
/// Base URL of the ChatGPT-subscription Codex backend.
const CODEX_BASE_URL: &str = "https://chatgpt.com/backend-api";
/// Which flavour of the Responses API an adapter speaks.
///
/// Same wire format and the same SSE decoder either way; the ChatGPT backend differs in its path,
/// in refusing to store a response, and in not accepting an output cap.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResponsesFlavor {
/// `POST {base}/responses` on an API-key endpoint.
Standard,
/// `POST {base}/codex/responses` against a ChatGPT plan.
Codex,
}
/// OpenAI Responses API provider adapter.
#[derive(Debug, Clone)]
pub struct OpenaiResponsesProvider {
/// Provider configuration (API key, base URL, compat flags).
config: ProviderConfig,
/// Standard endpoint or the ChatGPT-subscription Codex backend.
flavor: ResponsesFlavor,
/// Where this call's auth comes from, resolved per request.
auth: std::sync::Arc<dyn crate::auth::AuthSource>,
/// Models whose endpoint refused `additional_tools`, so their deferred tools go back to the
/// list for the rest of the session.
listed_tools: std::sync::Arc<Learned<()>>,
}
impl OpenaiResponsesProvider {
/// Create a new adapter from configuration.
pub fn new(config: ProviderConfig) -> Self {
let auth = crate::auth::StaticAuth::bearer(config.api_key.clone()).into_arc();
Self { config, flavor: ResponsesFlavor::Standard, auth, listed_tools: Default::default() }
}
/// Speak to the ChatGPT-subscription Codex backend instead of an API-key endpoint.
pub fn codex(mut self) -> Self {
self.flavor = ResponsesFlavor::Codex;
self
}
/// Resolve auth from a credential store instead of the fixed config key.
pub fn with_auth(mut self, auth: std::sync::Arc<dyn crate::auth::AuthSource>) -> Self {
self.auth = auth;
self
}
/// Get the effective base URL.
fn effective_base_url(&self) -> &str {
self.config.base_url.as_deref().unwrap_or(match self.flavor {
ResponsesFlavor::Standard => DEFAULT_BASE_URL,
ResponsesFlavor::Codex => CODEX_BASE_URL,
})
}
/// The endpoint one request goes to.
fn request_url(&self, base: &str) -> String {
let base = base.trim_end_matches('/');
match self.flavor {
ResponsesFlavor::Standard => format!("{base}/responses"),
// Tolerate a base URL that already names the path, so a user pointing at a proxy can
// configure either form.
ResponsesFlavor::Codex if base.ends_with("/codex/responses") => base.to_string(),
ResponsesFlavor::Codex if base.ends_with("/codex") => format!("{base}/responses"),
ResponsesFlavor::Codex => format!("{base}/codex/responses"),
}
}
/// Whether this request's deferred tools load in place: unless the flags or a refusal said not
/// to.
fn loads_in_place(&self, req: &CompletionRequest) -> bool {
let compat = req.model.compat.as_ref().unwrap_or(&self.config.compat);
compat.defer_tool_loading && !self.listed_tools.knows(&req.model.r#ref.id)
}
fn remember_listed_tools(&self, req: &CompletionRequest) {
self.listed_tools.remember(&req.model.r#ref.id, ());
}
}
#[async_trait::async_trait]
impl Provider for OpenaiResponsesProvider {
fn name(&self) -> &str {
"openai_responses"
}
async fn stream(
&self,
req: CompletionRequest,
cancel: tokio::sync::watch::Receiver<bool>,
) -> Result<FBoxStream<'static, ProviderEvent>, ProviderError> {
// Auth first: a missing credential is a question for the user, not a request to send.
let auth = self.auth.request_auth().await?;
let base = auth.base_url.clone().unwrap_or_else(|| self.effective_base_url().to_string());
let url = self.request_url(&base);
let mut in_place = self.loads_in_place(&req);
debug!(url = %url, model = %req.model.r#ref.id, "sending responses request");
let mut headers =
vec![("Content-Type", "application/json"), ("Accept", "text/event-stream")];
let compat = req.model.compat.as_ref().unwrap_or(&self.config.compat);
headers.extend(crate::openai_compat::copilot_request_headers(compat, &req));
let response = loop {
let body = self.body_for(&req, in_place);
let request =
crate::http::json_request(crate::http::shared_client().post(&url), &headers, &body);
crate::wire::record_request(self.name(), &url, &headers, &body);
let response = crate::http::send(auth.apply(request)).await?;
if !(in_place && response.status() == reqwest::StatusCode::BAD_REQUEST) {
break response;
}
// One recoverable 400: an endpoint that doesn't know `additional_tools`. List the
// deferred tools instead, retry once, and remember it for this model
let body_text = response.text().await.unwrap_or_default();
if !refuses_in_place_loading(&body_text) {
return Err(crate::http::status_error(reqwest::StatusCode::BAD_REQUEST, body_text));
}
warn!(
model = %req.model.r#ref.id,
rejection = %body_text,
"the endpoint refused in-place tool loading; listing deferred tools instead"
);
self.remember_listed_tools(&req);
in_place = false;
};
if !response.status().is_success() {
let status = response.status();
let body_text = response.text().await.unwrap_or_default();
return Err(crate::http::status_error(status, body_text));
}
// A subscription backend reports how much of the plan is left in the response headers. Read
// it before consuming the body, and lead the stream with it so the UI can show headroom for
// the turn that is about to run.
let plan = plan_usage_from_headers(response.headers());
let events = crate::sse::decode(response.bytes_stream(), cancel, ResponsesDecoder);
Ok(match plan {
Some(plan) => {
use futures::StreamExt;
let lead = futures::stream::once(async move { ProviderEvent::PlanUsage(plan) });
Box::pin(lead.chain(events))
}
None => events,
})
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,44 @@
//! Plan headroom — what a ChatGPT subscription reports about its own quota.
use luxe_core::provider::{PlanUsage, PlanWindow};
/// Read a ChatGPT plan's remaining headroom out of a Codex response's headers.
///
/// The backend publishes `x-codex-*` headers on every response: which plan, how much of the primary
/// (weekly) and secondary windows is spent, when each resets, and any pay-as-you-go credit balance.
/// Header names and shapes were read off a live response rather than documentation, so every field
/// is optional and a missing or unparseable one is simply absent — this is a display signal, and a
/// wrong guess must never look like a real number.
pub fn plan_usage_from_headers(headers: &reqwest::header::HeaderMap) -> Option<PlanUsage> {
let text = |name: &str| {
headers
.get(name)
.and_then(|value| value.to_str().ok())
.map(str::trim)
.filter(|value| !value.is_empty())
};
let number = |name: &str| text(name).and_then(|value| value.parse::<f64>().ok());
let window = |prefix: &str| {
let used = number(&format!("x-codex-{prefix}-used-percent"))?;
let minutes = number(&format!("x-codex-{prefix}-window-minutes")).unwrap_or(0.0) as u64;
// A zero-length window is the backend saying "this one doesn't apply to your plan".
(minutes > 0).then(|| PlanWindow {
used_percent: used as f32,
window_minutes: minutes,
resets_in_secs: number(&format!("x-codex-{prefix}-reset-after-seconds"))
.map(|secs| secs.max(0.0) as u64),
})
};
let usage = PlanUsage {
plan: text("x-codex-plan-type").map(str::to_string),
primary: window("primary"),
secondary: window("secondary"),
// Only meaningful when the account actually has credits enabled.
credits_balance: text("x-codex-credits-has-credits")
.filter(|has| has.eq_ignore_ascii_case("true"))
.and_then(|_| number("x-codex-credits-balance")),
};
(!usage.is_empty()).then_some(usage)
}

View File

@@ -0,0 +1,396 @@
//! Responses request building — core messages to `POST /responses` wire JSON.
use std::collections::{HashMap, HashSet};
use luxe_core::message::ContentBlock;
use luxe_core::provider::{CompletionRequest, ThinkingLevel};
use super::{OpenaiResponsesProvider, ResponsesFlavor};
use crate::wire_json::data_url;
impl OpenaiResponsesProvider {
/// Build the JSON request body for `POST /v1/responses`, as the next request would.
#[cfg(test)]
pub(crate) fn build_request_body(&self, req: &CompletionRequest) -> serde_json::Value {
self.body_for(req, self.loads_in_place(req))
}
/// Build the JSON request body for `POST /v1/responses`, with the deferred tools loaded in
/// place when `in_place` is set and there are any.
///
/// In place, the top-level `tools` is the engine's list without the deferred names, so it's the
/// same bytes before and after an activation, and each successful `activate_tools` result is
/// followed by an `additional_tools` item carrying what it loaded. A pass that withholds
/// tools loads nothing either.
pub(super) fn body_for(&self, req: &CompletionRequest, in_place: bool) -> serde_json::Value {
let loadable: HashMap<&str, &luxe_core::provider::ToolSchema> =
if in_place && !req.tools.is_empty() {
req.deferred_tools.iter().map(|tool| (tool.name.as_str(), tool)).collect()
} else {
HashMap::new()
};
// --- input array ---
let input = build_input_items_loading(
&req.messages,
req.model.input.contains(&luxe_core::provider::Modality::Image),
&loadable,
);
let mut body = serde_json::json!({
"model": req.model.r#ref.id,
"stream": true,
"input": input,
});
// System prompt becomes `instructions`.
if let Some(system) = &req.system {
body["instructions"] = serde_json::Value::String(system.clone());
}
// Max output tokens (omit when 0 — "no cap"). The Codex backend decides its own cap and
// rejects the field.
if self.flavor == ResponsesFlavor::Standard {
if let Some(max) = req.max_tokens {
if max > 0 {
body["max_output_tokens"] = max.into();
}
}
}
// The Codex backend never persists a response, and it wants the tool policy stated.
if self.flavor == ResponsesFlavor::Codex {
body["store"] = serde_json::Value::Bool(false);
body["include"] = serde_json::json!(["reasoning.encrypted_content"]);
body["tool_choice"] = serde_json::Value::String("auto".to_string());
body["parallel_tool_calls"] = serde_json::Value::Bool(true);
// Codex requires instructions; an empty turn would otherwise 400.
if req.system.is_none() {
body["instructions"] =
serde_json::Value::String("You are a helpful coding assistant.".to_string());
}
}
// Reasoning — only for reasoning-capable models. Run statelessly (`store: false`) and ask
// for encrypted reasoning items so they can be round-tripped across tool calls; the
// Responses API 400s ("function_call ... without its required reasoning item") if a
// reasoning model's tool call is replayed without its reasoning. `summary: "auto"` also
// surfaces human-readable reasoning for display.
if req.model.reasoning {
body["store"] = serde_json::Value::Bool(false);
body["include"] = serde_json::json!(["reasoning.encrypted_content"]);
let level = req.model.effective_thinking_level(req.thinking);
let mut reasoning = serde_json::json!({ "summary": "auto" });
if level != ThinkingLevel::Off {
let effort = req.model.thinking_level_value(level).unwrap_or(match level {
ThinkingLevel::Minimal | ThinkingLevel::Low => "low",
ThinkingLevel::High | ThinkingLevel::XHigh => "high",
ThinkingLevel::Ultra => "max",
_ => "medium",
});
reasoning["effort"] = serde_json::Value::String(effort.to_string());
}
body["reasoning"] = reasoning;
}
// Tools — flat array, NOT nested under "function".
if !req.tools.is_empty() {
let tools: Vec<serde_json::Value> = req
.tools
.iter()
.filter(|tool| !loadable.contains_key(tool.name.as_str()))
.map(function_tool)
.collect();
body["tools"] = serde_json::Value::Array(tools);
}
// Last, so the model's own recipe outranks every field above it.
crate::sampling::apply(&mut body, &req.model.sampling_params);
body
}
}
/// One `function` tool definition, as `tools` and `additional_tools` both take it.
fn function_tool(t: &luxe_core::provider::ToolSchema) -> serde_json::Value {
// NOTE: the Responses API defaults `strict` to true, unlike Chat Completions. Left out, every
// call is decoded against its schema as a grammar, and that grammar allows whitespace between
// tokens that a model can fall into writing until its output limit: replaying one captured
// request, 3 of 18 tries ran away like that, and 0 of 36 with this set.
serde_json::json!({
"type": "function",
"name": t.name,
"description": t.description,
"parameters": t.parameters,
"strict": false,
})
}
/// Whether `body` is a 400 about `additional_tools` itself, so listing the tools instead would get
/// the request through.
pub(super) fn refuses_in_place_loading(body: &str) -> bool {
body.contains("additional_tools")
}
/// The calls in `messages` to a tool an earlier activation loaded in place, by call id.
///
/// A tool loaded by `additional_tools` lives in a namespace of its own name, and a call to it
/// replays only with that namespace attached (a live 400 without it: "Missing namespace for
/// function_call 'module_report'"). A call with no activation ahead of it comes from a session
/// that had the tool listed, and replays as it was sent; the API takes a call to a tool it no
/// longer has.
fn namespaced_calls<'a>(
messages: &'a [luxe_core::message::Message],
loadable: &HashMap<&str, &luxe_core::provider::ToolSchema>,
) -> HashSet<&'a str> {
let mut namespaced = HashSet::new();
if loadable.is_empty() {
return namespaced;
}
let mut requested: HashMap<&str, Vec<String>> = HashMap::new();
let mut loaded: HashSet<String> = HashSet::new();
for block in messages.iter().flat_map(|message| &message.content) {
match block {
ContentBlock::ToolCall { id, name, arguments }
if name == luxe_core::tool::ACTIVATE_TOOLS_NAME =>
{
requested.insert(id, luxe_core::tool_activation::requested_names(arguments));
}
ContentBlock::ToolCall { id, name, .. }
if loadable.contains_key(name.as_str()) && loaded.contains(name) =>
{
namespaced.insert(id.as_str());
}
ContentBlock::ToolResult { call_id, is_error: false, .. } => {
loaded.extend(requested.remove(call_id.as_str()).unwrap_or_default());
}
_ => {}
}
}
namespaced
}
/// The deferred tools each `activate_tools` call loads in place, by call id.
fn activations<'a>(
messages: &[luxe_core::message::Message],
loadable: &HashMap<&str, &'a luxe_core::provider::ToolSchema>,
) -> HashMap<String, Vec<&'a luxe_core::provider::ToolSchema>> {
if loadable.is_empty() {
return HashMap::new();
}
messages
.iter()
.flat_map(|message| &message.content)
.filter_map(|block| match block {
ContentBlock::ToolCall { id, name, arguments }
if name == luxe_core::tool::ACTIVATE_TOOLS_NAME =>
{
let tools: Vec<_> = luxe_core::tool_activation::requested_names(arguments)
.iter()
.filter_map(|name| loadable.get(name.as_str()).copied())
.collect();
(!tools.is_empty()).then(|| (id.clone(), tools))
}
_ => None,
})
.collect()
}
/// One `input_image` content part carrying bytes as a data URL.
fn input_image(mime: &str, data: &str) -> serde_json::Value {
serde_json::json!({ "type": "input_image", "image_url": data_url(mime, data) })
}
/// A tool result's `output`: the plain string it has always been, or the content array this API
/// accepts when the result carries pixels.
///
/// Unlike chat-completions, nothing has to be restructured here — `function_call_output.output` is
/// `string | Array<input_text | input_image | input_file>`, so the image rides inside the result it
/// belongs to and no `user` message is interleaved. The string form is kept whenever there is no
/// image, because that is what every existing transcript and wire test reads.
fn function_call_output(
content: &[luxe_core::ToolOutput],
accepts_images: bool,
) -> serde_json::Value {
let text = luxe_core::ToolOutput::joined_text(content);
let images: Vec<serde_json::Value> = if accepts_images {
luxe_core::ToolOutput::images(content).map(|(mime, data)| input_image(mime, data)).collect()
} else {
Vec::new()
};
if images.is_empty() {
let carried = luxe_core::ToolOutput::images(content).next().is_some();
// Nothing but an image, and no way to send it: say so rather than send an empty result.
return serde_json::Value::String(if text.is_empty() && carried {
"[image]".to_string()
} else {
text
});
}
let mut parts = Vec::with_capacity(images.len() + 1);
parts.push(serde_json::json!({
"type": "input_text",
"text": if text.is_empty() { "(see attached image)".to_string() } else { text },
}));
parts.extend(images);
serde_json::Value::Array(parts)
}
/// [`build_input_items_loading`] with nothing loaded in place.
#[cfg(test)]
pub(super) fn build_input_items(
messages: &[luxe_core::message::Message],
accepts_images: bool,
) -> Vec<serde_json::Value> {
build_input_items_loading(messages, accepts_images, &HashMap::new())
}
/// Convert the conversation history into the flat `input` array the Responses API expects.
///
/// A successful `activate_tools` result is followed by an `additional_tools` item carrying the
/// `loadable` tools it asked for, which makes them callable from that point on. It's derived from
/// the transcript alone, so it sits in the same place on every later request and the cache keeps
/// everything before it.
fn build_input_items_loading(
messages: &[luxe_core::message::Message],
accepts_images: bool,
loadable: &HashMap<&str, &luxe_core::provider::ToolSchema>,
) -> Vec<serde_json::Value> {
use luxe_core::message::Role;
let activations = activations(messages, loadable);
let namespaced = namespaced_calls(messages, loadable);
let mut items: Vec<serde_json::Value> = Vec::new();
for msg in messages {
match msg.role {
Role::User => items.push(user_item(msg, accepts_images)),
Role::Assistant => assistant_items(msg, &namespaced, &mut items),
Role::Tool => tool_items(msg, accepts_images, &activations, &mut items),
// System role is handled via `instructions`; skip.
Role::System => {}
}
}
items
}
/// A user turn: its text, with its images beside it when the model takes them.
fn user_item(msg: &luxe_core::message::Message, accepts_images: bool) -> serde_json::Value {
let text = msg.text();
let images: Vec<serde_json::Value> = if accepts_images {
msg.content
.iter()
.filter_map(|block| match block {
ContentBlock::Image { data, mime, .. } => Some(input_image(mime, data)),
_ => None,
})
.collect()
} else {
Vec::new()
};
if images.is_empty() {
return serde_json::json!({ "role": "user", "content": text });
}
let mut parts = vec![serde_json::json!({ "type": "input_text", "text": text })];
parts.extend(images);
serde_json::json!({ "role": "user", "content": parts })
}
/// An assistant turn may contain text, tool calls, or both, each its own item in content order.
fn assistant_items(
msg: &luxe_core::message::Message,
namespaced: &HashSet<&str>,
items: &mut Vec<serde_json::Value>,
) {
for block in &msg.content {
match block {
ContentBlock::Text(text) => {
items.push(serde_json::json!({ "role": "assistant", "content": text }));
}
ContentBlock::Thinking { text, id, encrypted, .. } => {
items.extend(reasoning_item(text, id.as_deref(), encrypted.as_deref()));
}
// Anthropic's encrypted reasoning has no OpenAI equivalent; skip it.
ContentBlock::RedactedThinking { .. } => {}
ContentBlock::ToolCall { id, name, arguments } => {
let mut item = serde_json::json!({
"type": "function_call",
"call_id": id,
"name": name,
"arguments": arguments.to_string(),
});
if namespaced.contains(id.as_str()) {
item["namespace"] = serde_json::Value::String(name.clone());
}
items.push(item);
}
// ToolResult inside an assistant block is unusual; skip.
_ => {}
}
}
}
/// Replay OpenAI-origin reasoning verbatim, in content order, so each reasoning item still
/// precedes its function_call (required, or the API 400s).
///
/// Anthropic thinking (signature only, no id/encrypted) is skipped. Under `store: false` an item
/// without `encrypted_content` is dropped by the API, so only emit when we captured it.
fn reasoning_item(
text: &str,
id: Option<&str>,
encrypted: Option<&str>,
) -> Option<serde_json::Value> {
if id.is_none() && encrypted.is_none() {
return None;
}
let mut item = serde_json::json!({ "type": "reasoning" });
if let Some(id) = id {
item["id"] = serde_json::Value::String(id.to_string());
}
if let Some(encrypted) = encrypted {
item["encrypted_content"] = serde_json::Value::String(encrypted.to_string());
}
item["summary"] = if text.is_empty() {
serde_json::json!([])
} else {
serde_json::json!([{ "type": "summary_text", "text": text }])
};
Some(item)
}
/// Each `ToolResult` block becomes a separate `function_call_output` item, followed by the
/// `additional_tools` item its activation loaded.
fn tool_items(
msg: &luxe_core::message::Message,
accepts_images: bool,
activations: &HashMap<String, Vec<&luxe_core::provider::ToolSchema>>,
items: &mut Vec<serde_json::Value>,
) {
let mut emitted = false;
for block in &msg.content {
if let ContentBlock::ToolResult { call_id, content, is_error } = block {
items.push(serde_json::json!({
"type": "function_call_output",
"call_id": call_id,
"output": function_call_output(content, accepts_images),
}));
emitted = true;
if let Some(tools) = activations.get(call_id).filter(|_| !is_error) {
items.push(serde_json::json!({
"type": "additional_tools",
"role": "developer",
"tools": tools.iter().map(|tool| function_tool(tool)).collect::<Vec<_>>(),
}));
}
}
}
if !emitted {
// Defensive: Tool message with no ToolResult blocks.
items.push(serde_json::json!({
"type": "function_call_output",
"call_id": "",
"output": "",
}));
}
}

View File

@@ -0,0 +1,338 @@
//! Responses SSE decoding — `event:`/`data:` records to [`ProviderEvent`]s.
use luxe_core::provider::{ProviderErrorKind, ProviderEvent, StopReason, Usage};
use serde::Deserialize;
use tracing::warn;
/// Parsed representation of a single SSE event from the Responses API.
#[derive(Debug)]
enum ResponsesSseEvent {
/// `response.output_text.delta` — streaming text chunk.
OutputTextDelta { delta: String },
/// `response.output_item.added` with `item.type == "function_call"`.
FunctionCallAdded { output_index: usize, call_id: String, name: String },
/// `response.function_call_arguments.delta` — streaming tool-call JSON chunk.
FunctionCallArgumentsDelta { output_index: usize, delta: String },
/// `response.reasoning_summary_text.delta` — streaming reasoning summary text at its item's
/// output index (so it groups with that item's id/encrypted_content).
ReasoningSummaryDelta { output_index: usize, delta: String },
/// `response.reasoning_summary_part.added` — a new *paragraph* of the summary begins.
///
/// One reasoning item's summary may arrive in several parts, and the deltas carry no separator
/// between them, so concatenating them ran the last sentence of one paragraph into the first of
/// the next. The part index is what tells them apart: part 0 opens the summary and needs no
/// break, and every part after it does.
ReasoningSummaryPartAdded { output_index: usize, summary_index: usize },
/// `response.output_item.done` with `item.type == "reasoning"` — the finalized reasoning item,
/// carrying its `id` and (when requested) `encrypted_content` for stateless replay.
ReasoningItemDone { output_index: usize, id: Option<String>, encrypted: Option<String> },
/// `response.completed` — the full response is done.
Completed { usage: Option<RespUsage>, has_function_call: bool },
/// `response.failed` / `response.error` / generic `error` — something went wrong.
Error { message: String, code: Option<serde_json::Value> },
}
/// An error event's payload: `error` says it at the top, `response.failed` under `response.error`.
#[derive(Debug, Default, Deserialize)]
#[serde(default)]
struct ErrorFrame {
message: Option<String>,
code: Option<serde_json::Value>,
error: Option<Box<ErrorFrame>>,
response: Option<Box<ErrorFrame>>,
}
/// Usage block inside `response.completed`.
#[derive(Debug, Deserialize)]
struct RespUsage {
input_tokens: u32,
output_tokens: u32,
/// Cached-input breakdown; `input_tokens` already includes these.
#[serde(default)]
input_tokens_details: Option<RespTokenDetails>,
/// Reasoning-output breakdown; `output_tokens` already includes these.
#[serde(default)]
output_tokens_details: Option<RespTokenDetails>,
}
/// The `*_tokens_details` sub-object on a Responses usage block.
#[derive(Debug, Deserialize, Default)]
struct RespTokenDetails {
#[serde(default)]
cached_tokens: u32,
/// What the request wrote to the cache, which OpenAI now reports and the catalog prices
#[serde(default)]
cache_write_tokens: u32,
#[serde(default)]
reasoning_tokens: u32,
}
/// Parse all SSE events from the raw text body and return ProviderEvents.
///
/// Each SSE "message" is separated by a blank line and looks like:
/// ```text
/// event: response.output_text.delta
/// data: {"delta":"..."}
/// ```
#[cfg(test)]
pub(crate) fn parse_responses_sse(text: &str) -> Vec<ProviderEvent> {
let mut events = Vec::new();
for chunk in text.split("\n\n") {
if let Some(ev) = parse_single_event(chunk) {
push_provider_events(ev, &mut events);
}
}
events
}
/// Parse one SSE chunk (potentially multi-line) into a typed event.
fn parse_single_event(chunk: &str) -> Option<ResponsesSseEvent> {
let mut event_type: Option<&str> = None;
let mut data: Option<&str> = None;
for line in chunk.lines() {
if let Some(t) = line.strip_prefix("event: ") {
event_type = Some(t.trim());
} else if let Some(d) = line.strip_prefix("data: ") {
data = Some(d.trim());
}
}
let event_type = event_type?;
let data = data.unwrap_or("{}");
match event_type {
"response.output_text.delta" => parse_text_delta(data),
"response.output_item.added" => parse_item_added(data),
"response.function_call_arguments.delta" => parse_arguments_delta(data),
"response.reasoning_summary_part.added" => parse_summary_part_added(data),
"response.reasoning_summary_text.delta" => parse_summary_delta(data),
"response.output_item.done" => parse_item_done(data),
"response.completed" => Some(parse_completed(data)),
"response.failed" | "response.error" | "error" => Some(parse_error(event_type, data)),
_ => None,
}
}
fn parse_text_delta(data: &str) -> Option<ResponsesSseEvent> {
#[derive(Deserialize)]
struct D {
delta: String,
}
let d: D = serde_json::from_str(data).ok()?;
Some(ResponsesSseEvent::OutputTextDelta { delta: d.delta })
}
/// Only a `function_call` item is of interest; any other kind starting is not an event.
fn parse_item_added(data: &str) -> Option<ResponsesSseEvent> {
#[derive(Deserialize)]
struct D {
output_index: usize,
item: Item,
}
#[derive(Deserialize)]
struct Item {
#[serde(rename = "type")]
item_type: String,
#[serde(default)]
call_id: String,
#[serde(default)]
name: String,
}
let d: D = serde_json::from_str(data).ok()?;
if d.item.item_type != "function_call" {
return None;
}
Some(ResponsesSseEvent::FunctionCallAdded {
output_index: d.output_index,
call_id: d.item.call_id,
name: d.item.name,
})
}
fn parse_arguments_delta(data: &str) -> Option<ResponsesSseEvent> {
#[derive(Deserialize)]
struct D {
output_index: usize,
delta: String,
}
let d: D = serde_json::from_str(data).ok()?;
Some(ResponsesSseEvent::FunctionCallArgumentsDelta {
output_index: d.output_index,
delta: d.delta,
})
}
fn parse_summary_part_added(data: &str) -> Option<ResponsesSseEvent> {
#[derive(Deserialize)]
struct D {
#[serde(default)]
output_index: usize,
#[serde(default)]
summary_index: usize,
}
let d: D = serde_json::from_str(data).ok()?;
Some(ResponsesSseEvent::ReasoningSummaryPartAdded {
output_index: d.output_index,
summary_index: d.summary_index,
})
}
fn parse_summary_delta(data: &str) -> Option<ResponsesSseEvent> {
#[derive(Deserialize)]
struct D {
#[serde(default)]
output_index: usize,
delta: String,
}
let d: D = serde_json::from_str(data).ok()?;
Some(ResponsesSseEvent::ReasoningSummaryDelta { output_index: d.output_index, delta: d.delta })
}
/// The finalized reasoning item carries its id and (when `include` requested it) the
/// `encrypted_content` we must replay on later turns.
fn parse_item_done(data: &str) -> Option<ResponsesSseEvent> {
#[derive(Deserialize)]
struct D {
#[serde(default)]
output_index: usize,
item: Item,
}
#[derive(Deserialize)]
struct Item {
#[serde(rename = "type")]
item_type: String,
#[serde(default)]
id: Option<String>,
#[serde(default)]
encrypted_content: Option<String>,
}
let d: D = serde_json::from_str(data).ok()?;
if d.item.item_type != "reasoning" {
return None;
}
Some(ResponsesSseEvent::ReasoningItemDone {
output_index: d.output_index,
id: d.item.id.filter(|id| !id.is_empty()),
encrypted: d.item.encrypted_content.filter(|enc| !enc.is_empty()),
})
}
/// Shape: `{ "response": { "usage": {...}, "output": [...] } }`.
fn parse_completed(data: &str) -> ResponsesSseEvent {
#[derive(Deserialize)]
struct D {
response: Resp,
}
#[derive(Deserialize)]
struct Resp {
#[serde(default)]
usage: Option<RespUsage>,
#[serde(default)]
output: Vec<OutputItem>,
}
#[derive(Deserialize)]
struct OutputItem {
#[serde(rename = "type")]
item_type: String,
}
match serde_json::from_str::<D>(data) {
Ok(d) => {
let has_function_call =
d.response.output.iter().any(|o| o.item_type == "function_call");
ResponsesSseEvent::Completed { usage: d.response.usage, has_function_call }
}
Err(e) => {
warn!(error = %e, "failed to parse response.completed data");
// Still emit a completed event without usage.
ResponsesSseEvent::Completed { usage: None, has_function_call: false }
}
}
}
fn parse_error(event_type: &str, data: &str) -> ResponsesSseEvent {
let frame: ErrorFrame = serde_json::from_str(data).unwrap_or_default();
let inner = frame.response.and_then(|response| response.error).or(frame.error);
let inner = inner.map(|inner| *inner).unwrap_or_default();
let fallback = if event_type == "error" { "unknown error" } else { event_type };
let message = frame.message.or(inner.message).unwrap_or_else(|| fallback.to_string());
ResponsesSseEvent::Error { message, code: frame.code.or(inner.code) }
}
/// Convert a typed Responses API SSE event into one or more ProviderEvents.
fn push_provider_events(event: ResponsesSseEvent, out: &mut Vec<ProviderEvent>) {
match event {
ResponsesSseEvent::OutputTextDelta { delta } => {
out.push(ProviderEvent::TextDelta { index: 0, delta });
}
ResponsesSseEvent::FunctionCallAdded { output_index, call_id, name } => {
out.push(ProviderEvent::ToolCallStart { index: output_index, id: call_id, name });
}
ResponsesSseEvent::FunctionCallArgumentsDelta { output_index, delta } => {
out.push(ProviderEvent::ToolCallDelta { index: output_index, json_delta: delta });
}
ResponsesSseEvent::ReasoningSummaryDelta { output_index, delta } => {
out.push(ProviderEvent::ThinkingDelta { index: output_index, delta });
}
// The break belongs *before* the part that follows it, and only from the second part on:
// emitting it for part 0 would open every reasoning block with a blank line.
ResponsesSseEvent::ReasoningSummaryPartAdded { output_index, summary_index } => {
if summary_index > 0 {
out.push(ProviderEvent::ThinkingDelta {
index: output_index,
delta: "\n\n".to_string(),
});
}
}
ResponsesSseEvent::ReasoningItemDone { output_index, id, encrypted } => {
out.push(ProviderEvent::ReasoningItem { index: output_index, id, encrypted });
}
ResponsesSseEvent::Completed { usage, has_function_call } => {
// Emit usage first (before Done; the turn loop stops on Done).
if let Some(u) = usage {
let cache_read = u.input_tokens_details.as_ref().map_or(0, |d| d.cached_tokens);
let cache_write =
u.input_tokens_details.as_ref().map_or(0, |d| d.cache_write_tokens);
let reasoning = u.output_tokens_details.as_ref().map_or(0, |d| d.reasoning_tokens);
out.push(ProviderEvent::Usage(Usage {
prompt_tokens: u.input_tokens,
completion_tokens: u.output_tokens,
total_tokens: u.input_tokens + u.output_tokens,
cache_read_tokens: cache_read,
cache_write_tokens: cache_write,
reasoning_tokens: reasoning,
cache_write_1h_tokens: 0,
}));
}
let reason = if has_function_call { StopReason::ToolCall } else { StopReason::EndTurn };
out.push(ProviderEvent::Done { reason });
}
ResponsesSseEvent::Error { message, code } => {
let kind = code.and_then(|code| crate::http::kind_of_code(&code, &message));
let kind =
kind.unwrap_or_else(|| ProviderErrorKind::Other("responses_api_error".into()));
out.push(ProviderEvent::Error { message, kind });
}
}
}
/// Record-at-a-time decoder for the Responses API.
///
/// Every record on this API is self-contained (usage rides along with `response.completed`), so
/// unlike the chat-completions decoder this one needs no state.
pub(super) struct ResponsesDecoder;
impl crate::sse::SseDecoder for ResponsesDecoder {
fn record(&mut self, record: &str, out: &mut Vec<ProviderEvent>) {
if let Some(event) = parse_single_event(record) {
push_provider_events(event, out);
}
}
}

View File

@@ -0,0 +1,15 @@
#![allow(clippy::unwrap_used)]
use super::{request::build_input_items, *};
use crate::test_server::{http_reply, request_body, serve_replies};
use luxe_core::message::{ContentBlock, Message, Role, ToolOutput};
use luxe_core::provider::{ModelInfo, ModelRef, StopReason, ThinkingLevel, ToolSchema};
mod codex;
mod lazy;
mod request;
mod sse;
mod support;
use sse::*;
use support::*;

View File

@@ -0,0 +1,128 @@
//! Codex — plan headroom and the ChatGPT backend flavour.
use super::*;
#[test]
fn plan_headroom_is_read_from_a_real_codex_response() {
let headers = codex_headers(&[
("x-codex-plan-type", "plus"),
("x-codex-primary-used-percent", "12"),
("x-codex-primary-window-minutes", "10080"),
("x-codex-primary-reset-after-seconds", "603553"),
("x-codex-secondary-used-percent", "0"),
("x-codex-secondary-window-minutes", "0"),
("x-codex-credits-has-credits", "False"),
("x-codex-credits-balance", "0"),
]);
let plan = plan_usage_from_headers(&headers).expect("headers carry a plan");
assert_eq!(plan.plan.as_deref(), Some("plus"));
let primary = plan.primary.expect("weekly window");
assert_eq!(primary.used_percent, 12.0);
assert_eq!(primary.window_label(), "weekly");
assert_eq!(primary.reset_label().as_deref(), Some("6d 23h"));
// A zero-length window is the backend saying the plan has no such limit.
assert!(plan.secondary.is_none(), "a 0-minute window is not a window");
// Credits are only meaningful when the account actually has them.
assert_eq!(plan.credits_balance, None);
assert_eq!(plan.summary().as_deref(), Some("plus · 12% of weekly (resets in 6d 23h)"));
}
#[test]
fn a_response_without_plan_headers_reports_nothing_rather_than_zero() {
assert!(plan_usage_from_headers(&codex_headers(&[])).is_none());
assert!(plan_usage_from_headers(&codex_headers(&[("x-request-id", "abc")])).is_none());
// Unparseable values are absent, not zero — a fake "0% used" is worse than no number.
let garbled = codex_headers(&[
("x-codex-primary-used-percent", "many"),
("x-codex-primary-window-minutes", "10080"),
]);
assert!(plan_usage_from_headers(&garbled).is_none());
}
/// The status line shows one window, and it should be the one about to bite.
#[test]
fn the_tightest_window_is_the_one_reported() {
let headers = codex_headers(&[
("x-codex-plan-type", "pro"),
("x-codex-primary-used-percent", "20"),
("x-codex-primary-window-minutes", "10080"),
("x-codex-secondary-used-percent", "83"),
("x-codex-secondary-window-minutes", "300"),
("x-codex-secondary-reset-after-seconds", "1800"),
("x-codex-credits-has-credits", "true"),
("x-codex-credits-balance", "12.5"),
]);
let plan = plan_usage_from_headers(&headers).expect("plan");
assert_eq!(plan.summary().as_deref(), Some("pro · 83% of 5h (resets in 30m)"));
assert_eq!(plan.credits_balance, Some(12.5));
}
/// The ChatGPT backend lives at a different path, and a base URL that already names it must not
/// be doubled up.
#[test]
fn the_codex_flavour_targets_the_chatgpt_backend_path() {
let codex = OpenaiResponsesProvider::new(ProviderConfig::default()).codex();
assert_eq!(codex.effective_base_url(), "https://chatgpt.com/backend-api");
assert_eq!(
codex.request_url("https://chatgpt.com/backend-api"),
"https://chatgpt.com/backend-api/codex/responses"
);
assert_eq!(
codex.request_url("https://proxy.local/codex/responses"),
"https://proxy.local/codex/responses"
);
assert_eq!(
codex.request_url("https://proxy.local/codex"),
"https://proxy.local/codex/responses"
);
assert_eq!(codex.request_url("https://proxy.local/"), "https://proxy.local/codex/responses");
// The standard flavour is untouched.
let standard = make_provider();
assert_eq!(
standard.request_url("https://api.openai.com/v1"),
"https://api.openai.com/v1/responses"
);
}
/// Codex refuses an output cap and never stores a response; both are wire-level requirements
/// rather than preferences.
#[test]
fn the_codex_flavour_omits_the_output_cap_and_forces_stateless_requests() {
let codex = OpenaiResponsesProvider::new(ProviderConfig::default()).codex();
let mut req = make_req("gpt-5.3-codex");
req.max_tokens = Some(4096);
let body = codex.build_request_body(&req);
assert!(body.get("max_output_tokens").is_none(), "Codex rejects an output cap");
assert_eq!(body["store"], false);
assert_eq!(body["include"][0], "reasoning.encrypted_content");
assert_eq!(body["tool_choice"], "auto");
assert_eq!(body["parallel_tool_calls"], true);
// Codex requires instructions; a turn without a system prompt still gets some.
assert!(body["instructions"].as_str().is_some_and(|text| !text.is_empty()));
// The standard flavour keeps sending the cap.
let standard = make_provider();
assert_eq!(standard.build_request_body(&req)["max_output_tokens"], 4096);
}
// -----------------------------------------------------------------------
// Request-body building
// -----------------------------------------------------------------------
#[test]
fn request_body_basic_fields() {
let p = make_provider();
let req = make_req("gpt-5");
let body = p.build_request_body(&req);
assert_eq!(body["model"], "gpt-5");
assert_eq!(body["stream"], true);
assert!(body["input"].is_array());
// No instructions when system is None.
assert!(body.get("instructions").is_none());
// No max_output_tokens when max_tokens is None.
assert!(body.get("max_output_tokens").is_none());
}

View File

@@ -0,0 +1,180 @@
//! Lazy tools — activation, replay and the refusal fallback.
use super::*;
pub(super) fn activation(id: &str, names: &[&str], is_error: bool) -> [Message; 2] {
[
Message {
role: Role::Assistant,
content: vec![ContentBlock::ToolCall {
id: id.to_string(),
name: luxe_core::tool::ACTIVATE_TOOLS_NAME.to_string(),
arguments: serde_json::json!({ "names": names }),
}],
},
Message::tool_result(id, "Activated.", is_error),
]
}
/// The engine's request: core plus the activated ones in `tools`, every deferred tool beside.
pub(super) fn lazy_req(activated: &[&str], messages: Vec<Message>) -> CompletionRequest {
let mut tools: Vec<ToolSchema> =
["activate_tools", "bash", "read"].iter().chain(activated).map(|n| schema(n)).collect();
tools.sort_by(|a, b| a.name.cmp(&b.name));
CompletionRequest {
tools,
deferred_tools: vec![schema("debug"), schema("test")],
messages,
..make_req("gpt-5.4")
}
}
pub(super) fn names(tools: &serde_json::Value) -> Vec<&str> {
tools.as_array().unwrap().iter().map(|tool| tool["name"].as_str().unwrap()).collect()
}
/// Activating a tool leaves `tools` byte-identical and loads the tool right after the result
/// that asked for it, so the cached prefix runs on past the activation.
#[test]
fn an_activation_loads_in_place_and_the_tool_list_holds_still() {
let p = make_provider();
let before = p.build_request_body(&lazy_req(&[], vec![Message::user("go")]));
let mut messages = vec![Message::user("go")];
messages.extend(activation("call-1", &["test", "read", "nope"], false));
let after = p.build_request_body(&lazy_req(&["test"], messages));
assert_eq!(names(&before["tools"]), vec!["activate_tools", "bash", "read"]);
assert_eq!(before["tools"], after["tools"], "the list holds still");
let input = after["input"].as_array().unwrap();
assert_eq!(input[0], before["input"][0], "an append");
assert_eq!(input[2]["type"], "function_call_output");
assert_eq!(input[3]["type"], "additional_tools");
assert_eq!(input[3]["role"], "developer");
assert_eq!(names(&input[3]["tools"]), vec!["test"], "only a deferred tool is loaded");
assert_eq!(input[3]["tools"][0]["strict"], false, "shaped like any other tool");
}
/// A call to a tool loaded in place replays in that tool's namespace, which is where the API
/// put it (a live 400 without it: "Missing namespace for function_call 'module_report'").
#[test]
fn a_loaded_tool_s_call_replays_in_its_namespace() {
let mut messages = vec![Message::user("go")];
messages.extend(activation("call-1", &["test"], false));
messages.push(Message {
role: Role::Assistant,
content: vec![ContentBlock::ToolCall {
id: "call-2".into(),
name: "test".into(),
arguments: serde_json::json!({}),
}],
});
messages.push(Message::tool_result("call-2", "1 passed", false));
let body = make_provider().build_request_body(&lazy_req(&["test"], messages));
let input = body["input"].as_array().unwrap();
assert_eq!(input[1].get("namespace"), None, "a core call has none");
assert_eq!(input[4]["type"], "function_call");
assert_eq!(input[4]["namespace"], "test");
}
/// A deferred tool the history calls before anything loaded it (a session that ran with lazy
/// tools off) replays as it was sent, with no namespace: it was never loaded into one, and the
/// API takes a call to a tool it no longer has.
#[test]
fn a_call_from_before_any_activation_replays_as_sent() {
let messages = vec![
Message::user("go"),
Message {
role: Role::Assistant,
content: vec![ContentBlock::ToolCall {
id: "call-1".into(),
name: "test".into(),
arguments: serde_json::json!({}),
}],
},
Message::tool_result("call-1", "1 passed", false),
];
let body = make_provider().build_request_body(&lazy_req(&[], messages));
assert_eq!(names(&body["tools"]), vec!["activate_tools", "bash", "read"]);
assert_eq!(body["input"][1]["name"], "test");
assert_eq!(body["input"][1].get("namespace"), None);
}
/// An activation that failed loads nothing, a pass that withholds tools loads nothing, and
/// with the flag off the request is the list it always was.
#[test]
fn nothing_loads_in_place_without_a_successful_activation_and_a_tool_list() {
let p = make_provider();
let mut failed = vec![Message::user("go")];
failed.extend(activation("call-1", &["test"], true));
let body = p.build_request_body(&lazy_req(&[], failed));
assert!(!body.to_string().contains("additional_tools"));
let mut loaded = vec![Message::user("go")];
loaded.extend(activation("call-1", &["test"], false));
let wrap_up = CompletionRequest {
tools: Vec::new(),
deferred_tools: Vec::new(),
..lazy_req(&["test"], loaded.clone())
};
let body = p.build_request_body(&wrap_up);
assert!(body.get("tools").is_none());
assert!(!body.to_string().contains("additional_tools"));
let listing = OpenaiResponsesProvider::new(ProviderConfig {
compat: luxe_core::provider::CompatFlags {
defer_tool_loading: false,
..Default::default()
},
..Default::default()
});
let body = listing.build_request_body(&lazy_req(&["test"], loaded));
assert_eq!(names(&body["tools"]), vec!["activate_tools", "bash", "read", "test"]);
assert!(!body.to_string().contains("additional_tools"));
}
/// An endpoint that doesn't know `additional_tools` is told once: the adapter lists the
/// deferred tools instead, retries, and keeps listing them for that model.
#[tokio::test]
async fn a_refusal_of_additional_tools_falls_back_to_listing_and_is_remembered() {
use futures::StreamExt;
let rejection = r#"{"error":{"message":"Invalid value: 'additional_tools'. Supported values are: 'message', 'function_call', 'function_call_output'.","type":"invalid_request_error"}}"#;
let turn = concat!(
"event: response.output_text.delta\n",
"data: {\"delta\":\"ok\"}\n\n",
"event: response.completed\n",
"data: {\"response\":{\"usage\":{\"input_tokens\":5,\"output_tokens\":1},",
"\"output\":[{\"type\":\"message\"}]}}\n\n",
);
let server = serve_replies(vec![
http_reply("400 Bad Request", "application/json", rejection),
http_reply("200 OK", "text/event-stream", turn),
http_reply("200 OK", "text/event-stream", turn),
]);
let port = server.port();
let provider = OpenaiResponsesProvider::new(ProviderConfig {
api_key: Some("sk-test".into()),
base_url: Some(format!("http://127.0.0.1:{port}/v1")),
..Default::default()
});
let mut messages = vec![Message::user("go")];
messages.extend(activation("call-1", &["test"], false));
for _ in 0..2 {
let (_keep, cancel) = tokio::sync::watch::channel(false);
let stream = provider
.stream(lazy_req(&["test"], messages.clone()), cancel)
.await
.expect("the retry recovers");
let events: Vec<ProviderEvent> = stream.collect().await;
assert!(events.iter().any(|event| matches!(event, ProviderEvent::TextDelta { .. })));
}
let requests = server.requests();
let bodies: Vec<&str> = requests.iter().map(|raw| request_body(raw)).collect();
assert_eq!(bodies.len(), 3, "one refusal, its retry, then the next turn");
assert!(bodies[0].contains("additional_tools"), "{}", bodies[0]);
assert!(!bodies[1].contains("additional_tools"), "retried listed: {}", bodies[1]);
assert!(bodies[1].contains("\"name\":\"test\""), "with the tool listed: {}", bodies[1]);
assert!(!bodies[2].contains("additional_tools"), "and remembered: {}", bodies[2]);
}

View File

@@ -0,0 +1,385 @@
//! Request — the body and the input items the adapter builds.
use super::*;
#[test]
fn request_body_system_becomes_instructions() {
let p = make_provider();
let mut req = make_req("gpt-5");
req.system = Some("You are a helpful assistant.".into());
let body = p.build_request_body(&req);
assert_eq!(body["instructions"], "You are a helpful assistant.");
}
#[test]
fn request_body_max_output_tokens_zero_omitted() {
let p = make_provider();
let mut req = make_req("gpt-5");
req.max_tokens = Some(0);
let body = p.build_request_body(&req);
assert!(body.get("max_output_tokens").is_none());
}
#[test]
fn request_body_max_output_tokens_nonzero_included() {
let p = make_provider();
let mut req = make_req("gpt-5");
req.max_tokens = Some(8192);
let body = p.build_request_body(&req);
assert_eq!(body["max_output_tokens"], 8192);
}
/// The Responses API is OpenAI-shaped too, so a model's recipe applies here as well — and it
/// is applied last, over `max_output_tokens` and everything else the adapter chose.
#[test]
fn a_models_sampling_recipe_reaches_the_responses_body_last() {
let p = make_provider();
let mut req = make_req("gpt-5");
req.max_tokens = Some(8192);
req.model.sampling_params = match serde_json::json!({
"temperature": 1.0, "top_p": 0.95, "max_output_tokens": 4096, "stream": false,
}) {
serde_json::Value::Object(map) => map,
_ => unreachable!("fixture is an object"),
};
let body = p.build_request_body(&req);
assert_eq!(body["temperature"], 1.0);
assert_eq!(body["top_p"], 0.95);
assert_eq!(body["max_output_tokens"], 4096, "a named field the recipe sets is overridden");
assert_eq!(body["stream"], true, "but not the ones that decide what request this is");
}
#[test]
fn request_body_tools_flat_not_nested() {
let p = make_provider();
let mut req = make_req("gpt-5");
req.tools = vec![ToolSchema {
name: "search".into(),
description: "Search the web".into(),
parameters: serde_json::json!({ "type": "object", "properties": {} }),
}];
let body = p.build_request_body(&req);
let tools = body["tools"].as_array().unwrap();
assert_eq!(tools.len(), 1);
let tool = &tools[0];
// Flat layout: name/description at top level, NOT under "function".
assert_eq!(tool["type"], "function");
assert_eq!(tool["name"], "search");
assert_eq!(tool["description"], "Search the web");
assert!(tool.get("function").is_none(), "tools must NOT be nested under 'function'");
assert_eq!(tool["strict"], false, "left out, the Responses API means true");
}
#[test]
fn request_body_reasoning_effort_for_reasoning_model() {
use std::collections::HashMap;
let p = make_provider();
let mut req = make_req("gpt-5");
req.model.reasoning = true;
req.model.thinking_level_map = HashMap::from([
("low".to_string(), Some("low".to_string())),
("medium".to_string(), Some("medium".to_string())),
("high".to_string(), Some("high".to_string())),
]);
req.thinking = ThinkingLevel::Medium;
let body = p.build_request_body(&req);
assert_eq!(body["reasoning"]["effort"], "medium");
assert_eq!(body["reasoning"]["summary"], "auto");
// Stateless reasoning replay: encrypted items, no server-side storage.
assert_eq!(body["store"], false);
assert_eq!(body["include"], serde_json::json!(["reasoning.encrypted_content"]));
}
#[test]
fn request_body_reasoning_model_off_still_enables_encrypted_replay() {
// Even at thinking=off, a reasoning model can emit reasoning we must be able to round-trip,
// so encrypted items + summary are requested (just without an explicit effort).
let p = make_provider();
let mut req = make_req("gpt-5");
req.model.reasoning = true;
req.thinking = ThinkingLevel::Off;
let body = p.build_request_body(&req);
assert_eq!(body["store"], false);
assert_eq!(body["include"], serde_json::json!(["reasoning.encrypted_content"]));
assert_eq!(body["reasoning"]["summary"], "auto");
assert!(body["reasoning"].get("effort").is_none(), "no effort at thinking=off");
}
#[test]
fn request_body_non_reasoning_model_no_reasoning() {
let p = make_provider();
let mut req = make_req("gpt-5");
req.model.reasoning = false;
req.thinking = ThinkingLevel::High;
let body = p.build_request_body(&req);
assert!(body.get("reasoning").is_none());
}
// -----------------------------------------------------------------------
// Input item building
// -----------------------------------------------------------------------
#[test]
fn input_user_message() {
let msgs = vec![Message::user("Hello")];
let items = build_input_items(&msgs, false);
assert_eq!(items.len(), 1);
assert_eq!(items[0]["role"], "user");
assert_eq!(items[0]["content"], "Hello");
}
/// Unlike chat-completions, `function_call_output.output` is `string | Array<input_text |
/// input_image | input_file>`, so the image rides inside the result and nothing is interleaved.
#[test]
fn a_tool_result_image_rides_inside_its_own_output_for_a_vision_model() {
let tool = Message {
role: Role::Tool,
content: vec![ContentBlock::ToolResult {
call_id: "call_1".into(),
content: vec![
ToolOutput::Text("quad.png: PNG".into()),
ToolOutput::Image {
data: "QUJD".into(),
mime: "image/png".into(),
name: Some("quad.png".into()),
},
],
is_error: false,
}],
};
let items = build_input_items(std::slice::from_ref(&tool), true);
assert_eq!(items.len(), 1, "no carrier item: this schema needs none");
assert_eq!(items[0]["type"], "function_call_output");
let parts = items[0]["output"].as_array().expect("the content-array form");
assert_eq!(parts[0]["type"], "input_text");
assert_eq!(parts[0]["text"], "quad.png: PNG");
assert_eq!(parts[1]["type"], "input_image");
assert_eq!(parts[1]["image_url"], "data:image/png;base64,QUJD");
// Text-only model: the plain string, and not one byte of base64.
let blind = build_input_items(&[tool], false);
assert_eq!(blind[0]["output"], "quad.png: PNG");
assert!(!blind[0].to_string().contains("QUJD"));
}
/// This path dropped user-attached images too — its `Role::User` arm only ever collected text,
/// so a `@screenshot.png` mention reached a Codex/ChatGPT session as nothing at all.
#[test]
fn a_user_attached_image_reaches_a_vision_model() {
let msg = Message {
role: Role::User,
content: vec![
ContentBlock::Text("what is this?".into()),
ContentBlock::Image {
data: "QUJD".into(),
mime: "image/png".into(),
name: Some("shot.png".into()),
},
],
};
let items = build_input_items(std::slice::from_ref(&msg), true);
let parts = items[0]["content"].as_array().expect("content parts");
assert_eq!(parts[0]["type"], "input_text");
assert_eq!(parts[0]["text"], "what is this?");
assert_eq!(parts[1]["type"], "input_image");
assert_eq!(parts[1]["image_url"], "data:image/png;base64,QUJD");
// Text-only: the string form it has always used, with the text intact.
let blind = build_input_items(&[msg], false);
assert_eq!(blind[0]["content"], "what is this?");
}
#[test]
fn input_assistant_text_message() {
let msg =
Message { role: Role::Assistant, content: vec![ContentBlock::Text("Hi there".into())] };
let items = build_input_items(&[msg], false);
assert_eq!(items.len(), 1);
assert_eq!(items[0]["role"], "assistant");
assert_eq!(items[0]["content"], "Hi there");
}
#[test]
fn input_replays_reasoning_item_before_its_function_call() {
// A reasoning turn: reasoning (summary + id + encrypted) then a tool call, then its result.
let assistant = Message {
role: Role::Assistant,
content: vec![
ContentBlock::Thinking {
text: "let me look".into(),
signature: None,
id: Some("rs_1".into()),
encrypted: Some("ENC==".into()),
opaque: None,
},
ContentBlock::ToolCall {
id: "call_1".into(),
name: "read".into(),
arguments: serde_json::json!({"path": "x"}),
},
],
};
let tool = Message {
role: Role::Tool,
content: vec![ContentBlock::ToolResult {
call_id: "call_1".into(),
content: vec![ToolOutput::Text("ok".into())],
is_error: false,
}],
};
let items = build_input_items(&[assistant, tool], false);
// Order preserved: reasoning → function_call → function_call_output.
assert_eq!(items[0]["type"], "reasoning");
assert_eq!(items[0]["id"], "rs_1");
assert_eq!(items[0]["encrypted_content"], "ENC==");
assert_eq!(items[0]["summary"][0]["type"], "summary_text");
assert_eq!(items[0]["summary"][0]["text"], "let me look");
assert_eq!(items[1]["type"], "function_call");
assert_eq!(items[1]["call_id"], "call_1");
assert_eq!(items[2]["type"], "function_call_output");
assert_eq!(items[2]["call_id"], "call_1");
}
#[test]
fn input_reasoning_without_summary_uses_empty_summary_array() {
let msg = Message {
role: Role::Assistant,
content: vec![ContentBlock::Thinking {
text: String::new(),
signature: None,
id: Some("rs_2".into()),
encrypted: Some("ENC2==".into()),
opaque: None,
}],
};
let items = build_input_items(&[msg], false);
assert_eq!(items.len(), 1);
assert_eq!(items[0]["type"], "reasoning");
assert_eq!(items[0]["summary"], serde_json::json!([]));
assert_eq!(items[0]["encrypted_content"], "ENC2==");
}
#[test]
fn input_skips_anthropic_thinking_on_responses_path() {
// Anthropic thinking (signature only, no id/encrypted) is not an OpenAI reasoning item.
let msg = Message {
role: Role::Assistant,
content: vec![
ContentBlock::Thinking {
text: "anthropic reasoning".into(),
signature: Some("SIG".into()),
id: None,
encrypted: None,
opaque: None,
},
ContentBlock::Text("answer".into()),
],
};
let items = build_input_items(&[msg], false);
assert!(
items.iter().all(|i| i["type"] != "reasoning"),
"cross-provider thinking is not replayed as an OpenAI reasoning item: {items:?}"
);
assert_eq!(items[0]["role"], "assistant");
assert_eq!(items[0]["content"], "answer");
}
#[test]
fn sse_captures_reasoning_summary_and_item() {
let text = concat!(
"event: response.reasoning_summary_text.delta\n",
"data: {\"output_index\":0,\"delta\":\"thinking...\"}\n\n",
"event: response.output_item.done\n",
"data: {\"output_index\":0,\"item\":{\"type\":\"reasoning\",\"id\":\"rs_9\",\"encrypted_content\":\"ENC==\",\"summary\":[]}}\n\n",
);
let events = parse_responses_sse(text);
assert!(
events.iter().any(|e| matches!(e, ProviderEvent::ThinkingDelta { index: 0, delta } if delta == "thinking...")),
"summary delta maps to ThinkingDelta at its output index: {events:?}"
);
assert!(
events.iter().any(|e| matches!(e, ProviderEvent::ReasoningItem { index: 0, id: Some(id), encrypted: Some(enc) } if id == "rs_9" && enc == "ENC==")),
"output_item.done reasoning maps to ReasoningItem with id + encrypted: {events:?}"
);
}
#[test]
fn input_assistant_tool_call() {
let msg = Message {
role: Role::Assistant,
content: vec![ContentBlock::ToolCall {
id: "call_abc".into(),
name: "read_file".into(),
arguments: serde_json::json!({"path": "foo.rs"}),
}],
};
let items = build_input_items(&[msg], false);
assert_eq!(items.len(), 1);
assert_eq!(items[0]["type"], "function_call");
assert_eq!(items[0]["call_id"], "call_abc");
assert_eq!(items[0]["name"], "read_file");
// Arguments are a JSON string.
assert!(items[0]["arguments"].is_string());
let args: serde_json::Value =
serde_json::from_str(items[0]["arguments"].as_str().unwrap()).unwrap();
assert_eq!(args["path"], "foo.rs");
}
#[test]
fn input_tool_result() {
let msg = Message {
role: Role::Tool,
content: vec![ContentBlock::ToolResult {
call_id: "call_abc".into(),
content: vec![ToolOutput::Text("file contents".into())],
is_error: false,
}],
};
let items = build_input_items(&[msg], false);
assert_eq!(items.len(), 1);
assert_eq!(items[0]["type"], "function_call_output");
assert_eq!(items[0]["call_id"], "call_abc");
assert_eq!(items[0]["output"], "file contents");
}
#[test]
fn input_multiple_tool_results_expand() {
let msg = Message {
role: Role::Tool,
content: vec![
ContentBlock::ToolResult {
call_id: "c1".into(),
content: vec![ToolOutput::Text("result A".into())],
is_error: false,
},
ContentBlock::ToolResult {
call_id: "c2".into(),
content: vec![ToolOutput::Text("result B".into())],
is_error: false,
},
],
};
let items = build_input_items(&[msg], false);
assert_eq!(items.len(), 2);
assert_eq!(items[0]["call_id"], "c1");
assert_eq!(items[1]["call_id"], "c2");
}
// -----------------------------------------------------------------------
// SSE parsing
// -----------------------------------------------------------------------
#[test]
fn sse_output_text_delta() {
let sse = "event: response.output_text.delta\ndata: {\"delta\":\"Hello, world!\"}\n\n";
let events = parse_responses_sse(sse);
assert_eq!(events.len(), 1);
assert!(
matches!(&events[0], ProviderEvent::TextDelta { index: 0, delta } if delta == "Hello, world!")
);
}

View File

@@ -0,0 +1,286 @@
//! SSE — events decoded and whole turns streamed.
use super::*;
#[test]
fn sse_function_call_added() {
let sse = concat!(
"event: response.output_item.added\n",
"data: {\"output_index\":2,\"item\":{\"type\":\"function_call\",",
"\"call_id\":\"call_xyz\",\"name\":\"bash\"}}\n\n"
);
let events = parse_responses_sse(sse);
assert_eq!(events.len(), 1);
assert!(matches!(&events[0],
ProviderEvent::ToolCallStart { index: 2, id, name }
if id == "call_xyz" && name == "bash"
));
}
#[test]
fn sse_function_call_arguments_delta() {
let sse = concat!(
"event: response.function_call_arguments.delta\n",
"data: {\"output_index\":2,\"delta\":\"{\\\"cmd\\\":\\\"ls\\\"}\"}\n\n"
);
let events = parse_responses_sse(sse);
assert_eq!(events.len(), 1);
assert!(matches!(&events[0],
ProviderEvent::ToolCallDelta { index: 2, json_delta }
if json_delta.contains("cmd")
));
}
#[test]
fn sse_tool_call_start_and_delta_same_index() {
// CRITICAL: ToolCallStart and ToolCallDelta must carry the same index.
let sse = concat!(
"event: response.output_item.added\n",
"data: {\"output_index\":3,\"item\":{\"type\":\"function_call\",",
"\"call_id\":\"call_99\",\"name\":\"read\"}}\n\n",
"event: response.function_call_arguments.delta\n",
"data: {\"output_index\":3,\"delta\":\"{\\\"path\\\":\\\"a.rs\\\"}\"}\n\n",
);
let events = parse_responses_sse(sse);
assert_eq!(events.len(), 2);
let start_index = match &events[0] {
ProviderEvent::ToolCallStart { index, .. } => *index,
other => panic!("expected ToolCallStart, got {other:?}"),
};
let delta_index = match &events[1] {
ProviderEvent::ToolCallDelta { index, .. } => *index,
other => panic!("expected ToolCallDelta, got {other:?}"),
};
assert_eq!(
start_index, delta_index,
"ToolCallStart and ToolCallDelta must share the same index"
);
}
#[test]
fn sse_non_function_call_output_item_skipped() {
// output_item.added where item.type != "function_call" should be silently ignored.
let sse = concat!(
"event: response.output_item.added\n",
"data: {\"output_index\":0,\"item\":{\"type\":\"message\",\"id\":\"msg_1\"}}\n\n"
);
let events = parse_responses_sse(sse);
assert!(events.is_empty());
}
#[test]
fn sse_reasoning_summary_delta() {
let sse = "event: response.reasoning_summary_text.delta\ndata: {\"delta\":\"thinking...\"}\n\n";
let events = parse_responses_sse(sse);
assert_eq!(events.len(), 1);
assert!(
matches!(&events[0], ProviderEvent::ThinkingDelta { index: 0, delta } if delta == "thinking...")
);
}
/// A summary that arrives in several parts is several paragraphs, and the deltas carry no
/// separator between them — so concatenating them ran the end of one into the start of the
/// next. The break goes before every part but the first, or each reasoning block would open
/// with a blank line.
#[test]
fn sse_reasoning_summary_parts_are_separated_but_never_led_by_a_break() {
let sse = concat!(
"event: response.reasoning_summary_part.added
",
"data: {\"output_index\":0,\"summary_index\":0}
",
"event: response.reasoning_summary_text.delta
",
"data: {\"output_index\":0,\"delta\":\"First, the parser.\"}
",
"event: response.reasoning_summary_part.added
",
"data: {\"output_index\":0,\"summary_index\":1}
",
"event: response.reasoning_summary_text.delta
",
"data: {\"output_index\":0,\"delta\":\"Then the writer.\"}
",
);
let thinking: String = parse_responses_sse(sse)
.iter()
.filter_map(|event| match event {
ProviderEvent::ThinkingDelta { delta, .. } => Some(delta.clone()),
_ => None,
})
.collect();
assert_eq!(thinking, "First, the parser.\n\nThen the writer.");
assert!(!thinking.starts_with('\n'), "the first part opens the block: {thinking:?}");
}
#[test]
fn sse_completed_end_turn() {
let sse = concat!(
"event: response.completed\n",
"data: {\"response\":{\"usage\":{\"input_tokens\":10,\"output_tokens\":5},",
"\"output\":[{\"type\":\"message\"}]}}\n\n"
);
let events = parse_responses_sse(sse);
assert_eq!(events.len(), 2); // Usage + Done
assert!(
matches!(&events[0], ProviderEvent::Usage(u) if u.prompt_tokens == 10 && u.completion_tokens == 5 && u.total_tokens == 15)
);
assert!(matches!(&events[1], ProviderEvent::Done { reason: StopReason::EndTurn }));
}
#[test]
fn sse_completed_tool_call() {
let sse = concat!(
"event: response.completed\n",
"data: {\"response\":{\"usage\":{\"input_tokens\":20,\"output_tokens\":8},",
"\"output\":[{\"type\":\"function_call\"}]}}\n\n"
);
let events = parse_responses_sse(sse);
assert_eq!(events.len(), 2); // Usage + Done
assert!(matches!(&events[1], ProviderEvent::Done { reason: StopReason::ToolCall }));
}
#[test]
fn sse_completed_no_usage() {
let sse = "event: response.completed\ndata: {\"response\":{\"output\":[]}}\n\n";
let events = parse_responses_sse(sse);
assert_eq!(events.len(), 1); // Just Done, no Usage
assert!(matches!(&events[0], ProviderEvent::Done { reason: StopReason::EndTurn }));
}
#[test]
fn sse_usage_captures_cache_and_reasoning_details() {
let sse = concat!(
"event: response.completed\n",
"data: {\"response\":{\"usage\":{\"input_tokens\":2000,\"output_tokens\":300,",
"\"input_tokens_details\":{\"cached_tokens\":1500},",
"\"output_tokens_details\":{\"reasoning_tokens\":250}},\"output\":[]}}\n\n",
);
let events = parse_responses_sse(sse);
let usage = events
.iter()
.find_map(|e| match e {
ProviderEvent::Usage(u) => Some(u),
_ => None,
})
.expect("a Usage event");
assert_eq!(usage.prompt_tokens, 2000);
assert_eq!(usage.cache_read_tokens, 1500);
assert_eq!(usage.reasoning_tokens, 250);
}
/// A write to the cache is billed, so it has to be read off the usage block rather than
/// assumed absent. The literal is a real `gpt-6-luna` response's usage, from the harness eval's
/// meter: it was priced as plain input, and the session's cost came out short.
#[test]
fn a_cache_write_is_read_off_the_responses_usage() {
let sse = concat!(
"event: response.completed\n",
"data: {\"response\":{\"usage\":{\"input_tokens\": 7196, \"input_tokens_details\": ",
"{\"cache_write_tokens\": 128, \"cached_tokens\": 7065}, \"output_tokens\": 46, ",
"\"output_tokens_details\": {\"reasoning_tokens\": 0}, \"total_tokens\": 7242},",
"\"output\":[]}}\n\n",
);
let usage = parse_responses_sse(sse)
.into_iter()
.find_map(|e| match e {
ProviderEvent::Usage(u) => Some(u),
_ => None,
})
.expect("a Usage event");
assert_eq!((usage.cache_read_tokens, usage.cache_write_tokens), (7065, 128));
assert_eq!(usage.prompt_tokens, 7196, "the prompt still counts everything it held");
}
#[test]
fn sse_error_event() {
let sse = "event: error\ndata: {\"message\":\"rate limit exceeded\"}\n\n";
let events = parse_responses_sse(sse);
assert_eq!(events.len(), 1);
assert!(
matches!(&events[0], ProviderEvent::Error { message, .. } if message == "rate limit exceeded")
);
}
#[test]
fn sse_response_failed() {
let sse = concat!(
"event: response.failed\n",
"data: {\"response\":{\"error\":{\"message\":\"model overloaded\"}}}\n\n"
);
let events = parse_responses_sse(sse);
assert_eq!(events.len(), 1);
assert!(
matches!(&events[0], ProviderEvent::Error { message, .. } if message == "model overloaded")
);
}
#[test]
fn sse_unknown_event_type_ignored() {
let sse = "event: response.some.future.event\ndata: {\"foo\":\"bar\"}\n\n";
let events = parse_responses_sse(sse);
assert!(events.is_empty());
}
#[test]
fn sse_full_turn_stream() {
// Simulate a complete text-only turn.
let sse = concat!(
"event: response.output_text.delta\n",
"data: {\"delta\":\"Hello\"}\n\n",
"event: response.output_text.delta\n",
"data: {\"delta\":\", world!\"}\n\n",
"event: response.completed\n",
"data: {\"response\":{\"usage\":{\"input_tokens\":5,\"output_tokens\":3},",
"\"output\":[{\"type\":\"message\"}]}}\n\n",
);
let events = parse_responses_sse(sse);
// TextDelta("Hello"), TextDelta(", world!"), Usage, Done
assert_eq!(events.len(), 4);
assert!(matches!(&events[0], ProviderEvent::TextDelta { delta, .. } if delta == "Hello"));
assert!(matches!(&events[1], ProviderEvent::TextDelta { delta, .. } if delta == ", world!"));
assert!(matches!(&events[2], ProviderEvent::Usage(_)));
assert!(matches!(&events[3], ProviderEvent::Done { reason: StopReason::EndTurn }));
}
#[test]
fn sse_full_tool_call_stream() {
// Simulate a turn that ends with a tool call.
let sse = concat!(
"event: response.output_item.added\n",
"data: {\"output_index\":0,\"item\":{\"type\":\"function_call\",",
"\"call_id\":\"call_1\",\"name\":\"bash\"}}\n\n",
"event: response.function_call_arguments.delta\n",
"data: {\"output_index\":0,\"delta\":\"{\\\"cmd\\\":\\\"ls\\\"}\"}\n\n",
"event: response.completed\n",
"data: {\"response\":{\"usage\":{\"input_tokens\":10,\"output_tokens\":4},",
"\"output\":[{\"type\":\"function_call\"}]}}\n\n",
);
let events = parse_responses_sse(sse);
// ToolCallStart, ToolCallDelta, Usage, Done(ToolCall)
assert_eq!(events.len(), 4);
assert!(
matches!(&events[0], ProviderEvent::ToolCallStart { index: 0, id, name } if id == "call_1" && name == "bash")
);
assert!(matches!(&events[1], ProviderEvent::ToolCallDelta { index: 0, .. }));
assert!(matches!(&events[2], ProviderEvent::Usage(_)));
assert!(matches!(&events[3], ProviderEvent::Done { reason: StopReason::ToolCall }));
}
// -----------------------------------------------------------------------
// In-place tool loading
// -----------------------------------------------------------------------
pub(super) fn schema(name: &str) -> ToolSchema {
ToolSchema {
name: name.to_string(),
description: format!("The {name} tool."),
parameters: serde_json::json!({"type": "object", "properties": {}}),
}
}

View File

@@ -0,0 +1,39 @@
//! Support — the provider and request every test here starts from.
use super::*;
pub(super) fn make_provider() -> OpenaiResponsesProvider {
OpenaiResponsesProvider::new(ProviderConfig {
api_key: Some("sk-test".into()),
base_url: Some("https://api.openai.com/v1".into()),
..Default::default()
})
}
pub(super) fn make_req(model_id: &str) -> CompletionRequest {
CompletionRequest {
model: ModelInfo { r#ref: ModelRef::new("openai", model_id), ..Default::default() },
messages: vec![Message::user("Hello")],
system: None,
tools: vec![],
thinking: ThinkingLevel::Off,
max_tokens: None,
..Default::default()
}
}
// -----------------------------------------------------------------------
// Codex flavour
// -----------------------------------------------------------------------
/// Header names and shapes taken verbatim from a live ChatGPT Plus response (2026-08-05).
pub(super) fn codex_headers(pairs: &[(&str, &str)]) -> reqwest::header::HeaderMap {
let mut headers = reqwest::header::HeaderMap::new();
for (name, value) in pairs {
headers.insert(
reqwest::header::HeaderName::from_bytes(name.as_bytes()).unwrap(),
reqwest::header::HeaderValue::from_str(value).unwrap(),
);
}
headers
}

View File

@@ -0,0 +1,102 @@
//! What each adapter makes of a provider's error: the status first, then the provider's own error
//! type, and only then its words.
#![allow(clippy::unwrap_used)]
use luxe_core::provider::{ProviderErrorKind as Kind, ProviderEvent};
use crate::sse::SseDecoder;
/// Every status lands on one kind, whatever the body says beside it.
///
/// The break this catches: the five adapters' error paths each wrote `"{status}: {body}"` into
/// one string, which core then searched for numbers — so a 400 quoting "130401 tokens" was an
/// auth failure, and only two of three adapters made a 401 an auth error at all.
#[test]
fn a_status_decides_the_kind() {
let rows = [
(401, "{}", Kind::Auth),
(403, "{}", Kind::Auth),
(429, "{}", Kind::RateLimit),
(500, "{}", Kind::Unavailable),
(529, "{\"type\":\"overloaded_error\"}", Kind::Unavailable),
(400, "prompt is too long: 130401 tokens > 128000 maximum context", Kind::Overflow),
(400, "{\"type\":\"invalid_request_error\"}", Kind::Other("provider".into())),
];
for (status, body, kind) in rows {
let status = reqwest::StatusCode::from_u16(status).unwrap();
assert_eq!(crate::http::status_error(status, body.into()).kind(), kind, "{status}");
}
}
/// The kind an error event carries, and nothing else.
fn kind_of(events: &[ProviderEvent]) -> Kind {
match events {
[ProviderEvent::Error { kind, .. }] => kind.clone(),
other => panic!("one error event, not {other:?}"),
}
}
/// A chat-completions error frame takes its kind from its `type`, or its `code`, whichever names
/// something, and a numeric code is read as the status it is.
///
/// The break this catches: the frame's type was stored as an opaque string kind, so what the
/// engine made of an error rode on its wording.
#[test]
fn a_compat_error_frame_is_typed() {
let decode = |frame: &str| {
let mut events = Vec::new();
crate::openai_compat::CompatDecoder::default().record(frame, &mut events);
kind_of(&events)
};
let overloaded = r#"data: {"error":{"message":"Overloaded","type":"overloaded_error"}}"#;
assert_eq!(decode(overloaded), Kind::Unavailable);
let limited = r#"data: {"error":{"message":"slow down","code":"rate_limit_exceeded"}}"#;
assert_eq!(decode(limited), Kind::RateLimit);
let quota = r#"data: {"error":{"message":"no","type":"insufficient_quota"}}"#;
assert_eq!(decode(quota), Kind::Other("insufficient_quota".into()));
// OpenAI's own overflow frame: the type says nothing, the code does
let overflow = r#"data: {"error":{"message":"too long","type":"invalid_request_error","code":"context_length_exceeded"}}"#;
assert_eq!(decode(overflow), Kind::Overflow);
}
/// A numeric `code`, as vLLM and llama.cpp send, is a status, and the frame still parses.
///
/// The break this catches: `code` was read as a string, so a frame carrying a number failed to
/// parse at all, was dropped, and the turn ended as though it had finished.
#[test]
fn a_numeric_error_code_is_read_as_a_status() {
let decode = |frame: &str| {
let mut events = Vec::new();
crate::openai_compat::CompatDecoder::default().record(frame, &mut events);
kind_of(&events)
};
assert_eq!(decode(r#"data: {"error":{"message":"slow down","code":429}}"#), Kind::RateLimit);
let long = r#"data: {"error":{"message":"maximum context length is 8192","code":400}}"#;
assert_eq!(decode(long), Kind::Overflow);
let events = crate::openai_responses::parse_responses_sse(
"event: error\ndata: {\"code\":503,\"message\":\"busy\"}\n\n",
);
assert_eq!(kind_of(&events), Kind::Unavailable);
}
/// A Responses API error event takes its kind from its `code`.
#[test]
fn a_responses_error_event_is_typed() {
let events = crate::openai_responses::parse_responses_sse(
"event: error\ndata: {\"code\":\"server_error\",\"message\":\"try again\"}\n\n",
);
assert_eq!(kind_of(&events), Kind::Unavailable);
// An older capture put `response.failed`'s error at the top
let events = crate::openai_responses::parse_responses_sse(
"event: response.failed\ndata: {\"error\":{\"code\":\"server_error\",\"message\":\"m\"}}\n\n",
);
let [ProviderEvent::Error { kind, message }] = &events[..] else { panic!("{events:?}") };
assert_eq!((kind, message.as_str()), (&Kind::Unavailable, "m"));
// `response.failed` carries its error inside the response it failed
let events = crate::openai_responses::parse_responses_sse(
"event: response.failed\ndata: {\"response\":{\"status\":\"failed\",\"error\":{\"code\":\"rate_limit_exceeded\",\"message\":\"x\"}}}\n\n",
);
let [ProviderEvent::Error { kind, message }] = &events[..] else { panic!("{events:?}") };
assert_eq!((kind, message.as_str()), (&Kind::RateLimit, "x"));
}

View File

@@ -0,0 +1,109 @@
//! Sampling passthrough — a model's declared sampler recipe, merged into the request body.
//!
//! Modern open-weight models ship a *required* sampling recipe rather than a suggestion, and
//! three of the keys a typical one names (`top_k`, `min_p`, `repeat_penalty`) have no field in the
//! OpenAI wire schema. Worse, the defaults are not neutral: llama.cpp's `min_p` is `0.05`, so a
//! request that simply omits it runs the model off-spec on every turn. So the map is passthrough,
//! not a modelled set of options — Luxe carries whatever the server understands and validates none
//! of it.
//!
//! OpenAI-shaped bodies only. Anthropic has no equivalent surface and ignores it.
use serde_json::{Map, Value};
use tracing::warn;
/// Fields a sampling map may not set, because they decide *what request this is* rather than how
/// it samples. Silently overwriting `stream` leaves the SSE reader waiting on a body that will
/// never stream, which is a hang with no diagnostic.
const RESERVED: [&str; 5] = ["model", "messages", "input", "stream", "tools"];
/// Merge a model's sampling parameters into a request body, last, so its keys win.
///
/// Called after every field the adapter sets itself — `temperature`, the output cap, the thinking
/// payload — which is the whole point: a model card's recipe is the final word on how that model
/// is sampled, and a key here beats whatever Luxe would otherwise have sent.
pub(crate) fn apply(body: &mut Value, params: &Map<String, Value>) {
if params.is_empty() {
return;
}
let Some(body) = body.as_object_mut() else { return };
for (key, value) in params {
if RESERVED.contains(&key.as_str()) {
warn!(key, "ignoring a reserved key in sampling_params");
continue;
}
body.insert(key.clone(), value.clone());
}
}
#[cfg(test)]
mod tests {
use super::*;
fn params(json: Value) -> Map<String, Value> {
match json {
Value::Object(map) => map,
_ => unreachable!("fixture is an object"),
}
}
/// The keys that have no OpenAI field are exactly the reason this exists, so they have to
/// arrive verbatim — unrecognized names and all.
#[test]
fn unmodelled_samplers_reach_the_body_untouched() {
let mut body = serde_json::json!({ "model": "qwen3.8-27b", "temperature": 0.2 });
apply(
&mut body,
&params(serde_json::json!({
"temperature": 1.0, "top_p": 0.95, "top_k": 20,
"min_p": 0.0, "repeat_penalty": 1.0, "mirostat_tau": 5,
})),
);
assert_eq!(body["temperature"], 1.0, "the recipe outranks what Luxe set");
assert_eq!(body["top_k"], 20);
assert_eq!(body["min_p"], 0.0);
assert_eq!(body["repeat_penalty"], 1.0);
assert_eq!(body["mirostat_tau"], 5, "nothing is validated; unknown keys pass through");
}
/// `min_p: 0` is the case that motivated the whole feature: llama.cpp's default is 0.05, so an
/// omitted key is not a neutral one. A falsy value must survive the merge.
#[test]
fn a_zero_is_a_value_not_an_absence() {
let mut body = serde_json::json!({});
apply(&mut body, &params(serde_json::json!({ "min_p": 0.0, "presence_penalty": 0 })));
assert_eq!(body["min_p"], 0.0);
assert_eq!(body["presence_penalty"], 0);
}
/// A sampling map is not a way to rewrite the request. Turning off `stream` would leave the
/// SSE reader waiting forever on a body that never streams.
#[test]
fn the_fields_that_decide_what_request_this_is_are_refused() {
let mut body = serde_json::json!({
"model": "real", "messages": ["real"], "stream": true, "tools": ["real"],
});
apply(
&mut body,
&params(serde_json::json!({
"model": "other", "messages": [], "input": [], "stream": false,
"tools": [], "top_k": 20,
})),
);
assert_eq!(body["model"], "real");
assert_eq!(body["messages"], serde_json::json!(["real"]));
assert_eq!(body["stream"], true);
assert_eq!(body["tools"], serde_json::json!(["real"]));
assert!(body.get("input").is_none());
assert_eq!(body["top_k"], 20, "the rest of the map still applies");
}
#[test]
fn an_empty_map_changes_nothing() {
let mut body = serde_json::json!({ "model": "m" });
apply(&mut body, &Map::new());
assert_eq!(body, serde_json::json!({ "model": "m" }));
}
}

View File

@@ -0,0 +1,269 @@
//! Incremental SSE decode — turn a live HTTP body into `ProviderEvent`s as bytes arrive.
//!
//! Every adapter here speaks server-sent events, and reading the *whole* response before parsing it
//! would make streaming a lie: reasoning and answer text would reach the UI together, at the end
//! of the call, and a cancel could not interrupt a provider call because nothing was being read.
//!
//! [`decode`] gives all three adapters that shape once. It buffers the body, cuts complete
//! `\n\n`-delimited records off the front, and hands each to an [`SseDecoder`] whose events are
//! yielded immediately. Cross-record state (Anthropic's split usage, the OpenAI-compat
//! `Usage`-before-`Done` ordering) lives in the decoder, which is why this is a trait and not a
//! function pointer.
use futures::stream::{BoxStream, Stream, StreamExt};
use luxe_core::provider::ProviderEvent;
use std::collections::VecDeque;
use tokio::sync::watch;
/// Per-provider translation of SSE records into `ProviderEvent`s.
///
/// Implementors are fed one complete record at a time, in order, and may keep whatever state the
/// wire format needs between records.
pub(crate) trait SseDecoder {
/// Decodes one SSE record (event/data lines, no trailing blank line), appending its events.
fn record(&mut self, record: &str, out: &mut Vec<ProviderEvent>);
/// Called once after the last record, for anything the decoder was holding back.
fn finish(&mut self, _out: &mut Vec<ProviderEvent>) {}
}
/// Streams `body` through `decoder`, yielding each `ProviderEvent` as soon as its record arrives.
///
/// A flipped `cancel` watch drops the body mid-flight, which is what actually aborts an in-flight
/// provider call; a transport error surfaces as a terminal `ProviderEvent::Error`.
pub(crate) fn decode<S, B, D>(
body: S,
cancel: watch::Receiver<bool>,
decoder: D,
) -> BoxStream<'static, ProviderEvent>
where
S: Stream<Item = Result<B, reqwest::Error>> + Send + 'static,
B: AsRef<[u8]> + Send + 'static,
D: SseDecoder + Send + 'static,
{
let state = DecodeState {
body: Box::pin(body),
buffer: String::new(),
pending: VecDeque::new(),
decoder,
cancel,
drained: false,
};
futures::stream::unfold(state, |mut state| async move {
loop {
if let Some(event) = state.pending.pop_front() {
return Some((event, state));
}
if state.drained {
return None;
}
state.pump().await;
}
})
.boxed()
}
struct DecodeState<S, D> {
body: std::pin::Pin<Box<S>>,
/// Bytes received but not yet forming a complete record.
buffer: String,
pending: VecDeque<ProviderEvent>,
decoder: D,
cancel: watch::Receiver<bool>,
drained: bool,
}
impl<S, B, D> DecodeState<S, D>
where
S: Stream<Item = Result<B, reqwest::Error>> + Send,
B: AsRef<[u8]>,
D: SseDecoder,
{
/// Reads one chunk (or notices the end/cancel) and queues whatever it decoded.
async fn pump(&mut self) {
if *self.cancel.borrow_and_update() {
return self.finish();
}
let quiet = async {
match crate::http::idle_timeout() {
Some(limit) => tokio::time::sleep(limit).await,
None => std::future::pending().await,
}
};
let chunk = tokio::select! {
chunk = self.body.next() => chunk,
// Cancelling has to interrupt the *read*, not just be noticed between chunks: a
// provider that has gone quiet mid-turn would otherwise hold the turn open.
_ = self.cancel.changed() => None,
() = quiet => {
let limit = crate::http::idle_timeout().map_or(0, |limit| limit.as_secs());
self.pending.push_back(ProviderEvent::Error {
message: format!("stream error: timed out after {limit}s with nothing from the provider"),
kind: luxe_core::provider::ProviderErrorKind::Transport,
});
self.drained = true;
return;
}
};
match chunk {
Some(Ok(bytes)) => {
// Lossy is right here: a split multi-byte character can only be repaired by the
// next chunk, and `\n\n` boundaries are ASCII, so records still cut correctly.
self.buffer.push_str(&String::from_utf8_lossy(bytes.as_ref()));
let mut events = Vec::new();
for record in take_records(&mut self.buffer) {
self.decoder.record(&record, &mut events);
}
self.pending.extend(events);
}
Some(Err(error)) => {
self.pending.push_back(ProviderEvent::Error {
message: format!("stream error: {error}"),
kind: luxe_core::provider::ProviderErrorKind::Transport,
});
self.drained = true;
}
None => self.finish(),
}
}
/// Flushes a trailing partial record and lets the decoder emit anything it held back.
fn finish(&mut self) {
let mut events = Vec::new();
let tail = std::mem::take(&mut self.buffer);
if !tail.trim().is_empty() {
self.decoder.record(&tail, &mut events);
}
self.decoder.finish(&mut events);
self.pending.extend(events);
self.drained = true;
}
}
/// Splits every complete record off the front of `buffer`, leaving the partial tail behind.
///
/// SSE separates records with a blank line. `\r\n\r\n` is accepted too — some proxies rewrite line
/// endings — and the `\r`s are trimmed by the per-line parsers downstream.
fn take_records(buffer: &mut String) -> Vec<String> {
let mut records = Vec::new();
loop {
let boundary = buffer
.find("\n\n")
.map(|at| (at, 2))
.or_else(|| buffer.find("\r\n\r\n").map(|at| (at, 4)));
let Some((at, width)) = boundary else { return records };
let record: String = buffer.drain(..at + width).collect();
records.push(record[..at].to_string());
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Records every record it is handed, and emits one text delta per record.
#[derive(Default)]
struct EchoDecoder {
seen: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
finished: bool,
}
impl SseDecoder for EchoDecoder {
fn record(&mut self, record: &str, out: &mut Vec<ProviderEvent>) {
self.seen.lock().expect("lock").push(record.to_string());
out.push(ProviderEvent::TextDelta { index: 0, delta: record.to_string() });
}
fn finish(&mut self, out: &mut Vec<ProviderEvent>) {
self.finished = true;
out.push(ProviderEvent::Done { reason: luxe_core::provider::StopReason::EndTurn });
}
}
/// A body that sends one record and then nothing, ever: the stream ends with a timeout a retry
/// can recognize, rather than holding the turn open.
#[tokio::test(start_paused = true)]
async fn a_stream_that_goes_quiet_times_out() {
let first = futures::stream::iter([Ok::<_, reqwest::Error>(b"data: a\n\n".to_vec())]);
let body = first.chain(futures::stream::pending());
let (_cancel_tx, cancel) = watch::channel(false);
let started = tokio::time::Instant::now();
let events: Vec<ProviderEvent> =
decode(body, cancel, EchoDecoder::default()).collect().await;
assert!(matches!(&events[0], ProviderEvent::TextDelta { delta, .. } if delta == "data: a"));
let ProviderEvent::Error { message, kind } = &events[1] else { panic!("{events:?}") };
assert_eq!(*kind, luxe_core::provider::ProviderErrorKind::Transport);
assert!(message.contains("timed out after 180s"), "{message}");
assert_eq!(events.len(), 2, "and that is the end of it");
assert_eq!(started.elapsed(), crate::http::IDLE_TIMEOUT);
}
fn chunks(
parts: &[&str],
) -> impl Stream<Item = Result<Vec<u8>, reqwest::Error>> + Send + 'static {
let owned: Vec<Vec<u8>> = parts.iter().map(|part| part.as_bytes().to_vec()).collect();
futures::stream::iter(owned.into_iter().map(Ok))
}
#[test]
fn records_are_cut_on_blank_lines_and_the_tail_is_kept() {
let mut buffer = String::from("event: a\ndata: 1\n\nevent: b\ndata: 2\n\nevent: c\ndata:");
let records = take_records(&mut buffer);
assert_eq!(records, vec!["event: a\ndata: 1", "event: b\ndata: 2"]);
assert_eq!(buffer, "event: c\ndata:");
}
#[test]
fn crlf_record_separators_are_accepted() {
let mut buffer = String::from("event: a\r\ndata: 1\r\n\r\nrest");
assert_eq!(take_records(&mut buffer), vec!["event: a\r\ndata: 1"]);
assert_eq!(buffer, "rest");
}
/// The point of the whole module: a record that arrives split across chunks is decoded as soon
/// as its final byte lands, not when the body ends.
#[tokio::test]
async fn a_record_split_across_chunks_decodes_once_completed() {
let (_tx, cancel) = watch::channel(false);
let decoder = EchoDecoder::default();
let seen = decoder.seen.clone();
let mut stream =
decode(chunks(&["data: he", "llo\n\ndata: wor", "ld\n\n"]), cancel, decoder);
let first = stream.next().await;
assert!(
matches!(first, Some(ProviderEvent::TextDelta { ref delta, .. }) if delta == "data: hello")
);
assert_eq!(seen.lock().expect("lock").len(), 1, "only the completed record was decoded");
let second = stream.next().await;
assert!(
matches!(second, Some(ProviderEvent::TextDelta { ref delta, .. }) if delta == "data: world")
);
}
#[tokio::test]
async fn a_trailing_partial_record_is_flushed_at_the_end() {
let (_tx, cancel) = watch::channel(false);
let mut stream =
decode(chunks(&["data: one\n\ndata: two"]), cancel, EchoDecoder::default());
let mut deltas = Vec::new();
while let Some(event) = stream.next().await {
if let ProviderEvent::TextDelta { delta, .. } = event {
deltas.push(delta);
}
}
assert_eq!(deltas, vec!["data: one", "data: two"]);
}
#[tokio::test]
async fn a_cancelled_stream_stops_reading() {
let (tx, cancel) = watch::channel(false);
tx.send(true).expect("cancel");
let mut stream = decode(chunks(&["data: one\n\n"]), cancel, EchoDecoder::default());
// Only the decoder's finish output survives — no records were read.
let events: Vec<_> = stream.by_ref().collect().await;
assert_eq!(events.len(), 1, "cancelled before the first record: {events:?}");
assert!(matches!(events[0], ProviderEvent::Done { .. }));
}
}

View File

@@ -0,0 +1,112 @@
//! Test server — the one canned HTTP/1.1 server the adapters' tests talk to.
//!
//! A mock that parses requests its own way is a place a test can pass for the wrong reason, so
//! the request is read once, verbatim, by [`read_http_request`], and every test sees the same
//! thing: the request line, the headers and the whole `Content-Length` body as text.
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::thread::JoinHandle;
/// Reads one whole HTTP request (headers and `Content-Length` body) off `sock`, verbatim.
pub(crate) fn read_http_request(sock: &mut TcpStream) -> String {
let mut buf = Vec::new();
let mut tmp = [0u8; 4096];
loop {
let n = sock.read(&mut tmp).unwrap_or(0);
if n == 0 {
break;
}
buf.extend_from_slice(&tmp[..n]);
let text = String::from_utf8_lossy(&buf);
if let Some(head_end) = text.find("\r\n\r\n") {
let content_len = text
.lines()
.find_map(|line| {
line.to_ascii_lowercase()
.strip_prefix("content-length:")
.map(|v| v.trim().parse::<usize>().unwrap_or(0))
})
.unwrap_or(0);
if buf.len() >= head_end + 4 + content_len {
break;
}
}
}
String::from_utf8_lossy(&buf).to_string()
}
/// The body of a request [`read_http_request`] returned.
pub(crate) fn request_body(raw: &str) -> &str {
raw.split_once("\r\n\r\n").map_or("", |(_, body)| body)
}
/// One canned HTTP reply.
///
/// `Connection: close` keeps each request on its own socket, so a mock serving several replies
/// isn't left waiting on `accept` while the client reuses the first.
pub(crate) fn http_reply(status: &str, content_type: &str, body: &str) -> String {
format!(
"HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
}
/// A server on a loopback port, answering each reply it was given once, in order.
pub(crate) struct MockServer {
port: u16,
handle: JoinHandle<Vec<String>>,
}
impl MockServer {
/// The port it listens on
pub(crate) fn port(&self) -> u16 {
self.port
}
/// Waits for the last reply to go out and returns every request it saw, verbatim.
pub(crate) fn requests(self) -> Vec<String> {
self.handle.join().expect("the mock server thread")
}
}
/// Starts a server that answers `replies` in order, one per connection.
pub(crate) fn serve_replies(replies: Vec<String>) -> MockServer {
let listener = TcpListener::bind("127.0.0.1:0").expect("a loopback port");
let port = listener.local_addr().expect("an address").port();
let handle = std::thread::spawn(move || {
let mut seen = Vec::new();
for reply in replies {
let Ok((mut sock, _)) = listener.accept() else { break };
seen.push(read_http_request(&mut sock));
let _ = sock.write_all(reply.as_bytes());
let _ = sock.flush();
}
seen
});
MockServer { port, handle }
}
/// Starts a server that answers one request with `status`, `content_type` and `body`.
pub(crate) fn serve_once(status: &str, content_type: &str, body: &str) -> MockServer {
serve_replies(vec![http_reply(status, content_type, body)])
}
/// Starts a server that writes `reply` as is — no length, no close — and keeps the socket open
/// until the returned sender fires, the way a proxy that holds a connection after the last event
/// does.
pub(crate) fn serve_held_open(reply: &str) -> (MockServer, std::sync::mpsc::Sender<()>) {
let listener = TcpListener::bind("127.0.0.1:0").expect("a loopback port");
let port = listener.local_addr().expect("an address").port();
let (release, held) = std::sync::mpsc::channel::<()>();
let reply = reply.to_owned();
let handle = std::thread::spawn(move || {
let Ok((mut sock, _)) = listener.accept() else { return Vec::new() };
let seen = read_http_request(&mut sock);
let _ = sock.write_all(reply.as_bytes());
let _ = sock.flush();
let _ = held.recv_timeout(std::time::Duration::from_secs(30));
vec![seen]
});
(MockServer { port, handle }, release)
}

View File

@@ -0,0 +1,462 @@
//! Wire log — an opt-in, on-disk record of everything Luxe sends to a model and gets back.
//!
//! Set `LUXE_WIRE_LOG=<path>` and every provider call appends JSONL: the exact request body as it
//! goes on the wire (after provider-specific shaping — `cache_control` markers, tool schemas,
//! thinking config), the request headers with credential values redacted, and every normalized
//! [`ProviderEvent`] coming back. `luxe wire <path>` turns that into an audit report.
//!
//! Off unless the variable is set, and never fatal: a log that cannot be written is dropped with a
//! warning rather than failing a turn. The file is local — nothing here phones home.
//!
//! Requests are recorded by the adapters, the only place the final body exists; responses by
//! [`RecordingProvider`], which wraps any adapter and needs no per-provider knowledge. The two
//! halves are tied together by a call id the decorator puts in a task-local, so concurrent
//! sessions never interleave into one another's records.
use std::io::Write;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{SystemTime, UNIX_EPOCH};
use luxe_core::provider::{CompletionRequest, Provider, ProviderError, ProviderEvent};
/// Header names whose value is a credential and must never reach the log.
const SECRET_HEADERS: &[&str] =
&["authorization", "x-api-key", "api-key", "cookie", "proxy-authorization"];
/// The open log file, resolved once from the environment.
static SINK: OnceLock<Option<Mutex<std::fs::File>>> = OnceLock::new();
/// Monotonic provider-call counter.
static SEQ: AtomicU64 = AtomicU64::new(0);
tokio::task_local! {
/// The call id of the provider call this task is inside, set by [`RecordingProvider`].
static CALL_ID: u64;
}
fn sink() -> Option<&'static Mutex<std::fs::File>> {
SINK.get_or_init(|| {
let path = std::env::var("LUXE_WIRE_LOG").ok().filter(|path| !path.trim().is_empty())?;
let path = std::path::PathBuf::from(path);
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
match std::fs::OpenOptions::new().create(true).append(true).open(&path) {
Ok(file) => {
tracing::info!(path = %path.display(), "wire log enabled");
Some(Mutex::new(file))
}
Err(error) => {
tracing::warn!(path = %path.display(), %error, "wire log could not be opened");
None
}
}
})
.as_ref()
}
/// Whether wire logging is on. Cheap enough to guard every call site.
pub fn enabled() -> bool {
sink().is_some()
}
/// The call this task belongs to, or `0` for a provider used without the recording wrapper.
pub fn current_call_id() -> u64 {
CALL_ID.try_with(|id| *id).unwrap_or(0)
}
fn append(record: serde_json::Value) {
if let Some(sink) = sink() {
append_to(sink, &record);
}
}
/// Writes `record` to `sink`, saying once if it could not.
fn append_to(sink: &Mutex<impl Write>, record: &serde_json::Value) {
let written = match sink.lock() {
Ok(mut out) => write_record(&mut *out, record),
Err(_) => Err(std::io::Error::other("the log's lock was poisoned")),
};
if let Err(error) = written {
note_dropped(&error);
}
}
/// One record as one line.
fn write_record(out: &mut impl Write, record: &serde_json::Value) -> std::io::Result<()> {
let line = serde_json::to_string(record).map_err(std::io::Error::other)?;
writeln!(out, "{line}")
}
/// Whether the log has already said it is dropping records.
static DROPPING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Says, once, that the log is dropping records, so a cut-short capture does not pass for a
/// quiet run. Returns whether this call was the one that said it.
fn note_dropped(error: &dyn std::fmt::Display) -> bool {
let first = !DROPPING.swap(true, Ordering::Relaxed);
if first {
tracing::warn!(%error, "the wire log could not be written; later records may be missing");
}
first
}
fn now_ms() -> u128 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or_default()
}
/// Record one outgoing request exactly as it will be sent.
///
/// `headers` carries only what the adapter sets explicitly; credential header values become
/// `<redacted>`, and the body goes through the shared secret redactor in case a key reached the
/// prompt by some other route.
pub fn record_request(
provider: &str,
url: &str,
headers: &[(&str, &str)],
body: &serde_json::Value,
) {
if !enabled() {
return;
}
let headers: serde_json::Map<String, serde_json::Value> = headers
.iter()
.map(|(name, value)| {
let secret = SECRET_HEADERS.contains(&name.to_ascii_lowercase().as_str());
let value = if secret { "<redacted>" } else { *value };
((*name).to_string(), serde_json::Value::String(value.to_string()))
})
.collect();
let body = match serde_json::to_string(body) {
Ok(text) => serde_json::from_str(&luxe_core::redact::process_secrets().redact(&text))
.unwrap_or_else(|_| body.clone()),
Err(_) => body.clone(),
};
append(serde_json::json!({
"kind": "request",
"call": current_call_id(),
"ts_ms": now_ms(),
"provider": provider,
"url": url,
"headers": headers,
"body": body,
}));
}
/// Longest reply text kept verbatim; beyond this the record keeps the count and an excerpt.
const MAX_TEXT: usize = 4_000;
/// Longest tool-call argument payload kept verbatim.
const MAX_ARGS: usize = 2_000;
/// Most arrival samples kept, so a pathological stream can't unbound the record.
const MAX_ARRIVALS: usize = 2_000;
/// Accumulates one call's response into a single record.
///
/// One line per event would be one line per *token* — unreadable, and it would bury the structure
/// an audit is actually looking for. Instead the stream is folded into what came back (text, tool
/// calls, usage, stop reason) plus an arrival timeline of `[ms_offset, chars]` pairs, which is what
/// proves "renders as it arrives" without duplicating the text.
#[derive(Default)]
struct ResponseRecord {
counts: std::collections::BTreeMap<&'static str, u64>,
text: String,
thinking_chars: usize,
tool_calls: Vec<(String, String, String)>,
usage: Option<serde_json::Value>,
stop: Option<String>,
errors: Vec<String>,
arrival: Vec<(u128, usize)>,
first_delta_ms: Option<u128>,
}
impl ResponseRecord {
fn observe(&mut self, event: &ProviderEvent, elapsed_ms: u128) {
let kind = match event {
ProviderEvent::Start => "start",
ProviderEvent::TextStart { .. } => "text_start",
ProviderEvent::TextDelta { delta, .. } => {
if self.first_delta_ms.is_none() {
self.first_delta_ms = Some(elapsed_ms);
}
if self.text.len() < MAX_TEXT {
self.text.push_str(delta);
}
if self.arrival.len() < MAX_ARRIVALS {
self.arrival.push((elapsed_ms, delta.chars().count()));
}
"text_delta"
}
ProviderEvent::TextEnd { .. } => "text_end",
ProviderEvent::ThinkingStart { .. } => "thinking_start",
ProviderEvent::ThinkingDelta { delta, .. } => {
if self.first_delta_ms.is_none() {
self.first_delta_ms = Some(elapsed_ms);
}
self.thinking_chars += delta.chars().count();
if self.arrival.len() < MAX_ARRIVALS {
self.arrival.push((elapsed_ms, delta.chars().count()));
}
"thinking_delta"
}
ProviderEvent::ThinkingSignature { .. } => "thinking_signature",
ProviderEvent::ReasoningItem { .. } => "reasoning_item",
ProviderEvent::ReasoningOpaque { .. } => "reasoning_opaque",
ProviderEvent::RedactedThinking { .. } => "redacted_thinking",
ProviderEvent::ThinkingEnd { .. } => "thinking_end",
ProviderEvent::ToolCallStart { id, name, .. } => {
self.tool_calls.push((id.clone(), name.clone(), String::new()));
"tool_call_start"
}
ProviderEvent::ToolCallDelta { json_delta, .. } => {
if let Some(call) = self.tool_calls.last_mut() {
if call.2.len() < MAX_ARGS {
call.2.push_str(json_delta);
}
}
"tool_call_delta"
}
ProviderEvent::ToolCallEnd { .. } => "tool_call_end",
ProviderEvent::Usage(usage) => {
self.usage = Some(serde_json::json!({
"prompt_tokens": usage.prompt_tokens,
"completion_tokens": usage.completion_tokens,
"total_tokens": usage.total_tokens,
"cache_read_tokens": usage.cache_read_tokens,
"cache_write_tokens": usage.cache_write_tokens,
"reasoning_tokens": usage.reasoning_tokens,
}));
"usage"
}
ProviderEvent::PlanUsage(_) => "plan_usage",
ProviderEvent::Done { reason } => {
self.stop = Some(format!("{reason:?}"));
"done"
}
ProviderEvent::Error { message, kind } => {
self.errors.push(format!("{kind:?}: {message}"));
"error"
}
};
*self.counts.entry(kind).or_default() += 1;
}
fn finish(self, call: u64, provider: &str, elapsed_ms: u128, completed: bool) {
let text = luxe_core::redact::process_secrets().redact(&self.text);
append(serde_json::json!({
"kind": "response",
"call": call,
"ts_ms": now_ms(),
"provider": provider,
"elapsed_ms": elapsed_ms,
"first_delta_ms": self.first_delta_ms,
"drained": completed,
"events": self.counts,
"text": text,
"thinking_chars": self.thinking_chars,
"tool_calls": self.tool_calls.iter().map(|(id, name, args)| serde_json::json!({
"id": id,
"name": name,
"arguments": luxe_core::redact::process_secrets().redact(args),
})).collect::<Vec<_>>(),
"usage": self.usage,
"stop": self.stop,
"errors": self.errors,
"arrival": self.arrival,
}));
}
}
fn record_error(call: u64, provider: &str, error: &ProviderError) {
append(serde_json::json!({
"kind": "error",
"call": call,
"ts_ms": now_ms(),
"provider": provider,
"error": luxe_core::redact::process_secrets().redact(&error.to_string()),
}));
}
/// Wraps any provider and records the event stream it produces.
///
/// Provider-agnostic on purpose: it sees normalized [`ProviderEvent`]s, so a new adapter is logged
/// the day it exists. The request half lives in the adapters, which are the only place the final
/// wire body is known.
pub struct RecordingProvider {
inner: Arc<dyn Provider + Send + Sync>,
}
impl RecordingProvider {
/// Wrap `inner`, or hand it back untouched when logging is off.
pub fn wrap(inner: Arc<dyn Provider + Send + Sync>) -> Arc<dyn Provider + Send + Sync> {
if enabled() {
Arc::new(Self { inner })
} else {
inner
}
}
}
#[async_trait::async_trait]
impl Provider for RecordingProvider {
fn name(&self) -> &str {
self.inner.name()
}
async fn stream(
&self,
req: CompletionRequest,
cancel: tokio::sync::watch::Receiver<bool>,
) -> Result<futures::stream::BoxStream<'static, ProviderEvent>, ProviderError> {
let call = SEQ.fetch_add(1, Ordering::Relaxed);
let provider = self.inner.name().to_string();
let started = std::time::Instant::now();
// The adapter records its request from inside this scope, so both halves share `call`.
let stream = match CALL_ID.scope(call, self.inner.stream(req, cancel)).await {
Ok(stream) => stream,
Err(error) => {
record_error(call, &provider, &error);
return Err(error);
}
};
Ok(Box::pin(Recording {
inner: stream,
open: Some(OpenRecord { call, provider, started, record: ResponseRecord::default() }),
}))
}
// Forwarded, or wrapping a provider for the log would quietly switch its cache warming off
fn prompt_cache_ttl(&self, req: &CompletionRequest) -> Option<std::time::Duration> {
self.inner.prompt_cache_ttl(req)
}
async fn warm_cache(
&self,
req: CompletionRequest,
) -> Result<luxe_core::provider::Usage, ProviderError> {
let call = SEQ.fetch_add(1, Ordering::Relaxed);
let started = std::time::Instant::now();
let warmed = CALL_ID.scope(call, self.inner.warm_cache(req)).await;
match &warmed {
// A response half, so `luxe wire` shows what the refresh read rather than a row of zeros
Ok(usage) => {
let mut record = ResponseRecord::default();
record.observe(&ProviderEvent::Usage(usage.clone()), started.elapsed().as_millis());
record.finish(call, self.inner.name(), started.elapsed().as_millis(), true);
}
Err(error) => record_error(call, self.inner.name(), error),
}
warmed
}
}
/// The in-flight half of a recorded stream.
struct OpenRecord {
call: u64,
provider: String,
started: std::time::Instant,
record: ResponseRecord,
}
/// A stream that folds what passes through it into one response record.
///
/// The record is flushed on **drop**, not just on end-of-stream: the engine stops polling the
/// moment it sees `Done` and drops the rest, so an end-of-stream hook alone would silently log
/// nothing for a normal turn. `drained` in the record says which of the two happened.
struct Recording<S> {
inner: S,
open: Option<OpenRecord>,
}
impl<S> Recording<S> {
fn flush(&mut self, drained: bool) {
if let Some(open) = self.open.take() {
let elapsed = open.started.elapsed().as_millis();
open.record.finish(open.call, &open.provider, elapsed, drained);
}
}
}
impl<S> futures::Stream for Recording<S>
where
S: futures::Stream<Item = ProviderEvent> + Unpin,
{
type Item = ProviderEvent;
fn poll_next(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
let this = self.get_mut();
match std::pin::Pin::new(&mut this.inner).poll_next(cx) {
std::task::Poll::Ready(Some(event)) => {
if let Some(open) = this.open.as_mut() {
open.record.observe(&event, open.started.elapsed().as_millis());
}
std::task::Poll::Ready(Some(event))
}
std::task::Poll::Ready(None) => {
this.flush(true);
std::task::Poll::Ready(None)
}
std::task::Poll::Pending => std::task::Poll::Pending,
}
}
}
impl<S> Drop for Recording<S> {
fn drop(&mut self) {
self.flush(false);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn credential_headers_are_redacted_and_protocol_headers_are_not() {
for name in ["Authorization", "x-api-key", "API-KEY", "Cookie"] {
assert!(
SECRET_HEADERS.contains(&name.to_ascii_lowercase().as_str()),
"{name} must be treated as a credential"
);
}
for name in ["anthropic-version", "Content-Type", "Accept", "anthropic-beta"] {
assert!(
!SECRET_HEADERS.contains(&name.to_ascii_lowercase().as_str()),
"{name} is protocol, not a credential"
);
}
}
/// A record the log cannot take is said, once, rather than dropped without a word.
///
/// The break this catches: every failure was swallowed, so a capture that stopped partway read
/// as a session that went quiet.
#[test]
fn a_record_the_log_cannot_take_is_said_once() {
struct Full;
impl Write for Full {
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
Err(std::io::Error::other("disk full"))
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
append_to(&Mutex::new(Full), &serde_json::json!({"kind": "request"}));
let error = std::io::Error::other("again");
assert!(!note_dropped(&error), "the append said it, so this one does not");
}
#[tokio::test]
async fn a_call_id_is_zero_outside_a_recorded_call_and_set_inside_one() {
assert_eq!(current_call_id(), 0, "an unwrapped adapter still records, under call 0");
CALL_ID.scope(7, async { assert_eq!(current_call_id(), 7) }).await;
}
}

View File

@@ -0,0 +1,16 @@
//! Wire JSON — the small shapes every adapter spells the same way.
/// `data:image/png;base64,…` — how the OpenAI schemas carry image bytes inside a JSON string.
pub(crate) fn data_url(mime: &str, data: &str) -> String {
format!("data:{mime};base64,{data}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_data_url_names_the_mime_and_the_encoding() {
assert_eq!(data_url("image/png", "QUJD"), "data:image/png;base64,QUJD");
}
}