Skip to content

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

Rust

feat(llm): add anthropic-oauth provider (Claude subscription via OAuth)

AkitaOnRailsf9c432e59715
diff --git a/README.md b/README.md
index 3d17acab..2913cb52 100644
--- a/README.md
+++ b/README.md
@@ -313,6 +313,7 @@ Recommended defaults:
| Provider | Default | Use when |
|---|---|---|
| `anthropic` | `claude-haiku-4-5` | Best default for consolidation quality and rule classification. |
+| `anthropic-oauth` | `claude-sonnet-4-6` | Use a Claude Pro/Max subscription via `claude setup-token`, no API key. |
| `openai` | `gpt-5.4-mini` | Cheaper and faster hosted option. |
| `openai-oauth` | `gpt-5.5` | ChatGPT Pro/Plus/Codex backend via `ai-memory auth login openai-oauth`; no Platform API key. |
| `copilot` | `gpt-5.5` | GitHub Copilot Chat backend via `ai-memory auth login copilot` or `COPILOT_GITHUB_TOKEN`; requires a Copilot subscription. |
@@ -324,6 +325,15 @@ the ChatGPT/Codex Responses backend, not `api.openai.com`. For Docker quick
starts, run `ai-memory auth login openai-oauth` with the wrapper so the token
lands in the same `ai-memory-data` volume as the server.
+`anthropic-oauth` hits the same `/v1/messages` endpoint as `anthropic` but
+authenticates with an OAuth bearer token instead of an API key. Run
+`claude setup-token` once, then set `AI_MEMORY_LLM_PROVIDER=anthropic-oauth` and
+`ANTHROPIC_OAUTH_TOKEN=<token>` (or `CLAUDE_CODE_OAUTH_TOKEN`, which `claude
+setup-token` writes automatically). No `ANTHROPIC_API_KEY` is needed.
+**⚠️ Unofficial and against Anthropic's usage policies — use at your own risk;
+it may get your account rate-limited or banned. See
+[the warning in `docs/install.md`](docs/install.md#anthropic-via-claude-subscription-oauth).**
+
`copilot` stores a GitHub user token in the same auth file, exchanges it for a
short-lived Copilot API token via GitHub's `/copilot_internal/v2/token`, and
uses the Copilot Chat endpoint with `vscode-chat` integration headers. You can
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index c39e0616..c5118f48 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -110,6 +110,7 @@ pub struct RuntimeEnv {
auth_token: Option<String>,
host_cwd: Option<String>,
anthropic_api_key: Option<SecretString>,
+ anthropic_oauth_token: Option<SecretString>,
openai_api_key: Option<SecretString>,
gemini_api_key: Option<SecretString>,
llm_api_key: Option<SecretString>,
@@ -129,6 +130,10 @@ impl RuntimeEnv {
auth_token: env_string("AI_MEMORY_AUTH_TOKEN"),
host_cwd: env_string("AI_MEMORY_HOST_CWD"),
anthropic_api_key: env_secret("ANTHROPIC_API_KEY"),
+ // CLAUDE_CODE_OAUTH_TOKEN is what `claude setup-token` writes;
+ // ANTHROPIC_OAUTH_TOKEN is our canonical name — accept both.
+ anthropic_oauth_token: env_secret("ANTHROPIC_OAUTH_TOKEN")
+ .or_else(|| env_secret("CLAUDE_CODE_OAUTH_TOKEN")),
openai_api_key: env_secret("OPENAI_API_KEY"),
// GOOGLE_API_KEY is the older alias many Google docs still
// mention; accept either so users don't get tripped up.
@@ -325,10 +330,11 @@ impl Config {
"openai-compat" | "openai_compat" => ProviderChoice::OpenAiCompat,
"openai-oauth" | "openai_oauth" => ProviderChoice::OpenAiOAuth,
"copilot" | "github-copilot" | "github_copilot" => ProviderChoice::Copilot,
+ "anthropic-oauth" | "anthropic_oauth" => ProviderChoice::AnthropicOAuth,
other => {
return Err(LlmError::NotConfigured(format!(
"AI_MEMORY_LLM_PROVIDER={other} is not one of \
- anthropic|openai|gemini|openai-compat|openai-oauth|copilot"
+ anthropic|openai|gemini|openai-compat|openai-oauth|copilot|anthropic-oauth"
)));
}
};
@@ -336,6 +342,7 @@ impl Config {
Some(s) => s.to_string(),
None => match provider {
ProviderChoice::Anthropic => "claude-sonnet-4-6".to_string(),
+ ProviderChoice::AnthropicOAuth => "claude-sonnet-4-6".to_string(),
ProviderChoice::OpenAi => "gpt-4o-mini".to_string(),
ProviderChoice::Gemini => "gemini-2.5-flash".to_string(),
ProviderChoice::OpenAiOAuth => "gpt-5.5".to_string(),
@@ -435,6 +442,7 @@ impl Config {
ProviderChoice::OpenAiCompat => self.runtime_env.llm_api_key.clone(),
ProviderChoice::OpenAiOAuth => None,
ProviderChoice::Copilot => None,
+ ProviderChoice::AnthropicOAuth => None,
}
}
@@ -499,6 +507,9 @@ impl Config {
.clone()
.or_else(|| self.llm_base_url.clone()),
),
+ AuthRequirement::AnthropicOAuthToken => {
+ ProviderAuth::anthropic_oauth_token(self.runtime_env.anthropic_oauth_token.clone())
+ }
}
}
@@ -790,4 +801,46 @@ mod tests {
assert_eq!(auth.token_file, tmp.path().join("auth.json"));
assert_eq!(auth.github_token.unwrap().expose_secret(), "ghu-test");
}
+
+ #[test]
+ fn anthropic_oauth_provider_resolves_choice_default_model_and_credential() {
+ let cfg = Config {
+ llm_provider: Some("anthropic-oauth".into()),
+ runtime_env: RuntimeEnv {
+ anthropic_oauth_token: Some(SecretString::from("tok-oauth-test")),
+ ..RuntimeEnv::default()
+ },
+ ..Config::default()
+ };
+
+ let provider = cfg.llm_provider_config().unwrap().unwrap();
+ assert_eq!(provider.provider, ProviderChoice::AnthropicOAuth);
+ assert_eq!(provider.model, "claude-sonnet-4-6");
+ assert_eq!(
+ provider.auth.requirement(),
+ AuthRequirement::AnthropicOAuthToken
+ );
+ assert_eq!(
+ provider
+ .auth
+ .require_anthropic_oauth_token()
+ .unwrap()
+ .expose_secret(),
+ "tok-oauth-test"
+ );
+ }
+
+ #[test]
+ fn anthropic_oauth_provider_underscore_alias_also_resolves() {
+ let cfg = Config {
+ llm_provider: Some("anthropic_oauth".into()),
+ runtime_env: RuntimeEnv {
+ anthropic_oauth_token: Some(SecretString::from("tok-alias")),
+ ..RuntimeEnv::default()
+ },
+ ..Config::default()
+ };
+ let provider = cfg.llm_provider_config().unwrap().unwrap();
+ assert_eq!(provider.provider, ProviderChoice::AnthropicOAuth);
+ }
}
diff --git a/crates/ai-memory-llm/src/anthropic.rs b/crates/ai-memory-llm/src/anthropic.rs
index a2792dd5..ea0d8380 100644
--- a/crates/ai-memory-llm/src/anthropic.rs
+++ b/crates/ai-memory-llm/src/anthropic.rs
@@ -18,10 +18,31 @@ pub const DEFAULT_BASE_URL: &str = "https://api.anthropic.com";
/// Pinned Anthropic API version header.
pub const ANTHROPIC_VERSION: &str = "2023-06-01";
+/// `anthropic-beta` header sent on OAuth (subscription) requests. Mirrors
+/// the Claude Code OAuth handshake: the `oauth-2025-04-20` feature is what
+/// authorises a subscription bearer token against /v1/messages, and the
+/// `claude-code-*` feature matches what the official CLI sends. Values
+/// cross-checked against oh-my-pi's `claudeCodeBetaDefaults`.
+///
+/// NOTE: this header combination is derived from Claude Code's documented OAuth
+/// handshake and should be smoke-tested with a real `claude setup-token` token
+/// before use in production, as Anthropic may update the required beta values.
+const ANTHROPIC_OAUTH_BETA: &str = "oauth-2025-04-20,claude-code-20250219";
+
+/// Authentication mode for the Anthropic provider.
+#[derive(Clone)]
+enum AnthropicAuth {
+ /// Static API key sent as `x-api-key`.
+ ApiKey(SecretString),
+ /// OAuth bearer token from a Claude Pro/Max subscription
+ /// (obtained via `claude setup-token`).
+ OAuth(SecretString),
+}
+
/// Anthropic Messages-API-backed provider.
pub struct AnthropicProvider {
client: reqwest::Client,
- api_key: SecretString,
+ auth: AnthropicAuth,
base_url: String,
model: String,
}
@@ -41,7 +62,28 @@ impl AnthropicProvider {
.build()?;
Ok(Self {
client,
- api_key,
+ auth: AnthropicAuth::ApiKey(api_key),
+ base_url: DEFAULT_BASE_URL.to_string(),
+ model: model.into(),
+ })
+ }
+
+ /// Construct a provider using an OAuth subscription token from
+ /// `claude setup-token` (Claude Pro/Max subscription). Hits the same
+ /// `/v1/messages` endpoint as `new`, but uses a Bearer token and the
+ /// `anthropic-beta: oauth-2025-04-20,claude-code-20250219` header
+ /// instead of `x-api-key`.
+ ///
+ /// # Errors
+ /// Returns a `reqwest::Error` if the underlying HTTP client cannot
+ /// be built.
+ pub fn new_oauth(token: SecretString, model: impl Into<String>) -> LlmResult<Self> {
+ let client = reqwest::Client::builder()
+ .timeout(Duration::from_secs(300))
+ .build()?;
+ Ok(Self {
+ client,
+ auth: AnthropicAuth::OAuth(token),
base_url: DEFAULT_BASE_URL.to_string(),
model: model.into(),
})
@@ -209,15 +251,17 @@ impl AnthropicProvider {
async fn post<B: Serialize, R: DeserializeOwned>(&self, body: &B) -> LlmResult<R> {
let url = format!("{}/v1/messages", self.base_url.trim_end_matches('/'));
debug!(url, "POST anthropic");
- let resp = self
+ let mut builder = self
.client
.post(&url)
- .header("x-api-key", self.api_key.expose_secret())
.header("anthropic-version", ANTHROPIC_VERSION)
- .header("content-type", "application/json")
- .json(body)
- .send()
- .await?;
+ .header("content-type", "application/json");
+ // Apply the auth headers through the same helper the tests assert on,
+ // so a change to one can't silently diverge from the other.
+ for (name, value) in self.auth_headers() {
+ builder = builder.header(name, value);
+ }
+ let resp = builder.json(body).send().await?;
let status = resp.status();
if !status.is_success() {
let body = resp.text().await.unwrap_or_default();
@@ -228,4 +272,93 @@ impl AnthropicProvider {
}
resp.json::<R>().await.map_err(LlmError::from)
}
+
+ /// The auth headers for this provider instance: `x-api-key` for a static
+ /// key, or `Authorization: Bearer` + `anthropic-beta` for an OAuth
+ /// subscription token. The two modes are mutually exclusive — OAuth must
+ /// never send `x-api-key` or Anthropic rejects the request. `post` applies
+ /// these, and the unit tests assert on them, so both stay in lockstep.
+ fn auth_headers(&self) -> Vec<(&'static str, String)> {
+ match &self.auth {
+ AnthropicAuth::ApiKey(key) => vec![("x-api-key", key.expose_secret().to_string())],
+ AnthropicAuth::OAuth(token) => vec![
+ ("authorization", format!("Bearer {}", token.expose_secret())),
+ ("anthropic-beta", ANTHROPIC_OAUTH_BETA.to_string()),
+ ],
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use secrecy::SecretString;
+
+ use super::*;
+
+ #[test]
+ fn api_key_provider_sends_x_api_key_no_authorization() {
+ let provider =
+ AnthropicProvider::new(SecretString::from("sk-ant-test"), "claude-sonnet-4-6").unwrap();
+ let headers = provider.auth_headers();
+ let names: Vec<&str> = headers.iter().map(|(name, _)| *name).collect();
+ assert!(names.contains(&"x-api-key"), "expected x-api-key header");
+ assert!(
+ !names.contains(&"authorization"),
+ "api-key mode must NOT send authorization header"
+ );
+ assert!(
+ !names.contains(&"anthropic-beta"),
+ "api-key mode must NOT send anthropic-beta header"
+ );
+ let key_val = headers
+ .iter()
+ .find(|(n, _)| *n == "x-api-key")
+ .map(|(_, v)| v.as_str())
+ .unwrap_or("");
+ assert_eq!(key_val, "sk-ant-test");
+ }
+
+ #[test]
+ fn oauth_provider_sends_bearer_and_beta_no_x_api_key() {
+ let provider =
+ AnthropicProvider::new_oauth(SecretString::from("tok-oauth-test"), "claude-sonnet-4-6")
+ .unwrap();
+ let headers = provider.auth_headers();
+ let names: Vec<&str> = headers.iter().map(|(name, _)| *name).collect();
+ assert!(
+ !names.contains(&"x-api-key"),
+ "oauth mode must NOT send x-api-key header"
+ );
+ assert!(
+ names.contains(&"authorization"),
+ "expected authorization header"
+ );
+ assert!(
+ names.contains(&"anthropic-beta"),
+ "expected anthropic-beta header"
+ );
+ let auth_val = headers
+ .iter()
+ .find(|(n, _)| *n == "authorization")
+ .map(|(_, v)| v.as_str())
+ .unwrap_or("");
+ assert_eq!(auth_val, "Bearer tok-oauth-test");
+ let beta_val = headers
+ .iter()
+ .find(|(n, _)| *n == "anthropic-beta")
+ .map(|(_, v)| v.as_str())
+ .unwrap_or("");
+ assert!(
+ beta_val.contains("oauth-2025-04-20"),
+ "anthropic-beta must contain oauth-2025-04-20"
+ );
+ }
+
+ #[test]
+ fn with_base_url_is_preserved_after_oauth_construction() {
+ let provider = AnthropicProvider::new_oauth(SecretString::from("tok"), "claude-sonnet-4-6")
+ .unwrap()
+ .with_base_url("http://localhost:9999");
+ assert_eq!(provider.base_url, "http://localhost:9999");
+ }
}
diff --git a/crates/ai-memory-llm/src/auth.rs b/crates/ai-memory-llm/src/auth.rs
index 2cd81bad..f6434114 100644
--- a/crates/ai-memory-llm/src/auth.rs
+++ b/crates/ai-memory-llm/src/auth.rs
@@ -44,6 +44,9 @@ pub enum AuthRequirement {
OpenAiOAuthToken,
/// Provider requires a GitHub token or stored auth for Copilot.
CopilotToken,
+ /// Provider requires an Anthropic OAuth subscription token
+ /// (from `claude setup-token`).
+ AnthropicOAuthToken,
}
/// Resolved Copilot auth inputs.
@@ -68,6 +71,8 @@ pub enum Credential {
OpenAiOAuthTokenFile(PathBuf),
/// GitHub Copilot auth inputs.
Copilot(CopilotAuth),
+ /// Anthropic OAuth subscription token from `claude setup-token`.
+ AnthropicOAuthToken(SecretString),
}
/// Resolved authentication for one provider instance.
@@ -129,6 +134,23 @@ impl ProviderAuth {
}
}
+ /// Resolve Anthropic OAuth auth from a subscription token (from `claude setup-token`).
+ #[must_use]
+ pub fn anthropic_oauth_token(token: Option<SecretString>) -> Self {
+ let has_token = token.is_some();
+ Self {
+ requirement: AuthRequirement::AnthropicOAuthToken,
+ credential: token.map(Credential::AnthropicOAuthToken),
+ source: if has_token {
+ CredentialSource::Environment {
+ name: "ANTHROPIC_OAUTH_TOKEN",
+ }
+ } else {
+ CredentialSource::NotProvided
+ },
+ }
+ }
+
fn from_api_key(
requirement: AuthRequirement,
key: Option<SecretString>,
@@ -182,6 +204,9 @@ impl ProviderAuth {
(_, Some(Credential::Copilot(_))) => Err(LlmError::NotConfigured(
"API key credential expected, got copilot auth".into(),
)),
+ (_, Some(Credential::AnthropicOAuthToken(_))) => Err(LlmError::NotConfigured(
+ "API key credential expected, got anthropic-oauth token".into(),
+ )),
(AuthRequirement::RequiredApiKey { env_var }, None) => {
Err(LlmError::NotConfigured((*env_var).into()))
}
@@ -195,6 +220,11 @@ impl ProviderAuth {
"copilot auth missing; run `ai-memory auth login copilot` or set COPILOT_GITHUB_TOKEN"
.into(),
)),
+ (AuthRequirement::AnthropicOAuthToken, None) => Err(LlmError::NotConfigured(
+ "anthropic-oauth token missing; run `claude setup-token` and set \
+ ANTHROPIC_OAUTH_TOKEN (or CLAUDE_CODE_OAUTH_TOKEN)"
+ .into(),
+ )),
}
}
@@ -203,7 +233,33 @@ impl ProviderAuth {
pub fn optional_api_key(&self) -> Option<SecretString> {
match &self.credential {
Some(Credential::ApiKey(key)) => Some(key.clone()),
- Some(Credential::OpenAiOAuthTokenFile(_) | Credential::Copilot(_)) | None => None,
+ Some(
+ Credential::OpenAiOAuthTokenFile(_)
+ | Credential::Copilot(_)
+ | Credential::AnthropicOAuthToken(_),
+ )
+ | None => None,
+ }
+ }
+
+ /// Extract the Anthropic OAuth subscription token.
+ ///
+ /// # Errors
+ /// Returns [`LlmError::NotConfigured`] when no token was resolved.
+ pub fn require_anthropic_oauth_token(&self) -> LlmResult<SecretString> {
+ match (&self.requirement, &self.credential) {
+ (
+ AuthRequirement::AnthropicOAuthToken,
+ Some(Credential::AnthropicOAuthToken(token)),
+ ) => Ok(token.clone()),
+ (AuthRequirement::AnthropicOAuthToken, None) => Err(LlmError::NotConfigured(
+ "anthropic-oauth token missing; run `claude setup-token` and set \
+ ANTHROPIC_OAUTH_TOKEN (or CLAUDE_CODE_OAUTH_TOKEN)"
+ .into(),
+ )),
+ _ => Err(LlmError::NotConfigured(
+ "anthropic-oauth token credential required".into(),
+ )),
}
}
@@ -319,4 +375,49 @@ mod tests {
Some("https://api.example.test")
);
}
+
+ #[test]
+ fn anthropic_oauth_token_round_trips_secret_and_reports_env_source() {
+ let auth = ProviderAuth::anthropic_oauth_token(Some(SecretString::from("oauth-tok-test")));
+ assert_eq!(
+ auth.source(),
+ CredentialSource::Environment {
+ name: "ANTHROPIC_OAUTH_TOKEN"
+ }
+ );
+ assert_eq!(
+ auth.require_anthropic_oauth_token()
+ .unwrap()
+ .expose_secret(),
+ "oauth-tok-test"
+ );
+ assert_eq!(auth.requirement(), AuthRequirement::AnthropicOAuthToken);
+ }
+
+ #[test]
+ fn anthropic_oauth_token_absent_returns_not_configured() {
+ let auth = ProviderAuth::anthropic_oauth_token(None);
+ assert_eq!(auth.source(), CredentialSource::NotProvided);
+ let err = auth.require_anthropic_oauth_token().unwrap_err();
+ assert!(
+ matches!(err, LlmError::NotConfigured(ref msg) if msg.contains("ANTHROPIC_OAUTH_TOKEN")),
+ "unexpected error: {err}"
+ );
+ }
+
+ #[test]
+ fn require_api_key_rejects_anthropic_oauth_credential() {
+ let auth = ProviderAuth::anthropic_oauth_token(Some(SecretString::from("tok")));
+ let err = auth.require_api_key().unwrap_err();
+ assert!(
+ matches!(err, LlmError::NotConfigured(ref msg) if msg.contains("anthropic-oauth token")),
+ "unexpected error: {err}"
+ );
+ }
+
+ #[test]
+ fn optional_api_key_returns_none_for_anthropic_oauth_credential() {
+ let auth = ProviderAuth::anthropic_oauth_token(Some(SecretString::from("tok")));
+ assert!(auth.optional_api_key().is_none());
+ }
}
diff --git a/crates/ai-memory-llm/src/factory.rs b/crates/ai-memory-llm/src/factory.rs
index 233ba4d2..ca0c7c07 100644
--- a/crates/ai-memory-llm/src/factory.rs
+++ b/crates/ai-memory-llm/src/factory.rs
@@ -34,6 +34,8 @@ pub enum ProviderChoice {
OpenAiOAuth,
/// GitHub Copilot Chat backend.
Copilot,
+ /// Anthropic Messages API via a Claude-subscription OAuth token.
+ AnthropicOAuth,
}
impl ProviderChoice {
@@ -55,6 +57,7 @@ impl ProviderChoice {
},
Self::OpenAiOAuth => AuthRequirement::OpenAiOAuthToken,
Self::Copilot => AuthRequirement::CopilotToken,
+ Self::AnthropicOAuth => AuthRequirement::AnthropicOAuthToken,
}
}
}
@@ -197,6 +200,14 @@ pub fn build_provider(config: ProviderConfig) -> LlmResult<Arc<dyn LlmProvider>>
let auth = config.auth.require_copilot_auth()?;
Ok(Arc::new(CopilotProvider::new(auth, config.model)?))
}
+ ProviderChoice::AnthropicOAuth => {
+ let token = config.auth.require_anthropic_oauth_token()?;
+ let mut provider = AnthropicProvider::new_oauth(token, config.model)?;
+ if let Some(url) = config.base_url {
+ provider = provider.with_base_url(url);
+ }
+ Ok(Arc::new(provider))
+ }
}
}
@@ -238,6 +249,10 @@ mod tests {
ProviderChoice::Copilot.auth_requirement(),
AuthRequirement::CopilotToken
);
+ assert_eq!(
+ ProviderChoice::AnthropicOAuth.auth_requirement(),
+ AuthRequirement::AnthropicOAuthToken
+ );
}
#[test]
diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml
index 63a140c7..82f3840d 100644
--- a/docker/docker-compose.yml
+++ b/docker/docker-compose.yml
@@ -25,6 +25,17 @@ services:
- "127.0.0.1:49374:49374"
environment:
- RUST_LOG=ai_memory=info,ai_memory_store=info,ai_memory_wiki=info,ai_memory_mcp=info,tracing_appender=warn
+ # Uncomment ONE provider block. All are opt-in; omit to run zero-LLM.
+ #
+ # Option A — Anthropic API key
+ #- AI_MEMORY_LLM_PROVIDER=anthropic
+ #- ANTHROPIC_API_KEY=sk-ant-...
+ #
+ # Option B — Anthropic via Claude Pro/Max subscription (claude setup-token)
+ # WARNING: unofficial, against Anthropic's usage policies — use at your
+ # own risk (may get your account rate-limited/banned). See docs/install.md.
+ #- AI_MEMORY_LLM_PROVIDER=anthropic-oauth
+ #- ANTHROPIC_OAUTH_TOKEN=
healthcheck:
test: ["CMD", "/usr/local/bin/ai-memory", "status"]
interval: 30s
diff --git a/docs/install.md b/docs/install.md
index 0bfba7e6..4446c194 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -629,6 +629,7 @@ ai-memory works in three intensity tiers:
|---|---|---|---|
| **Zero-LLM** (default) | FTS5 search, rule-based session summaries, auto-handoffs from prompt + tool-call history | (none) | $0 |
| **+ LLM consolidation** | LLM rewrites session pages as coherent narratives; PreCompact checkpoints; LLM-driven contradiction lint | `AI_MEMORY_LLM_PROVIDER=anthropic` + `ANTHROPIC_API_KEY` | ~$0.01–0.05 / session |
+| **+ Anthropic via subscription** | Same LLM features using a Claude Pro/Max subscription instead of an API key | `AI_MEMORY_LLM_PROVIDER=anthropic-oauth` + `ANTHROPIC_OAUTH_TOKEN` | Uses your Claude subscription |
| **+ ChatGPT/Codex OAuth** | Same LLM features using a ChatGPT Pro/Plus login instead of an OpenAI Platform key | `AI_MEMORY_LLM_PROVIDER=openai-oauth` + `ai-memory auth login openai-oauth` | Uses your ChatGPT subscription |
| **+ GitHub Copilot** | Same LLM features using a GitHub Copilot subscription | `AI_MEMORY_LLM_PROVIDER=copilot` + `ai-memory auth login copilot` or `COPILOT_GITHUB_TOKEN` | Uses your Copilot subscription |
| **+ Hybrid retrieval** | RRF over FTS5 + vector cosine similarity. Better recall on paraphrased queries | `AI_MEMORY_EMBEDDING_PROVIDER=openai` + `OPENAI_API_KEY` | ~$0.0001 / page on backfill |
@@ -640,6 +641,7 @@ If you set only the provider, ai-memory picks a sensible default:
| Setting | Default | Why |
|---|---|---|
| `AI_MEMORY_LLM_PROVIDER=anthropic` | `claude-haiku-4-5` | **Recommended default.** Best balance of speed, restraint, and classification quality. Not a reasoning model. Consistently classifies durable project rules as `kind: rule`. |
+| `AI_MEMORY_LLM_PROVIDER=anthropic-oauth` | `claude-sonnet-4-6` | Anthropic via Claude subscription. Run `claude setup-token` once; set `ANTHROPIC_OAUTH_TOKEN` (or `CLAUDE_CODE_OAUTH_TOKEN`). No `ANTHROPIC_API_KEY` needed. Same `/v1/messages` endpoint, Bearer token auth. |
| `AI_MEMORY_LLM_PROVIDER=openai` | `gpt-5.4-mini` | Cheaper + faster alternative. Same parse reliability; mild over-classification on thin sessions. |
| `AI_MEMORY_LLM_PROVIDER=openai-oauth` | `gpt-5.5` | ChatGPT/Codex backend. Run `ai-memory auth login openai-oauth` once; ai-memory stores the refresh token in `<data_dir>/auth.json` and refreshes access tokens automatically. |
| `AI_MEMORY_LLM_PROVIDER=copilot` | `gpt-5.5` | GitHub Copilot Chat backend. ai-memory stores a GitHub user token in `<data_dir>/auth.json`, exchanges it for a short-lived Copilot API token, and refreshes before expiry. |
@@ -654,6 +656,49 @@ If you set only the provider, ai-memory picks a sensible default:
> internal reasoning and hang or emit empty responses with the strict-JSON
> consolidation prompt. Turn reasoning off if you must use one.
+### Anthropic via Claude subscription (OAuth)
+
+> [!WARNING]
+> **Unofficial and against Anthropic's usage policies — use at your own risk.**
+> Anthropic provides no public OAuth API for the Claude Pro/Max subscription;
+> this reuses the `claude setup-token` credential against `/v1/messages`, which
+> is **not a supported or sanctioned integration**. Anthropic's terms reserve
+> subscription (Claude Code) access for interactive use, and using it as an
+> automated API backend may breach those terms and **could get your account
+> rate-limited, flagged, or banned**. The header recipe is also undocumented
+> and can change without notice. If you want a supported path, use the
+> `anthropic` provider with a real Platform API key. We ship this purely as an
+> opt-in convenience and make no guarantees about it.
+
+`anthropic-oauth` is for Claude Pro/Max subscribers who want to use their
+existing subscription instead of an Anthropic Platform API key. It hits the
+**same** `/v1/messages` endpoint as the `anthropic` provider — only the auth
+headers differ (Bearer token + `anthropic-beta: oauth-2025-04-20`).
+
+```bash
+# Obtain a token once using the Claude Code CLI:
+claude setup-token
+
+# Then export it (the CLI may also write CLAUDE_CODE_OAUTH_TOKEN automatically):
+export ANTHROPIC_OAUTH_TOKEN=<paste token here>
+export AI_MEMORY_LLM_PROVIDER=anthropic-oauth
+ai-memory serve
+```
+
+For Docker, pass the token as an env var:
+
+```bash
+docker run -d --name ai-memory \
+ -p 127.0.0.1:49374:49374 \
+ -v ai-memory-data:/data \
+ -e AI_MEMORY_LLM_PROVIDER=anthropic-oauth \
+ -e ANTHROPIC_OAUTH_TOKEN=<token> \
+ akitaonrails/ai-memory:latest
+```
+
+Both `ANTHROPIC_OAUTH_TOKEN` and `CLAUDE_CODE_OAUTH_TOKEN` are accepted;
+ai-memory checks `ANTHROPIC_OAUTH_TOKEN` first.
+
### OpenAI OAuth / Codex
`openai-oauth` is for ChatGPT Pro/Plus/Codex accounts. It does **not** use
diff --git a/evals/src/main.rs b/evals/src/main.rs
index 0ee1159a..1c59799d 100644
--- a/evals/src/main.rs
+++ b/evals/src/main.rs
@@ -334,6 +334,7 @@ fn resolve_provider(side: &str, args: &Args) -> Result<ResolvedConfig> {
None,
base_url.clone(),
),
+ AuthRequirement::AnthropicOAuthToken => ProviderAuth::anthropic_oauth_token(api_key),
};
Ok(ResolvedConfig {