Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

feat(llm): send OpenRouter app-attribution headers by default

Jayson Reisa5f257048f90
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fe0cc8a7..6087a19c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- The `openai-compat` provider now sends OpenRouter's app-attribution
+ headers (`HTTP-Referer`, `X-Title`) by default when its base URL points
+ at `openrouter.ai`, so ai-memory's usage shows up on OpenRouter's app
+ leaderboard. An explicit `AI_MEMORY_LLM_HEADERS` entry for either header
+ still wins, and a non-OpenRouter compat endpoint (Ollama, vLLM, LM
+ Studio) never receives them.
+
### Changed
- The managed routing snippet now states that Claude Code loads `CLAUDE.md` and
does not read `AGENTS.md`: a project whose canonical instruction file is
diff --git a/crates/ai-memory-llm/src/factory.rs b/crates/ai-memory-llm/src/factory.rs
index f8603845..0bd1cfc2 100644
--- a/crates/ai-memory-llm/src/factory.rs
+++ b/crates/ai-memory-llm/src/factory.rs
@@ -284,6 +284,29 @@ fn with_default_user_agent(
headers
}
+/// Layer OpenRouter's app-attribution headers (`HTTP-Referer`, `X-Title`)
+/// under the operator's headers when the `openai-compat` base URL points at
+/// OpenRouter, so ai-memory's usage shows up on OpenRouter's app leaderboard
+/// without requiring `AI_MEMORY_LLM_HEADERS` configuration. An explicit
+/// operator entry for either header still wins, same precedence as the
+/// default user agent.
+fn with_default_openrouter_headers(
+ base_url: &str,
+ mut headers: crate::ExtraHeaders,
+) -> crate::ExtraHeaders {
+ if crate::openai::is_openrouter_base(base_url) {
+ headers.set_default(
+ reqwest::header::HeaderName::from_static("http-referer"),
+ reqwest::header::HeaderValue::from_static(crate::OPENROUTER_HTTP_REFERER),
+ );
+ headers.set_default(
+ reqwest::header::HeaderName::from_static("x-title"),
+ reqwest::header::HeaderValue::from_static(crate::OPENROUTER_X_TITLE),
+ );
+ }
+ headers
+}
+
/// Construct an `Arc<dyn LlmProvider>` matching the config.
///
/// # Errors
@@ -327,6 +350,7 @@ pub fn build_provider(config: ProviderConfig) -> LlmResult<Arc<dyn LlmProvider>>
let base = config
.base_url
.ok_or_else(|| LlmError::NotConfigured("LLM_BASE_URL".into()))?;
+ let extra_headers = with_default_openrouter_headers(&base, extra_headers);
Ok(Arc::new(
OpenAiCompatProvider::new(base, config.auth.optional_api_key(), config.model)?
.with_strict(config.compat_strict)
@@ -464,6 +488,42 @@ mod tests {
assert!(!ua.contains("opencode"), "{ua} impersonates another client");
}
+ /// OpenRouter attributes usage on its app leaderboard by these headers;
+ /// without a default, a plain `openai-compat` setup pointed at
+ /// OpenRouter would arrive unattributed.
+ #[test]
+ fn openrouter_app_headers_are_layered_for_an_openrouter_base_url() {
+ let headers = with_default_openrouter_headers(
+ "https://openrouter.ai/api/v1",
+ crate::ExtraHeaders::default(),
+ );
+ assert_eq!(
+ headers.get("http-referer"),
+ Some(crate::OPENROUTER_HTTP_REFERER)
+ );
+ assert_eq!(headers.get("x-title"), Some(crate::OPENROUTER_X_TITLE));
+ }
+
+ /// A self-hosted `openai-compat` endpoint (Ollama, vLLM, LM Studio) has
+ /// no leaderboard to attribute to, so it must not receive these.
+ #[test]
+ fn openrouter_app_headers_are_absent_for_a_non_openrouter_base_url() {
+ let headers = with_default_openrouter_headers(
+ "http://localhost:11434/v1",
+ crate::ExtraHeaders::default(),
+ );
+ assert_eq!(headers.get("http-referer"), None);
+ assert_eq!(headers.get("x-title"), None);
+ }
+
+ #[test]
+ fn an_operator_http_referer_wins_over_the_openrouter_default() {
+ let operator = crate::ExtraHeaders::parse(["http-referer: https://example.com"]).unwrap();
+ let headers = with_default_openrouter_headers("https://openrouter.ai/api/v1", operator);
+ assert_eq!(headers.get("http-referer"), Some("https://example.com"));
+ assert_eq!(headers.get("x-title"), Some(crate::OPENROUTER_X_TITLE));
+ }
+
#[test]
fn missing_required_provider_auth_preserves_error_shape() {
let cfg = ProviderConfig {
diff --git a/crates/ai-memory-llm/src/lib.rs b/crates/ai-memory-llm/src/lib.rs
index 1ba6307d..2e53cc3d 100644
--- a/crates/ai-memory-llm/src/lib.rs
+++ b/crates/ai-memory-llm/src/lib.rs
@@ -54,6 +54,19 @@ pub const DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 300;
/// it.
pub const DEFAULT_USER_AGENT: &str = concat!("ai-memory/", env!("CARGO_PKG_VERSION"));
+/// `HTTP-Referer` ai-memory sends to OpenRouter.
+///
+/// OpenRouter attributes usage to an app on its public leaderboard by
+/// `HTTP-Referer` and [`OPENROUTER_X_TITLE`]; without them, ai-memory's
+/// requests show up unattributed. Layered under `AI_MEMORY_LLM_HEADERS` by
+/// [`factory::build_provider`] only when the `openai-compat` base URL points
+/// at `openrouter.ai`, so a non-OpenRouter compat endpoint (Ollama, vLLM,
+/// LM Studio) never receives these.
+pub const OPENROUTER_HTTP_REFERER: &str = "https://github.com/akitaonrails/ai-memory";
+
+/// `X-Title` ai-memory sends to OpenRouter. See [`OPENROUTER_HTTP_REFERER`].
+pub const OPENROUTER_X_TITLE: &str = "ai-memory";
+
pub mod anthropic;
pub mod auth;
pub mod copilot;
diff --git a/crates/ai-memory-llm/src/openai.rs b/crates/ai-memory-llm/src/openai.rs
index e6c87a20..95d25cbc 100644
--- a/crates/ai-memory-llm/src/openai.rs
+++ b/crates/ai-memory-llm/src/openai.rs
@@ -599,7 +599,7 @@ fn model_requires_default_temperature(model: &str) -> bool {
model_requires_max_completion_tokens(model)
}
-fn is_openrouter_base(url: &str) -> bool {
+pub(crate) fn is_openrouter_base(url: &str) -> bool {
url.to_ascii_lowercase().contains("openrouter.ai")
}
diff --git a/crates/ai-memory-llm/tests/suite/extra_headers_on_the_wire.rs b/crates/ai-memory-llm/tests/suite/extra_headers_on_the_wire.rs
index f93cd577..3df23fb1 100644
--- a/crates/ai-memory-llm/tests/suite/extra_headers_on_the_wire.rs
+++ b/crates/ai-memory-llm/tests/suite/extra_headers_on_the_wire.rs
@@ -11,7 +11,8 @@
use ai_memory_llm::types::ChatRequest;
use ai_memory_llm::{
- DEFAULT_USER_AGENT, ExtraHeaders, ProviderAuth, ProviderChoice, ProviderConfig, build_provider,
+ DEFAULT_USER_AGENT, ExtraHeaders, OPENROUTER_HTTP_REFERER, OPENROUTER_X_TITLE, ProviderAuth,
+ ProviderChoice, ProviderConfig, build_provider,
};
use secrecy::SecretString;
use serde_json::json;
@@ -121,6 +122,61 @@ async fn provider_owned_headers_survive_alongside_operator_headers() {
);
}
+/// A base URL that is not OpenRouter must not receive OpenRouter's
+/// attribution headers — a self-hosted Ollama/vLLM/LM Studio endpoint has no
+/// leaderboard to attribute to.
+#[tokio::test]
+async fn a_non_openrouter_compat_endpoint_does_not_receive_openrouter_headers() {
+ let request = captured_request(ExtraHeaders::default()).await;
+ assert!(values(&request, "http-referer").is_empty());
+ assert!(values(&request, "x-title").is_empty());
+}
+
+/// OpenRouter attributes usage on its app leaderboard by `HTTP-Referer` and
+/// `X-Title`; without these on the wire, ai-memory's requests would arrive
+/// unattributed.
+#[tokio::test]
+async fn openrouter_app_headers_reach_the_provider_request() {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(ok_body()))
+ .mount(&server)
+ .await;
+
+ // `is_openrouter_base` only checks for the substring `openrouter.ai`, so
+ // a fake path segment on the local mock server exercises the same code
+ // path a real `https://openrouter.ai/api/v1` base URL would.
+ let base_url = format!("{}/openrouter.ai", server.uri());
+ let provider = build_provider(ProviderConfig {
+ provider: ProviderChoice::OpenAiCompat,
+ model: "anthropic/claude-sonnet-4.6".into(),
+ auth: ProviderAuth::optional_api_key_from_env("LLM_API_KEY", None),
+ base_url: Some(base_url),
+ compat_strict: false,
+ request_timeout_secs: 30,
+ reasoning_effort: None,
+ extra_headers: ExtraHeaders::default(),
+ })
+ .expect("provider builds");
+
+ provider
+ .complete(ChatRequest::user_prompt("hi"))
+ .await
+ .expect("mock responds 200");
+
+ let received = server
+ .received_requests()
+ .await
+ .expect("mock recorded requests");
+ assert_eq!(received.len(), 1, "expected exactly one upstream request");
+ let request = &received[0];
+ assert_eq!(
+ values(request, "http-referer"),
+ vec![OPENROUTER_HTTP_REFERER]
+ );
+ assert_eq!(values(request, "x-title"), vec![OPENROUTER_X_TITLE]);
+}
+
/// The `opencode` provider defaults to Go, so a base URL an operator sets
/// must actually redirect it — this is the regression the silently-dropped
/// `ProviderConfig::base_url` caused. Driving it against a mock is the only