Skip to content

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

Rust

Fix CLI OIDC bearer fallback

Djalma Júnior9912e48b9c48
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bc6009ab..33e9193c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -30,6 +30,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
roots after marker validation; custom `--target-dir` skill roots remain a
manual cleanup path.
+### Changed
+- Agent-facing routing prompts and auto-scope docs now call out that static MCP
+ clients running parallel sessions need explicit scope arguments or a
+ session-aware bridge that forwards the real lifecycle-hook session id.
+
+### Fixed
+- Thin-client HTTP CLI commands (`status`, `search`, `read-page`, `write-page`,
+ `delete-page`, `backup`, `embed`, `reindex`, and related admin commands) now
+ fall back to a stored OIDC device-flow token from `auth.json` when
+ `AI_MEMORY_AUTH_TOKEN` / `[auth].bearer_token` is absent. Static bearer tokens
+ still take precedence.
+
## [1.3.0] - 2026-06-24
### Added
diff --git a/README.md b/README.md
index e5f56ab4..7ed06437 100644
--- a/README.md
+++ b/README.md
@@ -373,7 +373,15 @@ ai-memory install-hooks --agent claude-code --apply \
OIDC hook auth requires the native `ai-memory hook ...` command path. The Docker
wrapper keeps shell-script hooks by default; set up OIDC from a native release
-binary or source install.
+binary or source install. Thin-client HTTP commands such as `ai-memory status`
+and `ai-memory search` also use the stored OIDC access token when no static
+`AI_MEMORY_AUTH_TOKEN` / `[auth].bearer_token` is configured; the static bearer
+still wins when present.
+
+OIDC/Keycloak session ids are login-provider sessions, not ai-memory agent
+sessions. Shared servers that rely on `[auto_scope]` session isolation still
+need explicit `workspace` + `project` / `scopes`, or a bridge that forwards the
+real lifecycle-hook session id on MCP requests.
**Want HTTPS?** ai-memory deliberately does not terminate TLS itself —
the right answer is a battle-tested reverse proxy in front of it.
diff --git a/crates/ai-memory-cli/src/auth_bearer.rs b/crates/ai-memory-cli/src/auth_bearer.rs
new file mode 100644
index 00000000..78b4b2a3
--- /dev/null
+++ b/crates/ai-memory-cli/src/auth_bearer.rs
@@ -0,0 +1,94 @@
+//! Bearer-token resolution shared by lifecycle hooks and thin HTTP clients.
+//!
+//! Static CLI/config tokens always win. When they are absent, a stored OIDC
+//! device-flow token is loaded from `auth.json`, refreshed if stale, and used
+//! as the bearer for server HTTP calls.
+
+use std::path::Path;
+
+use ai_memory_llm::{OidcToken, refresh_access_token};
+use secrecy::ExposeSecret as _;
+
+/// Resolve the bearer for one server request: explicit/static token first,
+/// stored OIDC token second, and no token last.
+pub async fn resolve_bearer(
+ client: &reqwest::Client,
+ auth_path: &Path,
+ static_token: Option<&str>,
+) -> Option<String> {
+ match static_token.filter(|t| !t.is_empty()) {
+ Some(t) => Some(t.to_string()),
+ None => resolve_oidc(client, auth_path).await,
+ }
+}
+
+/// Load the stored OIDC token, refreshing and persisting it when stale.
+///
+/// Returns the access token, or `None` when there is no token or refresh
+/// failed. Failing open to "no bearer" preserves the old unauthenticated CLI
+/// behavior and lets the server return the authoritative auth error.
+pub async fn resolve_oidc(client: &reqwest::Client, auth_path: &Path) -> Option<String> {
+ let mut token = OidcToken::load(auth_path).ok().flatten()?;
+ if token.needs_refresh() {
+ let Ok(refreshed) = refresh_access_token(client, &token).await else {
+ return None;
+ };
+ let _ = refreshed.save(auth_path);
+ token = refreshed;
+ }
+ Some(token.access.expose_secret().to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ use secrecy::SecretString;
+
+ fn save_oidc_token(path: &Path, access: &str) {
+ let token = OidcToken {
+ access: SecretString::from(access.to_string()),
+ refresh: SecretString::from("refresh-token".to_string()),
+ expires_at_ms: u64::MAX,
+ issuer: "https://issuer.example.com/realms/team".to_string(),
+ client_id: "ai-memory-cli".to_string(),
+ token_endpoint: "https://issuer.example.com/token".to_string(),
+ };
+ token.save(path).expect("save test OIDC token");
+ }
+
+ #[tokio::test]
+ async fn static_token_wins_over_stored_oidc() {
+ let tmp = tempfile::tempdir().unwrap();
+ let auth_path = tmp.path().join("auth.json");
+ save_oidc_token(&auth_path, "oidc-access");
+ let client = reqwest::Client::new();
+
+ let bearer = resolve_bearer(&client, &auth_path, Some("static-token")).await;
+
+ assert_eq!(bearer.as_deref(), Some("static-token"));
+ }
+
+ #[tokio::test]
+ async fn stored_oidc_is_used_when_static_token_is_absent() {
+ let tmp = tempfile::tempdir().unwrap();
+ let auth_path = tmp.path().join("auth.json");
+ save_oidc_token(&auth_path, "oidc-access");
+ let client = reqwest::Client::new();
+
+ let bearer = resolve_bearer(&client, &auth_path, None).await;
+
+ assert_eq!(bearer.as_deref(), Some("oidc-access"));
+ }
+
+ #[tokio::test]
+ async fn empty_when_static_and_oidc_are_absent() {
+ let tmp = tempfile::tempdir().unwrap();
+ let auth_path = tmp.path().join("auth.json");
+ let client = reqwest::Client::new();
+
+ let bearer = resolve_bearer(&client, &auth_path, None).await;
+
+ assert!(bearer.is_none());
+ }
+}
diff --git a/crates/ai-memory-cli/src/commands/audit_contamination.rs b/crates/ai-memory-cli/src/commands/audit_contamination.rs
index cc2cfa95..340829de 100644
--- a/crates/ai-memory-cli/src/commands/audit_contamination.rs
+++ b/crates/ai-memory-cli/src/commands/audit_contamination.rs
@@ -50,7 +50,7 @@ struct Finding {
/// Returns an error if the server is unreachable, returns non-2xx, or the
/// response can't be parsed.
pub async fn run(config: &Config, args: AuditContaminationArgs) -> Result<()> {
- let ep = ServerEndpoint::from_config(config);
+ let ep = ServerEndpoint::from_config_resolving_auth(config).await;
let query = scope_query(&args)?;
let report: Report = get_json(&ep, "/admin/audit-contamination", &query).await?;
diff --git a/crates/ai-memory-cli/src/commands/auto_improve.rs b/crates/ai-memory-cli/src/commands/auto_improve.rs
index 3661cab8..ed21af26 100644
--- a/crates/ai-memory-cli/src/commands/auto_improve.rs
+++ b/crates/ai-memory-cli/src/commands/auto_improve.rs
@@ -60,7 +60,7 @@ struct ProposalOutcome {
/// # Errors
/// Returns an error if the server is unreachable or rejects the review request.
pub async fn run(config: &Config, args: AutoImproveArgs) -> Result<()> {
- let endpoint = ServerEndpoint::from_config(config);
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let project = super::resolve_project_name(config, args.project.as_deref())?;
let settings = &config.auto_improve;
let request = AutoImproveRequest {
diff --git a/crates/ai-memory-cli/src/commands/auto_improve_report.rs b/crates/ai-memory-cli/src/commands/auto_improve_report.rs
index 55bd15be..8f5ec974 100644
--- a/crates/ai-memory-cli/src/commands/auto_improve_report.rs
+++ b/crates/ai-memory-cli/src/commands/auto_improve_report.rs
@@ -30,7 +30,7 @@ struct AutoImproveReportStageResponse {
/// # Errors
/// Returns an error if the server is unreachable or rejects the read-only report request.
pub async fn run(config: &Config, args: AutoImproveReportArgs) -> Result<()> {
- let endpoint = ServerEndpoint::from_config(config);
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let project = super::resolve_project_name(config, args.project.as_deref())?;
let request = AutoImproveReportRequest {
workspace: args.workspace,
diff --git a/crates/ai-memory-cli/src/commands/backup.rs b/crates/ai-memory-cli/src/commands/backup.rs
index 51fca6f4..088bb2e0 100644
--- a/crates/ai-memory-cli/src/commands/backup.rs
+++ b/crates/ai-memory-cli/src/commands/backup.rs
@@ -17,7 +17,7 @@ use crate::http_client::{ServerEndpoint, post_to_file};
/// Returns an error if the POST to `/admin/backup` fails, the server
/// returns a non-2xx status, or the output file cannot be written.
pub async fn run(config: &Config, args: BackupArgs) -> Result<()> {
- let endpoint = ServerEndpoint::from_config(config);
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let dest = &args.to;
if let Some(parent) = dest.parent()
&& !parent.as_os_str().is_empty()
diff --git a/crates/ai-memory-cli/src/commands/bootstrap.rs b/crates/ai-memory-cli/src/commands/bootstrap.rs
index 3a69f74c..669363a9 100644
--- a/crates/ai-memory-cli/src/commands/bootstrap.rs
+++ b/crates/ai-memory-cli/src/commands/bootstrap.rs
@@ -31,7 +31,7 @@ use crate::http_client::{ServerEndpoint, post_json};
/// Bails when the resolved repo path cannot be inspected, when source
/// collection fails, or when the server returns a non-2xx response.
pub async fn run(config: &Config, args: BootstrapArgs) -> Result<()> {
- let ep = ServerEndpoint::from_config(config);
+ let ep = ServerEndpoint::from_config_resolving_auth(config).await;
info!(server = %ep.url, auth = ep.auth_token.is_some(), "bootstrap CLI configured");
// ---- repo path — auto-detect via libgit2, fall back to CWD ----
diff --git a/crates/ai-memory-cli/src/commands/checkpoints.rs b/crates/ai-memory-cli/src/commands/checkpoints.rs
index 177f244c..2f4ae826 100644
--- a/crates/ai-memory-cli/src/commands/checkpoints.rs
+++ b/crates/ai-memory-cli/src/commands/checkpoints.rs
@@ -21,7 +21,7 @@ struct CheckpointResponse {
/// Returns an error if the server is unreachable or returns a non-2xx
/// response.
pub async fn run(config: &Config, args: CheckpointsArgs) -> Result<()> {
- let endpoint = ServerEndpoint::from_config(config);
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let limit = args.limit.to_string();
let checkpoints: Vec<CheckpointResponse> = get_json(
&endpoint,
diff --git a/crates/ai-memory-cli/src/commands/commit.rs b/crates/ai-memory-cli/src/commands/commit.rs
index 9c262122..09c7e28e 100644
--- a/crates/ai-memory-cli/src/commands/commit.rs
+++ b/crates/ai-memory-cli/src/commands/commit.rs
@@ -29,7 +29,7 @@ struct CommitResponse {
/// Returns an error if the server is unreachable or returns a non-2xx
/// response.
pub async fn run(config: &Config, args: CommitArgs) -> Result<()> {
- let endpoint = ServerEndpoint::from_config(config);
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let resp: CommitResponse = post_json(
&endpoint,
"/admin/commit",
diff --git a/crates/ai-memory-cli/src/commands/curator.rs b/crates/ai-memory-cli/src/commands/curator.rs
index 410e585c..634829a6 100644
--- a/crates/ai-memory-cli/src/commands/curator.rs
+++ b/crates/ai-memory-cli/src/commands/curator.rs
@@ -34,7 +34,7 @@ pub async fn run(config: &Config, args: CuratorArgs) -> Result<()> {
bail!("choose either --dry-run or --stage, not both");
}
let dry_run = args.dry_run || !args.stage;
- let endpoint = ServerEndpoint::from_config(config);
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let project = super::resolve_project_name(config, args.project.as_deref())?;
let request = CuratorRequest {
workspace: args.workspace,
diff --git a/crates/ai-memory-cli/src/commands/delete_page.rs b/crates/ai-memory-cli/src/commands/delete_page.rs
index 83d49813..4edadc78 100644
--- a/crates/ai-memory-cli/src/commands/delete_page.rs
+++ b/crates/ai-memory-cli/src/commands/delete_page.rs
@@ -39,7 +39,7 @@ pub async fn run(config: &Config, args: DeletePageArgs) -> Result<()> {
// root. Keeps delete + read-back pairs targeting the same project.
let project = super::resolve_project_name(config, args.project.as_deref())?;
- let endpoint = ServerEndpoint::from_config(config);
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let resp: DeletePageResponseBody = post_json(
&endpoint,
"/admin/delete-page",
diff --git a/crates/ai-memory-cli/src/commands/embed.rs b/crates/ai-memory-cli/src/commands/embed.rs
index 8c01fee5..5cfb68a8 100644
--- a/crates/ai-memory-cli/src/commands/embed.rs
+++ b/crates/ai-memory-cli/src/commands/embed.rs
@@ -27,7 +27,7 @@ struct EmbedRequest {
/// Returns an error if the server is unreachable or returns a non-2xx
/// response.
pub async fn run(config: &Config, args: EmbedArgs) -> Result<()> {
- let endpoint = ServerEndpoint::from_config(config);
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
// Model migrations must reach stale rows in every project namespace.
// Without an explicit `--project`, `--force` / `--reembed` fans out
// across the whole workspace instead of the CWD-derived project only.
diff --git a/crates/ai-memory-cli/src/commands/forget_sweep.rs b/crates/ai-memory-cli/src/commands/forget_sweep.rs
index e58df434..9ebf6072 100644
--- a/crates/ai-memory-cli/src/commands/forget_sweep.rs
+++ b/crates/ai-memory-cli/src/commands/forget_sweep.rs
@@ -24,7 +24,7 @@ struct ForgetSweepRequest {
/// Returns an error if the server is unreachable or returns a non-2xx
/// response.
pub async fn run(config: &Config, args: ForgetSweepArgs) -> Result<()> {
- let endpoint = ServerEndpoint::from_config(config);
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let project = super::resolve_project_name(config, args.project.as_deref())?;
let report: serde_json::Value = post_json(
&endpoint,
diff --git a/crates/ai-memory-cli/src/commands/hook_spool.rs b/crates/ai-memory-cli/src/commands/hook_spool.rs
index 13c4f85b..08093694 100644
--- a/crates/ai-memory-cli/src/commands/hook_spool.rs
+++ b/crates/ai-memory-cli/src/commands/hook_spool.rs
@@ -22,8 +22,6 @@ use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
-use ai_memory_llm::{OidcToken, refresh_access_token};
-use secrecy::ExposeSecret as _;
use serde::{Deserialize, Serialize};
use super::hook_capture::{BatchOutcome, PostOutcome, build_client, post_batch, post_hook};
@@ -441,7 +439,9 @@ async fn entry_bearer(
AuthMode::Anonymous => None,
AuthMode::Oidc => {
if oidc_cache.is_none() {
- *oidc_cache = Some(resolve_oidc(client, data_dir).await);
+ *oidc_cache = Some(
+ crate::auth_bearer::resolve_oidc(client, &data_dir.join("auth.json")).await,
+ );
}
oidc_cache.clone().flatten()
}
@@ -526,25 +526,7 @@ pub async fn resolve_bearer(
data_dir: &Path,
auth_token: Option<&str>,
) -> Option<String> {
- match auth_token {
- Some(t) => Some(t.to_string()),
- None => resolve_oidc(client, data_dir).await,
- }
-}
-
-/// Load the stored OIDC token, refreshing (and persisting) it when stale.
-/// Returns the access token, or None when there's no token / refresh failed.
-async fn resolve_oidc(client: &reqwest::Client, data_dir: &Path) -> Option<String> {
- let auth_path = data_dir.join("auth.json");
- let mut token = OidcToken::load(&auth_path).ok().flatten()?;
- if token.needs_refresh() {
- let Ok(refreshed) = refresh_access_token(client, &token).await else {
- return None;
- };
- let _ = refreshed.save(&auth_path);
- token = refreshed;
- }
- Some(token.access.expose_secret().to_string())
+ crate::auth_bearer::resolve_bearer(client, &data_dir.join("auth.json"), auth_token).await
}
fn prune_spool_file_count(spool: &Path) {
diff --git a/crates/ai-memory-cli/src/commands/lint.rs b/crates/ai-memory-cli/src/commands/lint.rs
index 4217cdca..a73c28db 100644
--- a/crates/ai-memory-cli/src/commands/lint.rs
+++ b/crates/ai-memory-cli/src/commands/lint.rs
@@ -22,7 +22,7 @@ struct LintRequest {
/// Returns an error if the server is unreachable or returns a non-2xx
/// response.
pub async fn run(config: &Config, args: LintArgs) -> Result<()> {
- let endpoint = ServerEndpoint::from_config(config);
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let project = super::resolve_project_name(config, args.project.as_deref())?;
let report: serde_json::Value = post_json(
&endpoint,
diff --git a/crates/ai-memory-cli/src/commands/move_project.rs b/crates/ai-memory-cli/src/commands/move_project.rs
index ea3d1459..c01fcc27 100644
--- a/crates/ai-memory-cli/src/commands/move_project.rs
+++ b/crates/ai-memory-cli/src/commands/move_project.rs
@@ -50,7 +50,7 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {
);
}
- let endpoint = ServerEndpoint::from_config(config);
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let report: serde_json::Value = post_json(
&endpoint,
"/admin/move-project",
diff --git a/crates/ai-memory-cli/src/commands/pending_writes.rs b/crates/ai-memory-cli/src/commands/pending_writes.rs
index b6255505..dcae2c68 100644
--- a/crates/ai-memory-cli/src/commands/pending_writes.rs
+++ b/crates/ai-memory-cli/src/commands/pending_writes.rs
@@ -35,7 +35,7 @@ struct DiffResponse {
}
pub async fn run(config: &Config, args: PendingWritesArgs) -> Result<()> {
- let ep = ServerEndpoint::from_config(config);
+ let ep = ServerEndpoint::from_config_resolving_auth(config).await;
match args.command {
PendingWritesCommand::List(args) => list(config, &ep, args).await,
PendingWritesCommand::Show(args) => show(config, &ep, args).await,
diff --git a/crates/ai-memory-cli/src/commands/purge_project.rs b/crates/ai-memory-cli/src/commands/purge_project.rs
index cfe85ac7..14c9422d 100644
--- a/crates/ai-memory-cli/src/commands/purge_project.rs
+++ b/crates/ai-memory-cli/src/commands/purge_project.rs
@@ -37,7 +37,7 @@ pub async fn run(config: &Config, args: PurgeProjectArgs) -> Result<()> {
);
}
- let endpoint = ServerEndpoint::from_config(config);
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let report: serde_json::Value = post_json(
&endpoint,
"/admin/purge-project",
diff --git a/crates/ai-memory-cli/src/commands/read_page.rs b/crates/ai-memory-cli/src/commands/read_page.rs
index e2f7ba77..70e84dd3 100644
--- a/crates/ai-memory-cli/src/commands/read_page.rs
+++ b/crates/ai-memory-cli/src/commands/read_page.rs
@@ -36,7 +36,7 @@ struct PageContent {
/// Returns an error if the server is unreachable, returns non-2xx,
/// or neither `--path` nor a query is supplied.
pub async fn run(config: &Config, args: ReadPageArgs) -> Result<()> {
- let ep = ServerEndpoint::from_config(config);
+ let ep = ServerEndpoint::from_config_resolving_auth(config).await;
let project = super::resolve_project_name(config, args.project.as_deref())?;
let page: PageContent = if let Some(ref raw_path) = args.path {
diff --git a/crates/ai-memory-cli/src/commands/rename_project.rs b/crates/ai-memory-cli/src/commands/rename_project.rs
index ba1cf388..64f0d61d 100644
--- a/crates/ai-memory-cli/src/commands/rename_project.rs
+++ b/crates/ai-memory-cli/src/commands/rename_project.rs
@@ -16,7 +16,7 @@ use crate::http_client::{ServerEndpoint, post_json};
/// Returns an error when the server is unreachable or returns a non-2xx
/// response (e.g. 404 workspace/project not found, 422 name taken or invalid).
pub async fn run(config: &Config, args: RenameProjectArgs) -> Result<()> {
- let endpoint = ServerEndpoint::from_config(config);
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let from = super::resolve_project_name(config, args.from.as_deref())?;
let body = serde_json::json!({
"workspace": args.workspace,
diff --git a/crates/ai-memory-cli/src/commands/reorg.rs b/crates/ai-memory-cli/src/commands/reorg.rs
index b7745544..561d1144 100644
--- a/crates/ai-memory-cli/src/commands/reorg.rs
+++ b/crates/ai-memory-cli/src/commands/reorg.rs
@@ -46,7 +46,7 @@ struct ReorgReport {
/// Returns an error if the server is unreachable or returns a non-2xx
/// response.
pub async fn run(config: &Config, args: ReorgArgs) -> Result<()> {
- let endpoint = ServerEndpoint::from_config(config);
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let report: ReorgReport = post_json(
&endpoint,
"/admin/reorg",
diff --git a/crates/ai-memory-cli/src/commands/restore_page.rs b/crates/ai-memory-cli/src/commands/restore_page.rs
index d26dc969..c9554be6 100644
--- a/crates/ai-memory-cli/src/commands/restore_page.rs
+++ b/crates/ai-memory-cli/src/commands/restore_page.rs
@@ -33,7 +33,7 @@ struct RestorePageResponse {
/// restored, or the restored page cannot be reindexed.
pub async fn run(config: &Config, args: RestorePageArgs) -> Result<()> {
let project = super::resolve_project_name(config, args.project.as_deref())?;
- let endpoint = ServerEndpoint::from_config(config);
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let resp: RestorePageResponse = post_json(
&endpoint,
"/admin/restore-page",
diff --git a/crates/ai-memory-cli/src/commands/search.rs b/crates/ai-memory-cli/src/commands/search.rs
index c21ea4f3..fc81ce4d 100644
--- a/crates/ai-memory-cli/src/commands/search.rs
+++ b/crates/ai-memory-cli/src/commands/search.rs
@@ -24,7 +24,7 @@ struct Hit {
/// # Errors
/// Returns an error if the server is unreachable or returns non-2xx.
pub async fn run(config: &Config, args: SearchArgs) -> Result<()> {
- let ep = ServerEndpoint::from_config(config);
+ let ep = ServerEndpoint::from_config_resolving_auth(config).await;
let project = super::resolve_project_name(config, args.project.as_deref())?;
let limit_str = args.limit.to_string();
let hits: Vec<Hit> = get_json(
diff --git a/crates/ai-memory-cli/src/commands/status.rs b/crates/ai-memory-cli/src/commands/status.rs
index 6e00b69e..8a3e3e0b 100644
--- a/crates/ai-memory-cli/src/commands/status.rs
+++ b/crates/ai-memory-cli/src/commands/status.rs
@@ -69,7 +69,7 @@ struct EmbeddingTriple {
/// Returns an error if the server is unreachable, returns non-2xx, or
/// the response can't be parsed.
pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {
- let ep = ServerEndpoint::from_config(config);
+ let ep = ServerEndpoint::from_config_resolving_auth(config).await;
let report: Report = get_json(&ep, "/admin/status", &[]).await?;
if args.json {
diff --git a/crates/ai-memory-cli/src/commands/user.rs b/crates/ai-memory-cli/src/commands/user.rs
index 9200da03..9f15195b 100644
--- a/crates/ai-memory-cli/src/commands/user.rs
+++ b/crates/ai-memory-cli/src/commands/user.rs
@@ -68,7 +68,7 @@ struct UserList {
/// Returns an error if the HTTP call fails, the server returns non-2xx,
/// or the response body can't be deserialised.
pub async fn run(config: &Config, args: UserArgs) -> Result<()> {
- let ep = ServerEndpoint::from_config(config);
+ let ep = ServerEndpoint::from_config_resolving_auth(config).await;
match args.command {
UserCommand::Add(args) => add(&ep, args).await,
UserCommand::List(args) => list(&ep, args).await,
diff --git a/crates/ai-memory-cli/src/commands/write_page.rs b/crates/ai-memory-cli/src/commands/write_page.rs
index 473f9c07..c91e225c 100644
--- a/crates/ai-memory-cli/src/commands/write_page.rs
+++ b/crates/ai-memory-cli/src/commands/write_page.rs
@@ -55,7 +55,7 @@ pub async fn run(config: &Config, args: WritePageArgs) -> Result<()> {
// write + read-back pairs from silently targeting different projects.
let project = super::resolve_project_name(config, args.project.as_deref())?;
- let endpoint = ServerEndpoint::from_config(config);
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let resp: WritePageResponseBody = post_json(
&endpoint,
"/admin/write-page",
diff --git a/crates/ai-memory-cli/src/http_client.rs b/crates/ai-memory-cli/src/http_client.rs
index 4743acf3..bc110f86 100644
--- a/crates/ai-memory-cli/src/http_client.rs
+++ b/crates/ai-memory-cli/src/http_client.rs
@@ -7,8 +7,8 @@
//! ## Configuration
//!
//! [`crate::config::Config`] captures `AI_MEMORY_SERVER_URL` and
-//! `AI_MEMORY_AUTH_TOKEN` exactly once; this module only consumes the
-//! resolved values.
+//! `AI_MEMORY_AUTH_TOKEN` exactly once; this module consumes those values
+//! and can fall back to the stored OIDC device-flow token used by native hooks.
use std::io::{BufWriter, Write as _};
use std::path::Path;
@@ -36,9 +36,12 @@ pub struct ServerEndpoint {
}
impl ServerEndpoint {
- /// Build the endpoint from the already-loaded process config.
+ /// Build the endpoint from config, resolving bearer auth and base path.
///
- /// The base-path prefix the server is mounted under (so client routes
+ /// Bearer precedence matches hooks: static config/env token first, stored
+ /// OIDC device token second, no token last.
+ ///
+ /// The base-path prefix the server is mounted under, so client routes
/// resolve as `<origin><base><path>` instead of 404ing) is resolved
/// from, in order of precedence:
/// 1. the **path component of `AI_MEMORY_SERVER_URL`** (the remote-client
@@ -49,11 +52,17 @@ impl ServerEndpoint {
/// "one config-read path" invariant; the CLI runs in the same
/// container as `serve`, which already reads the same env var via
/// clap to nest its router).
- #[must_use]
- pub fn from_config(config: &Config) -> Self {
+ pub async fn from_config_resolving_auth(config: &Config) -> Self {
+ let client = reqwest::Client::new();
+ let token = crate::auth_bearer::resolve_bearer(
+ &client,
+ &config.oidc_device_token_path(),
+ config.auth.bearer_token.as_deref(),
+ )
+ .await;
Self::build(
Some(config.server_url.clone()),
- config.auth.bearer_token.clone(),
+ token,
config.server_url_configured(),
Some(config.base_path.clone()).filter(|s| !s.is_empty()),
)
@@ -564,4 +573,39 @@ mod tests {
.unwrap();
assert_eq!(auth, "Bearer tok123");
}
+
+ #[tokio::test]
+ async fn from_config_resolving_auth_uses_stored_oidc_for_authorization_header() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = Config {
+ data_dir: tmp.path().to_path_buf(),
+ ..Config::default()
+ };
+ config.auth.bearer_token = None;
+ ai_memory_llm::OidcToken {
+ access: secrecy::SecretString::from("oidc-access".to_string()),
+ refresh: secrecy::SecretString::from("refresh-token".to_string()),
+ expires_at_ms: u64::MAX,
+ issuer: "https://issuer.example.com/realms/team".to_string(),
+ client_id: "ai-memory-cli".to_string(),
+ token_endpoint: "https://issuer.example.com/token".to_string(),
+ }
+ .save(&config.oidc_device_token_path())
+ .expect("save test OIDC token");
+
+ let ep = ServerEndpoint::from_config_resolving_auth(&config).await;
+ let client = reqwest::Client::new();
+ let req = ep
+ .authenticate(client.get("http://localhost"))
+ .build()
+ .unwrap();
+ let auth = req
+ .headers()
+ .get("authorization")
+ .expect("Authorization header must be set")
+ .to_str()
+ .unwrap();
+
+ assert_eq!(auth, "Bearer oidc-access");
+ }
}
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index 34f519a6..941b9747 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -14,6 +14,7 @@ use clap::Parser;
use tracing::info;
mod auth;
+mod auth_bearer;
mod cli;
mod commands;
mod config;
diff --git a/crates/ai-memory-core/src/routing_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rs
index f76f464c..6dcd246e 100644
--- a/crates/ai-memory-core/src/routing_snippet.rs
+++ b/crates/ai-memory-core/src/routing_snippet.rs
@@ -40,6 +40,12 @@ did we decide in the `other-app` project?"). Phrases like "this project",
"here", "we", "our work", and "where did we leave off" all mean the
*current* project, so call tools with no scoping args.
+This default assumes the MCP client can identify the current agent
+session. Static MCP clients in parallel sessions for the same user cannot
+forward the real agent session id automatically; pass explicit
+`workspace` + `project` / `scopes`, or use a session-aware bridge that
+forwards the lifecycle-hook session id on MCP calls.
+
**Lifecycle hooks already capture every prompt and tool call
automatically.** Do not manually write routine notes. Only write durable
memory when the user explicitly asks to remember or annotate something
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index ee1a6818..7bc3e3bb 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -158,6 +158,12 @@ asks about a handoff and the SessionStart auto-fetched block is already \
in your context, answer from it; do NOT re-call the tool to look for it \
in another project.\n\
\n\
+This default assumes the MCP client can identify the current agent \
+session. Static MCP clients in parallel sessions for the same user \
+cannot forward the real agent session id automatically; pass explicit \
+`workspace` + `project` / `scopes`, or use a session-aware bridge that \
+forwards the lifecycle-hook session id on MCP calls.\n\
+\n\
Lifecycle hooks already capture every prompt + tool call automatically \
— you do NOT need to write routine notes by hand. When the user \
explicitly asks to remember a permanent annotation/fact/rule, write a \
@@ -2753,6 +2759,30 @@ mod tests {
);
}
+ #[test]
+ fn prompts_warn_static_mcp_parallel_sessions_need_explicit_scope() {
+ for prompt in [MEMORY_INSTRUCTIONS, ai_memory_core::SNIPPET_BODY] {
+ let lower = prompt.to_ascii_lowercase();
+ assert!(
+ lower.contains("static mcp") && lower.contains("parallel sessions"),
+ "prompt must warn about static MCP clients in parallel sessions"
+ );
+ assert!(
+ lower.contains("real agent session id")
+ && (lower.contains("session-aware bridge")
+ || lower.contains("session aware bridge")),
+ "prompt must distinguish real agent session id from static MCP config"
+ );
+ assert!(
+ lower.contains("explicit")
+ && lower.contains("workspace")
+ && lower.contains("project")
+ && lower.contains("scopes"),
+ "prompt must tell agents to use explicit scope when session id is unavailable"
+ );
+ }
+ }
+
#[test]
fn prompts_route_permanent_annotations_to_write_page_not_handoff() {
assert_detailed_prompt_surfaces(|label, prompt| {
diff --git a/docs/auto-scope.md b/docs/auto-scope.md
index 4b4c597e..a6642280 100644
--- a/docs/auto-scope.md
+++ b/docs/auto-scope.md
@@ -87,6 +87,11 @@ AI_MEMORY_AUTO_SCOPE__MAX_ENTRIES=8192
| MCP request header `Mcp-Session-Id` | fallback `session_id` for tool calls |
| Anonymous / no token | empty actor → single slot |
+`X-Memory-Actor-Session-Id` means the agent-run session id from the
+lifecycle-hook payload. It is not an OIDC/Keycloak login session: the
+provider's JWT `sid` claim identifies an IdP browser/device session and
+must not be used as ai-memory's actor session key.
+
`per_session` reads from `session_id`; `per_actor` reads from both
`user` and `session_id`. In `per_actor`, a request that has `user` but
no session id can use that user's latest no-session slot instead of the
@@ -110,6 +115,13 @@ requests that carry a different MCP session id fail closed to the baked
default, while requests with no usable actor identity still degrade to
the legacy single slot.
+OIDC/Keycloak authentication can identify the human user, client, and
+agent, but it does not automatically identify the current coding-agent
+session. If a gateway validates a Keycloak JWT, it should propagate
+`X-Memory-Actor-User` / `Sub` / `Client` / `Agent`; it should only emit
+`X-Memory-Actor-Session-Id` when a real agent session id has been
+forwarded by a session-aware bridge.
+
For built-in installs that use static MCP config, prefer:
- `single` for one operator / one active project at a time.
diff --git a/docs/install.md b/docs/install.md
index 16fc5388..94e7d17a 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -322,6 +322,17 @@ ai-memory auth login oidc-device \
--client-id "ai-memory-cli"
```
+The stored OIDC access token is also used by thin-client HTTP commands
+(`status`, `search`, `read-page`, `write-page`, `backup`, `embed`, and
+similar) when no static `AI_MEMORY_AUTH_TOKEN` / `[auth].bearer_token` is
+configured. Static bearer auth still has precedence.
+
+OIDC/Keycloak `sid` claims describe the login provider's session, not the
+coding-agent session ai-memory uses for `[auto_scope]` isolation. Gateways may
+propagate the authenticated user/client/agent headers, but
+`X-Memory-Actor-Session-Id` should only contain a real lifecycle-hook session id
+from a session-aware bridge.
+
Restart the service after changing provider settings:
```bash
@@ -942,7 +953,7 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree
| `generate-auth-token` | `docker run --rm` | Print a random hex bearer token |
| `auth login openai-oauth` | same data volume as the server | Store a ChatGPT/Codex OAuth refresh token for the optional `openai-oauth` LLM provider |
| `auth login copilot` | same data volume as the server | Store a GitHub token for the optional `copilot` LLM provider |
-| `auth login oidc-device` | same developer data dir as native hooks | Store a per-developer OIDC device token for native hook authentication |
+| `auth login oidc-device` | same developer data dir as native hooks and thin-client CLI commands | Store a per-developer OIDC device token for native hook authentication and HTTP CLI fallback auth |
| `install-mcp --client` | `docker run --rm` | MCP-config snippet per client |
| `install-hooks --agent` | `docker run --rm` | Hook-config snippet for an existing hooks dir |
| `setup-agent --agent --to --host-prefix` | `docker run --rm -v` | Extract bundled scripts + print config (one-shot) |
diff --git a/docs/users.md b/docs/users.md
index 70a55be4..4767444c 100644
--- a/docs/users.md
+++ b/docs/users.md
@@ -301,7 +301,10 @@ the bearer authenticates, attribution flows from the token's owner
- **Root token is single.** `[auth].bearer_token` is the admin token
for every `/admin/*` endpoint. DB users created with `user add` are
normal users, not additional admins.
-- **OIDC is hook authentication, not page authorization.** Native hooks can use
- a per-developer OIDC device token, but ai-memory still has one shared wiki per
- server and no per-page RBAC. If you need data isolation, run separate
- ai-memory servers or isolate at a reverse proxy.
+- **OIDC is request authentication, not page authorization.** Native hooks and
+ thin-client CLI commands can use a per-developer OIDC device token, but
+ ai-memory still has one shared wiki per server and no per-page RBAC. The
+ Keycloak/OIDC `sid` claim is also not an ai-memory agent session id; session
+ auto-scope needs the lifecycle-hook session id or explicit `workspace` +
+ `project` / `scopes`. If you need data isolation, run separate ai-memory
+ servers or isolate at a reverse proxy.