Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat: add a Cursor Agent CLI LLM provider
José Fernando Gomes Marcial06b19e3baed7
diff --git a/AGENTS.md b/AGENTS.mdindex 8d20ace2..57b065b8 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -142,7 +142,8 @@ Core design:raw-observation fallback.- **LLM is opt-in.** Zero-LLM mode still captures, searches (FTS5), andwrites rule-based summaries. Providers (Anthropic, OpenAI, OpenAI/Codex- OAuth, GitHub Copilot, Gemini, OpenAI-compatible endpoints) enable+ OAuth, GitHub Copilot, Gemini, OpenAI-compatible endpoints, Cursor Agent+ CLI) enableconsolidation, lint, and the auto-improvement loop.- **Per-project isolation by construction**: every row and page is keyedby `(workspace_id, project_id, path)`, resolved from the caller's cwd,diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5a907691..434bd16b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- Added the `cursor` LLM provider. Consolidation calls the logged-in Cursor+ Agent CLI (`agent --print --mode ask`) so a Cursor subscription can drive+ summaries without an API key. The default model is `composer-2.5-fast`;+ `AI_MEMORY_CURSOR_AGENT` overrides the binary. The provider never passes+ `--yolo` or `--force`, because the prompt is captured session text.+## [2.6.0] - 2026-10-07diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 75a72da7..d9b65353 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -2683,6 +2683,8 @@ pub enum LlmProviderChoice {Copilot,/// OpenCode cloud API (Go by default; AI_MEMORY_LLM_BASE_URL selects Zen).Opencode,+ /// Cursor subscription via the logged-in `agent` CLI (`--print --mode ask`).+ Cursor,}/// Arguments for `embed`.diff --git a/crates/ai-memory-cli/src/commands/llm_test.rs b/crates/ai-memory-cli/src/commands/llm_test.rsindex b43330c8..32986c33 100644--- a/crates/ai-memory-cli/src/commands/llm_test.rs+++ b/crates/ai-memory-cli/src/commands/llm_test.rs@@ -86,6 +86,7 @@ impl From<LlmProviderChoice> for ProviderChoice {LlmProviderChoice::Codex => Self::Codex,LlmProviderChoice::Copilot => Self::Copilot,LlmProviderChoice::Opencode => Self::OpenCode,+ LlmProviderChoice::Cursor => Self::Cursor,}}}@@ -102,6 +103,14 @@ mod tests {);}+ #[test]+ fn cursor_choice_maps_to_runtime_provider() {+ assert_eq!(+ ProviderChoice::from(LlmProviderChoice::Cursor),+ ProviderChoice::Cursor+ );+ }+#[test]fn codex_choice_maps_to_runtime_provider() {assert_eq!(diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex 89df0382..c03d84c3 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -12,9 +12,9 @@ use std::path::{Path, PathBuf};use std::sync::Arc;use ai_memory_llm::{- AuthRequirement, Candidate, EmbedderChoice, EmbedderConfig, ExtraHeaders, FallbackLlmProvider,- LlmError, LlmProvider, LlmResult, OPENCODE_DEFAULT_MODEL, ProviderAuth, ProviderChoice,- ProviderConfig, ReasoningEffort, build_provider,+ AuthRequirement, CURSOR_DEFAULT_MODEL, Candidate, EmbedderChoice, EmbedderConfig, ExtraHeaders,+ FallbackLlmProvider, LlmError, LlmProvider, LlmResult, OPENCODE_DEFAULT_MODEL, ProviderAuth,+ ProviderChoice, ProviderConfig, ReasoningEffort, build_provider, cursor_executable,};use anyhow::{Context, Result};use figment::{@@ -661,6 +661,7 @@ pub struct RuntimeEnv {platform_home: Option<PathBuf>,codex_home: Option<PathBuf>,codex_executable: Option<PathBuf>,+ cursor_executable: Option<PathBuf>,server_url: Option<String>,auth_token: Option<String>,host_cwd: Option<String>,@@ -702,6 +703,7 @@ impl RuntimeEnv {platform_home,codex_home: env_path("CODEX_HOME"),codex_executable: env_path("AI_MEMORY_CODEX_EXECUTABLE"),+ cursor_executable: env_path("AI_MEMORY_CURSOR_AGENT"),server_url: env_string("AI_MEMORY_SERVER_URL"),auth_token: env_string("AI_MEMORY_AUTH_TOKEN"),host_cwd: env_string("AI_MEMORY_HOST_CWD"),@@ -2184,7 +2186,7 @@ impl Config {let provider = provider_choice_from_str(provider_raw).ok_or_else(|| {LlmError::NotConfigured(format!("AI_MEMORY_LLM_PROVIDER={provider_raw} is not one of \- anthropic|openai|gemini|openai-compat|openai-oauth|codex|copilot|anthropic-oauth|opencode"+ anthropic|openai|gemini|openai-compat|openai-oauth|codex|copilot|anthropic-oauth|opencode|cursor"))})?;let model = match non_empty(self.llm_model.as_deref()) {@@ -2205,6 +2207,7 @@ impl Config {));}ProviderChoice::OpenCode => OPENCODE_DEFAULT_MODEL.to_string(),+ ProviderChoice::Cursor => CURSOR_DEFAULT_MODEL.to_string(),},};Ok(Some(ProviderConfig {@@ -2244,7 +2247,7 @@ impl Config {let provider = provider_choice_from_str(provider_raw).ok_or_else(|| {LlmError::NotConfigured(format!("llm_fallbacks[{index}].provider={provider_raw} is not one of \- anthropic|openai|gemini|openai-compat|openai-oauth|codex|copilot|anthropic-oauth|opencode"+ anthropic|openai|gemini|openai-compat|openai-oauth|codex|copilot|anthropic-oauth|opencode|cursor"))})?;let model = non_empty(Some(profile.model.as_str()))@@ -2318,6 +2321,9 @@ impl Config {AuthRequirement::AnthropicOAuthToken => {ProviderAuth::anthropic_oauth_token(self.runtime_env.anthropic_oauth_token.clone())}+ AuthRequirement::CursorCli => ProviderAuth::cursor(cursor_executable(+ self.runtime_env.cursor_executable.as_deref(),+ )),}}@@ -2566,6 +2572,7 @@ impl Config {ProviderChoice::Copilot => None,ProviderChoice::AnthropicOAuth => None,ProviderChoice::OpenCode => self.runtime_env.opencode_api_key.clone(),+ ProviderChoice::Cursor => None,}}@@ -2657,6 +2664,9 @@ impl Config {AuthRequirement::AnthropicOAuthToken => {ProviderAuth::anthropic_oauth_token(self.runtime_env.anthropic_oauth_token.clone())}+ AuthRequirement::CursorCli => ProviderAuth::cursor(cursor_executable(+ self.runtime_env.cursor_executable.as_deref(),+ )),}}@@ -2713,6 +2723,7 @@ fn provider_choice_from_str(raw: &str) -> Option<ProviderChoice> {"copilot" | "github-copilot" | "github_copilot" => ProviderChoice::Copilot,"anthropic-oauth" | "anthropic_oauth" => ProviderChoice::AnthropicOAuth,"opencode" | "opencode-zen" | "opencode_zen" => ProviderChoice::OpenCode,+ "cursor" => ProviderChoice::Cursor,_ => return None,})}@@ -5066,6 +5077,26 @@ mod tests {}}+ #[test]+ fn cursor_provider_resolves_choice_default_model_and_executable() {+ let cfg = Config {+ llm_provider: Some("cursor".into()),+ runtime_env: RuntimeEnv {+ cursor_executable: Some(PathBuf::from("/opt/cursor/agent")),+ ..RuntimeEnv::default()+ },+ ..Config::default()+ };++ let provider = cfg.llm_provider_config().unwrap().unwrap();+ let auth = provider.auth.require_cursor_auth().unwrap();++ assert_eq!(provider.provider, ProviderChoice::Cursor);+ assert_eq!(provider.model, CURSOR_DEFAULT_MODEL);+ assert_eq!(auth.executable, PathBuf::from("/opt/cursor/agent"));+ assert_eq!(provider.auth.requirement(), AuthRequirement::CursorCli);+ }+fn load_with_toml(toml: &str) -> anyhow::Result<Config> {let tmp = TempDir::new().unwrap();let config_path = tmp.path().join("config.toml");diff --git a/crates/ai-memory-llm/Cargo.toml b/crates/ai-memory-llm/Cargo.tomlindex 959163df..6e8682b0 100644--- a/crates/ai-memory-llm/Cargo.toml+++ b/crates/ai-memory-llm/Cargo.toml@@ -6,7 +6,7 @@ rust-version.workspace = truelicense.workspace = truerepository.workspace = trueauthors.workspace = true-description = "LLM provider trait with typed Anthropic, OpenAI, Gemini, Codex, OpenAI OAuth, GitHub Copilot and OpenAI-compat clients."+description = "LLM provider trait with typed Anthropic, OpenAI, Gemini, Codex, OpenAI OAuth, GitHub Copilot, Cursor Agent, and OpenAI-compat clients."# One integration-test binary instead of one per file. Each binary# statically links the whole dep graph and gets scanned by macOS on# first run.diff --git a/crates/ai-memory-llm/src/auth.rs b/crates/ai-memory-llm/src/auth.rsindex a5e465fc..78288628 100644--- a/crates/ai-memory-llm/src/auth.rs+++ b/crates/ai-memory-llm/src/auth.rs@@ -49,6 +49,8 @@ pub enum AuthRequirement {/// Provider requires an Anthropic OAuth subscription token/// (from `claude setup-token`).AnthropicOAuthToken,+ /// Provider shells out to the logged-in Cursor Agent CLI.+ CursorCli,}/// Resolved Copilot auth inputs.@@ -73,6 +75,13 @@ pub struct CodexAuth {pub executable: PathBuf,}+/// Resolved inputs for the Cursor Agent CLI provider.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct CursorAuth {+ /// `agent` binary, or the path in `AI_MEMORY_CURSOR_AGENT`.+ pub executable: PathBuf,+}+/// Materialized provider credential.#[derive(Debug, Clone)]pub enum Credential {@@ -86,6 +95,8 @@ pub enum Credential {Copilot(CopilotAuth),/// Anthropic OAuth subscription token from `claude setup-token`.AnthropicOAuthToken(SecretString),+ /// Cursor Agent CLI executable. Login lives in the Cursor app, not here.+ Cursor(CursorAuth),}/// Resolved authentication for one provider instance.@@ -160,6 +171,20 @@ impl ProviderAuth {}}+ /// Resolve Cursor auth from the agent executable path.+ #[must_use]+ pub fn cursor(executable: impl Into<PathBuf>) -> Self {+ Self {+ requirement: AuthRequirement::CursorCli,+ credential: Some(Credential::Cursor(CursorAuth {+ executable: executable.into(),+ })),+ source: CredentialSource::Environment {+ name: "AI_MEMORY_CURSOR_AGENT",+ },+ }+ }+/// Resolve Anthropic OAuth auth from a subscription token (from `claude setup-token`).#[must_use]pub fn anthropic_oauth_token(token: Option<SecretString>) -> Self {@@ -236,6 +261,9 @@ impl ProviderAuth {(_, Some(Credential::AnthropicOAuthToken(_))) => Err(LlmError::NotConfigured("API key credential expected, got anthropic-oauth token".into(),)),+ (_, Some(Credential::Cursor(_))) => Err(LlmError::NotConfigured(+ "API key credential expected, got cursor agent CLI".into(),+ )),(AuthRequirement::RequiredApiKey { env_var }, None) => {Err(LlmError::NotConfigured((*env_var).into()))}@@ -258,6 +286,10 @@ impl ProviderAuth {ANTHROPIC_OAUTH_TOKEN (or CLAUDE_CODE_OAUTH_TOKEN)".into(),)),+ (AuthRequirement::CursorCli, None) => Err(LlmError::NotConfigured(+ "cursor agent executable missing; set AI_MEMORY_CURSOR_AGENT or install `agent`"+ .into(),+ )),}}@@ -270,7 +302,8 @@ impl ProviderAuth {Credential::OpenAiOAuthTokenFile(_)| Credential::Codex(_)| Credential::Copilot(_)- | Credential::AnthropicOAuthToken(_),+ | Credential::AnthropicOAuthToken(_)+ | Credential::Cursor(_),)| None => None,}@@ -333,6 +366,23 @@ impl ProviderAuth {}}+ /// Extract the Cursor Agent executable.+ ///+ /// # Errors+ /// Returns [`LlmError::NotConfigured`] if this is not Cursor CLI auth.+ pub fn require_cursor_auth(&self) -> LlmResult<CursorAuth> {+ match (&self.requirement, &self.credential) {+ (AuthRequirement::CursorCli, Some(Credential::Cursor(auth))) => Ok(auth.clone()),+ (AuthRequirement::CursorCli, None) => Err(LlmError::NotConfigured(+ "cursor agent executable missing; set AI_MEMORY_CURSOR_AGENT or install `agent`"+ .into(),+ )),+ _ => Err(LlmError::NotConfigured(+ "cursor agent credential required".into(),+ )),+ }+ }+/// Extract Copilot auth inputs.////// # Errorsdiff --git a/crates/ai-memory-llm/src/cursor_agent.rs b/crates/ai-memory-llm/src/cursor_agent.rsnew file mode 100644index 00000000..52841e2d--- /dev/null+++ b/crates/ai-memory-llm/src/cursor_agent.rs@@ -0,0 +1,283 @@+//! Cursor subscription provider.+//!+//! Consolidation calls the logged-in Cursor Agent CLI (`agent --print`)+//! instead of a platform API key. The CLI already holds the Cursor+//! subscription. Invocations stay in `--mode ask`: captured session text is+//! untrusted, and `--yolo` / `--force` would let that text run tools.++use std::path::{Path, PathBuf};+use std::process::Stdio;+use std::time::Duration;++use async_trait::async_trait;+use tokio::io::{AsyncRead, AsyncReadExt as _};+use tokio::process::Command;+use tokio::time::timeout;+use uuid::Uuid;++use crate::auth::CursorAuth;+use crate::error::{LlmError, LlmResult};+use crate::provider::LlmProvider;+use crate::types::{ChatRequest, ChatResponse, Role};++/// Model used when `AI_MEMORY_LLM_MODEL` is unset.+///+/// Fast Cursor model. Override with any id `agent --list-models` prints.+pub const CURSOR_DEFAULT_MODEL: &str = "composer-2.5-fast";++const MAX_STDOUT_BYTES: usize = 1024 * 1024;+const MAX_STDERR_BYTES: usize = 64 * 1024;++/// Chat provider that shells out to the Cursor `agent` CLI.+pub struct CursorAgentProvider {+ model: String,+ auth: CursorAuth,+ timeout: Duration,+}++impl CursorAgentProvider {+ /// Construct the provider.+ ///+ /// The executable is not probed here: a missing `agent` binary fails on+ /// the first completion with a path-specific error.+ #[must_use]+ pub fn new(auth: CursorAuth, model: impl Into<String>) -> Self {+ Self {+ model: model.into(),+ auth,+ timeout: Duration::from_secs(crate::DEFAULT_REQUEST_TIMEOUT_SECS),+ }+ }++ /// Override the CLI wait ceiling.+ #[must_use]+ pub fn with_timeout_secs(mut self, secs: u64) -> Self {+ self.timeout = Duration::from_secs(secs);+ self+ }++ async fn complete_text(+ &self,+ request: &ChatRequest,+ schema: Option<&serde_json::Value>,+ ) -> LlmResult<String> {+ let workspace = TempWorkspace::create()?;+ let body = render_request(request, schema);+ std::fs::write(workspace.path.join("request.md"), body)+ .map_err(|err| LlmError::UnexpectedShape(format!("writing cursor prompt: {err}")))?;++ let mut command = Command::new(&self.auth.executable);+ command+ .arg("--print")+ .arg("--mode")+ .arg("ask")+ .arg("--output-format")+ .arg("text")+ .arg("--trust")+ .arg("--workspace")+ .arg(&workspace.path);+ if self.model != "default" {+ command.arg("--model").arg(&self.model);+ }+ command+ .arg(+ "Read request.md in this workspace and answer it. \+ Reply with only the requested answer. Do not use tools.",+ )+ .current_dir(&workspace.path)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .kill_on_drop(true);++ let mut child = command.spawn().map_err(|err| {+ LlmError::NotConfigured(format!(+ "cursor agent CLI ({}) failed to start: {err}. Install the Cursor agent \+ or set AI_MEMORY_CURSOR_AGENT",+ self.auth.executable.display()+ ))+ })?;+ let stdout = child+ .stdout+ .take()+ .ok_or_else(|| LlmError::UnexpectedShape("cursor agent stdout missing".into()))?;+ let stderr = child+ .stderr+ .take()+ .ok_or_else(|| LlmError::UnexpectedShape("cursor agent stderr missing".into()))?;++ let collected = timeout(self.timeout, async {+ let stdout = read_capped(stdout, MAX_STDOUT_BYTES).await?;+ let stderr = read_capped(stderr, MAX_STDERR_BYTES).await?;+ let status = child.wait().await.map_err(|err| {+ LlmError::UnexpectedShape(format!("waiting for cursor agent: {err}"))+ })?;+ Ok::<_, LlmError>((status, stdout, stderr))+ })+ .await+ .map_err(|_| LlmError::Provider {+ status: 504,+ body: "cursor agent timed out".into(),+ })??;++ let (status, stdout, stderr) = collected;+ if !status.success() {+ let code = status.code().unwrap_or(1);+ let body = String::from_utf8_lossy(&stderr);+ return Err(LlmError::Provider {+ status: u16::try_from(code).unwrap_or(1),+ body: truncate_chars(&body, 500),+ });+ }+ let text = String::from_utf8_lossy(&stdout).trim().to_string();+ if text.is_empty() {+ return Err(LlmError::UnexpectedShape(+ "cursor agent returned an empty answer".into(),+ ));+ }+ Ok(text)+ }+}++#[async_trait]+impl LlmProvider for CursorAgentProvider {+ fn name(&self) -> &'static str {+ "cursor"+ }++ fn model(&self) -> &str {+ &self.model+ }++ async fn complete(&self, request: ChatRequest) -> LlmResult<ChatResponse> {+ let text = self.complete_text(&request, None).await?;+ Ok(ChatResponse {+ text,+ usage: None,+ model: self.model.clone(),+ })+ }++ async fn complete_structured_raw(+ &self,+ request: ChatRequest,+ schema: serde_json::Value,+ ) -> LlmResult<serde_json::Value> {+ let text = self.complete_text(&request, Some(&schema)).await?;+ parse_json_answer(&text)+ }+}++struct TempWorkspace {+ path: PathBuf,+}++impl TempWorkspace {+ fn create() -> LlmResult<Self> {+ let path = std::env::temp_dir().join(format!("ai-memory-cursor-{}", Uuid::now_v7()));+ std::fs::create_dir(&path).map_err(|err| {+ LlmError::UnexpectedShape(format!("creating cursor workspace: {err}"))+ })?;+ Ok(Self { path })+ }+}++impl Drop for TempWorkspace {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.path);+ }+}++fn render_request(request: &ChatRequest, schema: Option<&serde_json::Value>) -> String {+ let mut body = String::new();+ if let Some(system) = &request.system {+ body.push_str("# System\n");+ body.push_str(system);+ body.push_str("\n\n");+ }+ for message in &request.messages {+ let heading = match message.role {+ Role::User => "# User\n",+ Role::Assistant => "# Assistant\n",+ };+ body.push_str(heading);+ body.push_str(&message.content);+ body.push_str("\n\n");+ }+ if let Some(schema) = schema {+ body.push_str("# Output\nReturn one JSON value matching this schema and nothing else.\n");+ body.push_str(&schema.to_string());+ body.push('\n');+ }+ body+}++fn parse_json_answer(text: &str) -> LlmResult<serde_json::Value> {+ let stripped = strip_fence(text.trim());+ if let Ok(value) = serde_json::from_str::<serde_json::Value>(stripped) {+ return Ok(value);+ }+ let start = stripped.find(['{', '[']);+ let end = stripped.rfind(['}', ']']);+ if let (Some(start), Some(end)) = (start, end)+ && end > start+ && let Ok(value) = serde_json::from_str::<serde_json::Value>(&stripped[start..=end])+ {+ return Ok(value);+ }+ Err(LlmError::UnexpectedShape(format!(+ "cursor agent did not return JSON: {}",+ truncate_chars(stripped, 200)+ )))+}++fn strip_fence(text: &str) -> &str {+ let Some(rest) = text.strip_prefix("```") else {+ return text;+ };+ let rest = rest.trim_start_matches(|c: char| c.is_ascii_alphanumeric() || c == '-');+ let rest = rest.trim_start_matches(['\r', '\n']);+ rest.trim_end().trim_end_matches('`').trim_end()+}++fn truncate_chars(text: &str, max: usize) -> String {+ let mut out = String::new();+ for ch in text.chars() {+ if out.chars().count() >= max {+ out.push('…');+ break;+ }+ out.push(ch);+ }+ out+}++async fn read_capped(mut reader: impl AsyncRead + Unpin, cap: usize) -> LlmResult<Vec<u8>> {+ let mut buf = [0_u8; 8192];+ let mut out = Vec::new();+ loop {+ let n = reader+ .read(&mut buf)+ .await+ .map_err(|err| LlmError::UnexpectedShape(format!("reading cursor agent: {err}")))?;+ if n == 0 {+ break;+ }+ if out.len().saturating_add(n) > cap {+ return Err(LlmError::UnexpectedShape(+ "cursor agent output exceeded the size cap".into(),+ ));+ }+ out.extend_from_slice(&buf[..n]);+ }+ Ok(out)+}++/// Executable the provider will spawn. `AI_MEMORY_CURSOR_AGENT` wins; otherwise+/// the name `agent` is resolved from `PATH` at spawn time.+#[must_use]+pub fn cursor_executable(override_path: Option<&Path>) -> PathBuf {+ override_path+ .map(Path::to_path_buf)+ .unwrap_or_else(|| PathBuf::from("agent"))+}diff --git a/crates/ai-memory-llm/src/factory.rs b/crates/ai-memory-llm/src/factory.rsindex f358acee..96a2e3d8 100644--- a/crates/ai-memory-llm/src/factory.rs+++ b/crates/ai-memory-llm/src/factory.rs@@ -11,6 +11,7 @@ use crate::AnthropicProvider;use crate::CodexProvider;use crate::CopilotEmbedder;use crate::CopilotProvider;+use crate::CursorAgentProvider;use crate::GeminiProvider;use crate::OpenAiCompatProvider;use crate::OpenAiOAuthProvider;@@ -45,6 +46,8 @@ pub enum ProviderChoice {/// OpenCode cloud API (OpenAI-compatible endpoint). Defaults to the Go/// endpoint; `base_url` selects Zen's general catalogue instead.OpenCode,+ /// Cursor subscription via the logged-in `agent` CLI (`--print --mode ask`).+ Cursor,}impl ProviderChoice {@@ -61,6 +64,7 @@ impl ProviderChoice {Self::Copilot => "copilot",Self::AnthropicOAuth => "anthropic-oauth",Self::OpenCode => "opencode",+ Self::Cursor => "cursor",}}@@ -87,6 +91,7 @@ impl ProviderChoice {Self::OpenCode => AuthRequirement::RequiredApiKey {env_var: "OPENCODE_API_KEY",},+ Self::Cursor => AuthRequirement::CursorCli,}}@@ -464,6 +469,12 @@ pub fn build_provider(config: ProviderConfig) -> LlmResult<Arc<dyn LlmProvider>>.with_extra_headers(extra_headers),))}+ ProviderChoice::Cursor => {+ let auth = config.auth.require_cursor_auth()?;+ Ok(Arc::new(+ CursorAgentProvider::new(auth, config.model).with_timeout_secs(timeout),+ ))+ }ProviderChoice::OpenCode => {let key = config.auth.require_api_key()?;// Defaults to Go; an operator reaches Zen's general catalogue@@ -506,6 +517,8 @@ mod tests {ProviderChoice::OpenAiOAuth,ProviderChoice::Copilot,ProviderChoice::AnthropicOAuth,+ ProviderChoice::Codex,+ ProviderChoice::Cursor,] {assert!(!choice.endpoint_is_operator_chosen(),@@ -558,6 +571,11 @@ mod tests {ProviderChoice::AnthropicOAuth.auth_requirement(),AuthRequirement::AnthropicOAuthToken);+ assert_eq!(ProviderChoice::Cursor.name(), "cursor");+ assert_eq!(+ ProviderChoice::Cursor.auth_requirement(),+ AuthRequirement::CursorCli+ );}/// `reqwest` sends no `User-Agent` unless configured, which left everydiff --git a/crates/ai-memory-llm/src/lib.rs b/crates/ai-memory-llm/src/lib.rsindex efcf3565..28be970a 100644--- a/crates/ai-memory-llm/src/lib.rs+++ b/crates/ai-memory-llm/src/lib.rs@@ -23,6 +23,9 @@//! * **Gemini**: `generationConfig.responseMimeType = "application/json"`//! plus `responseSchema` (OpenAPI 3 subset; `$ref`s inlined,//! Draft-2020-12 keywords stripped before send).+//! * **Cursor**: the logged-in `agent` CLI in `--mode ask`. No HTTP client+//! and no copied token; `--yolo` is never passed because the prompt is+//! captured session text.//! * **OpenAI-compat** (Ollama, vLLM, LM Studio): we ask for//! `response_format: { type: "json_object" }` when supported,//! otherwise parse the first balanced `{…}` from the text body.@@ -71,6 +74,7 @@ pub mod anthropic;pub mod auth;pub mod codex;pub mod copilot;+pub mod cursor_agent;pub mod embedding;pub mod error;pub mod factory;@@ -97,7 +101,7 @@ mod text;pub use anthropic::AnthropicProvider;pub use auth::{- AuthRequirement, CodexAuth, CopilotAuth, Credential, CredentialSource, ProviderAuth,+ AuthRequirement, CodexAuth, CopilotAuth, Credential, CredentialSource, CursorAuth, ProviderAuth,};pub use codex::CodexProvider;pub use copilot::{@@ -106,6 +110,7 @@ pub use copilot::{GITHUB_ACCESS_TOKEN_URL, GITHUB_COPILOT_CLIENT_ID, GITHUB_COPILOT_TOKEN_URL,GITHUB_DEVICE_CODE_URL,};+pub use cursor_agent::{CURSOR_DEFAULT_MODEL, CursorAgentProvider, cursor_executable};pub use embedding::{Embedder, OpenAiCompatEmbedder, OpenAiEmbedder, SyntheticEmbedder, VoyageEmbedder, cosine,};diff --git a/crates/ai-memory-llm/tests/suite/cursor_provider.rs b/crates/ai-memory-llm/tests/suite/cursor_provider.rsnew file mode 100644index 00000000..99c54e66--- /dev/null+++ b/crates/ai-memory-llm/tests/suite/cursor_provider.rs@@ -0,0 +1,107 @@+//! Offline tests for the Cursor Agent CLI provider.+//!+//! The fake executable is a shell script, so these tests are Unix-only.+//! They assert the argv contract: ask mode, no `--yolo` / `--force`.++#![cfg(unix)]++use std::os::unix::fs::PermissionsExt as _;+use std::path::{Path, PathBuf};++use ai_memory_llm::{+ CURSOR_DEFAULT_MODEL, ChatRequest, CursorAgentProvider, LlmProvider, ProviderAuth,+};++fn sh_single(value: &str) -> String {+ format!("'{}'", value.replace('\'', "'\\''"))+}++fn fake_agent(dir: &Path, sink: &Path, stdout: &str) -> PathBuf {+ let path = dir.join("agent");+ let script = format!(+ "#!/bin/sh\nprintf '%s\\n' \"$@\" > {}\ncase \" $* \" in\n *' --yolo '*|*' --force '*) echo refusing >&2; exit 2 ;;\nesac\nprintf '%s\\n' {}\n",+ sh_single(&sink.display().to_string()),+ sh_single(stdout),+ );+ std::fs::write(&path, script).unwrap();+ let mut perms = std::fs::metadata(&path).unwrap().permissions();+ perms.set_mode(0o755);+ std::fs::set_permissions(&path, perms).unwrap();+ path+}++struct TempDir(PathBuf);++impl TempDir {+ fn new() -> Self {+ let path =+ std::env::temp_dir().join(format!("ai-memory-cursor-test-{}", uuid::Uuid::now_v7()));+ std::fs::create_dir(&path).unwrap();+ Self(path)+ }+}++impl Drop for TempDir {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+}++fn provider(executable: PathBuf, model: &str) -> CursorAgentProvider {+ CursorAgentProvider::new(+ ProviderAuth::cursor(executable)+ .require_cursor_auth()+ .expect("cursor executable resolves"),+ model,+ )+}++#[tokio::test]+async fn ask_mode_returns_text_without_yolo() {+ let dir = TempDir::new();+ let sink = dir.0.join("argv");+ let executable = fake_agent(&dir.0, &sink, "OK");+ let response = provider(executable, CURSOR_DEFAULT_MODEL)+ .complete(ChatRequest::user_prompt("Reply with OK"))+ .await+ .unwrap();+ assert_eq!(response.text, "OK");+ let argv = std::fs::read_to_string(&sink).unwrap();+ assert!(argv.contains("--mode\nask\n"), "{argv}");+ assert!(argv.contains("--print\n"), "{argv}");+ assert!(!argv.contains("--yolo"), "{argv}");+ assert!(!argv.contains("--force"), "{argv}");+ assert!(argv.contains(CURSOR_DEFAULT_MODEL), "{argv}");+}++#[tokio::test]+async fn default_model_omits_the_model_flag() {+ let dir = TempDir::new();+ let sink = dir.0.join("argv");+ let executable = fake_agent(&dir.0, &sink, "{\"answer\":\"ok\"}");+ let value = provider(executable, "default")+ .complete_structured_raw(+ ChatRequest::user_prompt("status"),+ serde_json::json!({"type": "object"}),+ )+ .await+ .unwrap();+ assert_eq!(value["answer"], "ok");+ let argv = std::fs::read_to_string(&sink).unwrap();+ assert!(!argv.contains("--model"), "{argv}");+}++#[tokio::test]+async fn fenced_json_is_parsed() {+ let dir = TempDir::new();+ let sink = dir.0.join("argv");+ let executable = fake_agent(&dir.0, &sink, "```json\n{\"answer\":1}\n```");+ let value = provider(executable, "default")+ .complete_structured_raw(+ ChatRequest::user_prompt("status"),+ serde_json::json!({"type": "object"}),+ )+ .await+ .unwrap();+ assert_eq!(value["answer"], 1);+}diff --git a/crates/ai-memory-llm/tests/suite/mod.rs b/crates/ai-memory-llm/tests/suite/mod.rsindex b034c653..4531bb28 100644--- a/crates/ai-memory-llm/tests/suite/mod.rs+++ b/crates/ai-memory-llm/tests/suite/mod.rs@@ -4,6 +4,7 @@mod copilot_embedder;mod copilot_provider;+mod cursor_provider;mod extra_headers_on_the_wire;mod fallback_provider;mod openai_compat_embedder;diff --git a/docs/install.md b/docs/install.mdindex 8c9e5231..240d68f0 100644--- a/docs/install.md+++ b/docs/install.md@@ -1892,6 +1892,7 @@ ai-memory works in three intensity tiers:| **+ 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 || **+ Codex credential reuse** | Same LLM features using the Codex CLI-owned login without copying or owning its refresh token | `AI_MEMORY_LLM_PROVIDER=codex` + an authenticated Codex CLI | 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 |+| **+ Cursor subscription** | Same LLM features using the logged-in Cursor Agent CLI. Read-only `--mode ask`; does not pass `--yolo` | `AI_MEMORY_LLM_PROVIDER=cursor` + `agent` on `PATH` (or `AI_MEMORY_CURSOR_AGENT`) | Uses your Cursor subscription || **+ LLM reranking** | At most one relevance pass over up to 30 bounded project/scopes search candidates; normal order is preserved on invalid, failed, timed-out, or concurrency-saturated responses | `AI_MEMORY_RERANKER=llm` + any configured LLM provider | One LLM call per eligible query, at most four concurrently || **+ Hybrid retrieval** | Adds vector cosine similarity to FTS5 + entity + graph RRF. Better recall on paraphrased queries | `AI_MEMORY_EMBEDDING_PROVIDER=openai` + `OPENAI_API_KEY` (or `EMBEDDING_API_KEY`) | ~$0.0001 / page on backfill |@@ -1907,6 +1908,7 @@ If you set only the provider, ai-memory picks a sensible default:| `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. Optional `AI_MEMORY_LLM_REASONING_EFFORT` (`none`/`minimal`/`low`/`medium`/`high`/`xhigh`/`max`/`ultra`/`persistent`) is mapped to each provider's native reasoning field; omit it to keep the model default. || `AI_MEMORY_LLM_PROVIDER=codex` | `gpt-5.6-luna` | Reuses only `access_token` and `account_id` from Codex's `auth.json`; token renewal is delegated to `codex app-server --stdio`. || `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. |+| `AI_MEMORY_LLM_PROVIDER=cursor` | `composer-2.5-fast` | Cursor subscription via `agent --print --mode ask --trust`. No API key and no `--yolo`. Override the binary with `AI_MEMORY_CURSOR_AGENT`. Any id from `agent --list-models` works as `AI_MEMORY_LLM_MODEL`. || `AI_MEMORY_LLM_PROVIDER=gemini` | `gemini-3.5-flash` | Google's hosted option with a generous free tier. ai-memory disables Gemini 3.5 Flash's default dynamic thinking so hidden thought tokens do not truncate strict JSON. Set `GEMINI_API_KEY` (or `GOOGLE_API_KEY`). || `AI_MEMORY_LLM_PROVIDER=opencode` | `mimo-v2.6-flash` | [OpenCode](https://opencode.ai) cloud API. Defaults to the **Go** endpoint, `opencode.ai/zen/go/v1` — a cost-optimised model subset. Published Responses models, including GPT-5.6 Luna and GPT-6 Luna, use `/responses`; supported Claude and Qwen Messages models use `/messages`. MiniMax M3/M2.7 and Qwen3.8 Max use Messages on Go and Chat Completions on Zen; Go Muse Contributor models use Responses. Changing the base URL reselects the transport and preserves request settings. See the [Go](https://opencode.ai/docs/go/#endpoints) and [Zen](https://opencode.ai/docs/zen/#endpoints) endpoint tables. For **Zen**'s full catalogue, set `AI_MEMORY_LLM_BASE_URL=https://opencode.ai/zen/v1` plus an `AI_MEMORY_LLM_MODEL` from it, such as `claude-sonnet-5-5`; the default model id is Go's. Requests identify ai-memory by version and reuse one session header across related attempts. Both endpoints take `OPENCODE_API_KEY` (key from `opencode.ai/auth`). Alias: `opencode-zen` — historical, and it selects Go like the others; the endpoint is chosen by the base URL, not the alias, with no automatic billing-product switch. || `AI_MEMORY_EMBEDDING_PROVIDER=openai` | `text-embedding-3-small` (1536-dim) | 5× cheaper than `-3-large` with marginal recall loss. |diff --git a/docs/llm-providers.md b/docs/llm-providers.mdindex 21d98e7c..b1255932 100644--- a/docs/llm-providers.md+++ b/docs/llm-providers.md@@ -47,6 +47,7 @@ Recommended defaults:| `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. || `codex` | `gpt-5.6-luna` | Reuse the Codex CLI-owned `auth.json`; access-token refresh remains owned by `codex app-server`. |+| `cursor` | `composer-2.5-fast` | Cursor subscription via the logged-in `agent` CLI. Runs `agent --print --mode ask` (read-only). Does not pass `--yolo`. || `copilot` | `gpt-5.5` | GitHub Copilot Chat backend via `ai-memory auth login copilot` or `COPILOT_GITHUB_TOKEN`; requires a Copilot subscription. || `gemini` | `gemini-3.5-flash` | Google-hosted option with a generous free tier. || `opencode` | `mimo-v2.6-flash` | OpenCode Go or Zen via `OPENCODE_API_KEY`. Go is the default endpoint; `AI_MEMORY_LLM_BASE_URL` selects Zen. Set `AI_MEMORY_LLM_MODEL` to an id the chosen endpoint serves. |@@ -75,6 +76,20 @@ ai-memory llm-test --provider codex --model gpt-5.6-luna --prompt "Reply with OKai-memory llm-test --provider codex --model gpt-5.6-luna --structured --prompt "Return a short answer"```+`cursor` uses the Cursor Agent already logged in on this machine. Set+`AI_MEMORY_LLM_PROVIDER=cursor`. The default model is `composer-2.5-fast`;+any id from `agent --list-models` works. `AI_MEMORY_CURSOR_AGENT` overrides+the binary. The provider writes the prompt into a temporary workspace and+calls `agent --print --mode ask --trust`. It does not pass `--yolo` or+`--force`: consolidation text is untrusted captured content, and those flags+would allow tool execution.++```bash+export AI_MEMORY_LLM_PROVIDER=cursor+export AI_MEMORY_LLM_MODEL=composer-2.5-fast+ai-memory llm-test --provider cursor --model composer-2.5-fast --prompt "Reply with OK"+```+Codex credential storage mode `file` is supported. `auto` works only when itseffective credential is present in `auth.json`; keyring-only and ephemeralcredentials are not read and produce an actionable missing-auth-file error.diff --git a/evals/src/ab.rs b/evals/src/ab.rsindex f2ee5cd1..bbdcb135 100644--- a/evals/src/ab.rs+++ b/evals/src/ab.rs@@ -328,6 +328,7 @@ fn resolve_provider(side: &str, args: &AbArgs) -> Result<ResolvedConfig> {base_url.clone(),),AuthRequirement::AnthropicOAuthToken => ProviderAuth::anthropic_oauth_token(api_key),+ AuthRequirement::CursorCli => ProviderAuth::cursor("agent"),};Ok(ResolvedConfig {diff --git a/evals/src/retrieval/qa.rs b/evals/src/retrieval/qa.rsindex 3b575df0..47ee206f 100644--- a/evals/src/retrieval/qa.rs+++ b/evals/src/retrieval/qa.rs@@ -367,6 +367,7 @@ fn build_llm_provider(ProviderAuth::copilot(tf.to_path_buf(), None, None, base_url.map(str::to_string))}AuthRequirement::AnthropicOAuthToken => ProviderAuth::anthropic_oauth_token(api_key),+ AuthRequirement::CursorCli => ProviderAuth::cursor("agent"),};let config = ProviderConfig {