Skip to content

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

Rust

feat(hooks): per-developer OIDC auth + async spool-based capture

Djalma Júnior6b7759cab552
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index b82cec05..046fbc80 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -256,6 +256,10 @@ pub enum AuthProviderChoice {
OpenaiOauth,
/// GitHub Copilot Chat backend.
Copilot,
+ /// Generic OIDC device-authorization grant (e.g. Keycloak). Stores a
+ /// per-developer token the lifecycle hooks use to authenticate to the
+ /// ai-memory server, instead of a shared static `--auth-token`.
+ OidcDevice,
}
/// Arguments for `auth login`.
@@ -270,9 +274,15 @@ pub struct AuthLoginArgs {
/// GitHub token to persist for Copilot instead of running device auth.
#[arg(long, hide_env_values = true)]
pub github_token: Option<String>,
- /// OAuth client id override for Copilot device auth.
+ /// OAuth/OIDC public client id. Required for `oidc-device`; an optional
+ /// override for `copilot` device auth.
#[arg(long)]
pub client_id: Option<String>,
+ /// OIDC issuer URL for `oidc-device` login, e.g. a Keycloak realm
+ /// (`https://keycloak.example.com/realms/serpro`). Endpoints are
+ /// discovered from `<issuer>/.well-known/openid-configuration`.
+ #[arg(long)]
+ pub issuer: Option<String>,
}
/// Arguments for `auth logout`.
diff --git a/crates/ai-memory-cli/src/commands/auth.rs b/crates/ai-memory-cli/src/commands/auth.rs
index 0c726bbd..70d584ec 100644
--- a/crates/ai-memory-cli/src/commands/auth.rs
+++ b/crates/ai-memory-cli/src/commands/auth.rs
@@ -3,8 +3,10 @@
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use ai_memory_llm::{
- CODEX_CLIENT_ID, CopilotToken, GITHUB_ACCESS_TOKEN_URL, GITHUB_COPILOT_CLIENT_ID,
- GITHUB_DEVICE_CODE_URL, OPENAI_OAUTH_TOKEN_URL, OpenAiOAuthToken, OpenAiOAuthTokenResponse,
+ CODEX_CLIENT_ID, CopilotToken, DeviceAuthorizationResponse, GITHUB_ACCESS_TOKEN_URL,
+ GITHUB_COPILOT_CLIENT_ID, GITHUB_DEVICE_CODE_URL, OIDC_DEFAULT_SCOPE, OPENAI_OAUTH_TOKEN_URL,
+ OidcDiscovery, OidcToken, OidcTokenResponse, OpenAiOAuthToken, OpenAiOAuthTokenResponse,
+ PollOutcome, discover, poll_token_once, request_device_code,
};
use anyhow::{Context, Result, anyhow, bail};
use secrecy::ExposeSecret as _;
@@ -28,23 +30,126 @@ pub async fn run(config: &Config, args: AuthArgs) -> Result<()> {
match args.command {
AuthCommand::Login(args) => match args.provider {
AuthProviderChoice::OpenaiOauth => {
- if args.github_token.is_some() || args.client_id.is_some() {
- bail!("--github-token and --client-id apply only to `auth login copilot`");
+ if args.github_token.is_some() || args.client_id.is_some() || args.issuer.is_some()
+ {
+ bail!(
+ "--github-token / --client-id / --issuer do not apply to `auth login openai-oauth`"
+ );
}
login_openai_oauth(config, args.timeout_secs).await
}
AuthProviderChoice::Copilot => {
+ if args.issuer.is_some() {
+ bail!("--issuer applies only to `auth login oidc-device`");
+ }
login_copilot(config, args.timeout_secs, args.github_token, args.client_id).await
}
+ AuthProviderChoice::OidcDevice => {
+ if args.github_token.is_some() {
+ bail!("--github-token applies only to `auth login copilot`");
+ }
+ let issuer = args
+ .issuer
+ .context("--issuer is required for `auth login oidc-device`")?;
+ let client_id = args
+ .client_id
+ .context("--client-id is required for `auth login oidc-device`")?;
+ login_oidc_device(config, &issuer, &client_id, args.timeout_secs).await
+ }
},
AuthCommand::Logout(args) => match args.provider {
AuthProviderChoice::OpenaiOauth => logout_openai_oauth(config),
AuthProviderChoice::Copilot => logout_copilot(config),
+ AuthProviderChoice::OidcDevice => logout_oidc_device(config),
},
AuthCommand::Status(_) => status(config),
}
}
+async fn login_oidc_device(
+ config: &Config,
+ issuer: &str,
+ client_id: &str,
+ timeout_secs: u64,
+) -> Result<()> {
+ let client = auth_http_client()?;
+ let discovery = discover(&client, issuer).await?;
+ let device = request_device_code(&client, &discovery, client_id, OIDC_DEFAULT_SCOPE).await?;
+
+ match device.verification_uri_complete.as_deref() {
+ Some(complete) => println!("Open this URL: {complete}"),
+ None => {
+ println!("Open this URL: {}", device.verification_uri);
+ println!("Enter code: {}", device.user_code);
+ }
+ }
+ println!("Waiting for authorization...");
+
+ let token_response = poll_oidc_device(
+ &client,
+ &discovery,
+ client_id,
+ &device,
+ Duration::from_secs(timeout_secs),
+ )
+ .await?;
+ let token = OidcToken::from_token_response(
+ &token_response,
+ issuer,
+ client_id,
+ &discovery.token_endpoint,
+ None,
+ )?;
+ let path = config.oidc_device_token_path();
+ token.save(&path).map_err(anyhow::Error::from)?;
+
+ println!("oidc-device: logged in");
+ println!("issuer: {issuer}");
+ println!("token file: {}", path.display());
+ Ok(())
+}
+
+async fn poll_oidc_device(
+ client: &reqwest::Client,
+ discovery: &OidcDiscovery,
+ client_id: &str,
+ device: &DeviceAuthorizationResponse,
+ timeout: Duration,
+) -> Result<OidcTokenResponse> {
+ let started = Instant::now();
+ let mut interval = Duration::from_secs(
+ device
+ .interval
+ .unwrap_or(5)
+ .max(1)
+ .saturating_add(POLLING_SAFETY_MARGIN_SECS),
+ );
+ let device_timeout = Duration::from_secs(device.expires_in.unwrap_or(600).max(1));
+ let timeout = timeout.min(device_timeout);
+ loop {
+ if started.elapsed() >= timeout {
+ bail!("timed out waiting for oidc-device authorization");
+ }
+ match poll_token_once(client, discovery, client_id, &device.device_code).await? {
+ PollOutcome::Token(token) => return Ok(*token),
+ PollOutcome::Pending => {}
+ PollOutcome::SlowDown => interval = interval.saturating_add(Duration::from_secs(5)),
+ PollOutcome::Denied => bail!("oidc-device authorization denied"),
+ PollOutcome::Expired => bail!("oidc-device code expired before authorization"),
+ PollOutcome::Other(error) => bail!("oidc-device authorization failed: {error}"),
+ }
+ sleep(interval).await;
+ }
+}
+
+fn logout_oidc_device(config: &Config) -> Result<()> {
+ let path = config.oidc_device_token_path();
+ OidcToken::remove(&path).map_err(anyhow::Error::from)?;
+ println!("oidc-device: logged out");
+ println!("token file: {}", path.display());
+ Ok(())
+}
+
async fn login_openai_oauth(config: &Config, timeout_secs: u64) -> Result<()> {
let client = auth_http_client()?;
let device = start_device_authorization(&client).await?;
@@ -173,6 +278,20 @@ fn status(config: &Config) -> Result<()> {
println!("token file: {}", copilot_path.display());
}
}
+
+ let oidc_path = config.oidc_device_token_path();
+ match OidcToken::load(&oidc_path).map_err(anyhow::Error::from)? {
+ Some(token) => {
+ println!("oidc-device: logged in");
+ println!("issuer: {}", token.issuer);
+ println!("expires in: {}", format_duration_until(token.expires_at_ms));
+ println!("token file: {}", oidc_path.display());
+ }
+ None => {
+ println!("oidc-device: not logged in");
+ println!("token file: {}", oidc_path.display());
+ }
+ }
Ok(())
}
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index 15a3ffe1..2fae41e8 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -1,18 +1,45 @@
//! `ai-memory hook` — emit a single lifecycle event natively.
//!
-//! Reads the event payload from stdin and issues the same HTTP request
-//! the shell hook scripts do, without spawning a shell or child
-//! processes. See `docs/windows.md#native-hook-command-claude-code-on-windows`.
+//! Reads the event payload from stdin. Instead of POSTing synchronously on the
+//! agent's hot path (which would block every tool call on the network and drop
+//! events against a slow/remote server), the event is **spooled** locally — an
+//! instant write — and the spool is drained to the server at session
+//! boundaries (a cleanup pass on `session-start`, the main flush on
+//! `session-end`). The one synchronous request is the `session-start` handoff
+//! GET, whose result is injected back into the agent as context.
+//!
+//! See `docs/windows.md#native-hook-command-claude-code-on-windows`.
use std::io::Read;
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+use ai_memory_llm::OidcToken;
use crate::cli::HookArgs;
-use super::hook_capture::{build_client, extract_cwd, get_handoff, marker_query_suffix, post_hook};
+use super::hook_capture::{build_client, extract_cwd, get_handoff, marker_query_suffix};
+use super::hook_spool;
-/// Run a single hook end-to-end. Always returns Ok and always writes a
-/// JSON object to stdout — a hook must never fail the agent.
-pub async fn run(args: HookArgs) -> anyhow::Result<()> {
+/// Per-event POST budget during a drain (off the hot path — generous enough for
+/// a remote/slow server).
+const DRAIN_EVENT_TIMEOUT: Duration = Duration::from_secs(3);
+/// Total budget for the `session-start` cleanup drain (kept tight so session
+/// start stays snappy even when the server is down — leftovers wait).
+const START_DRAIN_BUDGET: Duration = Duration::from_secs(3);
+/// Total budget for the `session-end` flush (the main delivery point; a session
+/// boundary tolerates more, and the agent isn't mid-tool-call).
+const END_DRAIN_BUDGET: Duration = Duration::from_secs(10);
+/// Budget for the synchronous handoff fetch (larger than a loopback default so
+/// a remote server can answer).
+const HANDOFF_TIMEOUT: Duration = Duration::from_secs(3);
+
+/// Run a single hook end-to-end. Always returns Ok and always writes a JSON
+/// object to stdout — a hook must never fail the agent.
+///
+/// `data_dir` is the resolved global `--data-dir` (if any); used to locate the
+/// spool and the stored OIDC token.
+pub async fn run(data_dir: Option<PathBuf>, args: HookArgs) -> anyhow::Result<()> {
let mut payload = String::new();
std::io::stdin().read_to_string(&mut payload).ok();
let json: serde_json::Value = serde_json::from_str(&payload).unwrap_or(serde_json::Value::Null);
@@ -21,18 +48,37 @@ pub async fn run(args: HookArgs) -> anyhow::Result<()> {
.map(|cwd| marker_query_suffix(&cwd))
.unwrap_or_default();
let base = args.server_url.trim_end_matches('/');
- let token = args.auth_token.as_deref();
- let client = build_client();
+ let dd = resolve_data_dir(data_dir.as_deref());
+ let spool = hook_spool::spool_dir(&dd);
- // Every event records itself via POST /hook (best-effort).
- let post_url = format!("{base}/hook?event={}&agent={}{qs}", args.event, args.agent);
- let _ = post_hook(&client, &post_url, &payload, token).await;
+ // Spool THIS event — an instant local write, never the network. The auth
+ // mode is decided without a round-trip: an explicit `--auth-token` is
+ // stored inline; otherwise a present OIDC token marks the event `oidc`
+ // (resolved + refreshed at drain time); otherwise anonymous.
+ let oidc_present = args.auth_token.is_none()
+ && OidcToken::load(&dd.join("auth.json"))
+ .ok()
+ .flatten()
+ .is_some();
+ let event_url = format!("{base}/hook?event={}&agent={}{qs}", args.event, args.agent);
+ let entry = hook_spool::entry_for(
+ event_url,
+ payload.clone(),
+ args.auth_token.as_deref(),
+ oidc_present,
+ );
+ let _ = hook_spool::enqueue(&spool, &entry);
- // session-start ALSO pulls the pending handoff and injects it as
- // context for the resuming agent.
+ // session-start: drain any backlog (e.g. from a previous session that ended
+ // abruptly), then fetch + inject the pending handoff for the resuming agent.
if args.event == "session-start" {
+ let _ = hook_spool::drain(&spool, &dd, START_DRAIN_BUDGET, DRAIN_EVENT_TIMEOUT).await;
+ let client = build_client();
+ let bearer = hook_spool::resolve_bearer(&client, &dd, args.auth_token.as_deref()).await;
let handoff_url = format!("{base}/handoff?agent={}{qs}", args.agent);
- if let Some(handoff) = get_handoff(&client, &handoff_url, token).await {
+ if let Some(handoff) =
+ get_handoff(&client, &handoff_url, bearer.as_deref(), HANDOFF_TIMEOUT).await
+ {
let envelope = serde_json::json!({
"hookSpecificOutput": {
"hookEventName": "SessionStart",
@@ -44,6 +90,26 @@ pub async fn run(args: HookArgs) -> anyhow::Result<()> {
}
}
+ // session-end: the main delivery point — flush the session's spooled
+ // observations (oldest-first) so the server has them before it consolidates.
+ if args.event == "session-end" {
+ let _ = hook_spool::drain(&spool, &dd, END_DRAIN_BUDGET, DRAIN_EVENT_TIMEOUT).await;
+ }
+
println!("{{}}");
Ok(())
}
+
+/// Resolve the data dir cheaply, without loading the full config (the hook
+/// fast-path skips config for latency). Mirrors `config.rs`: explicit
+/// `--data-dir`, else `AI_MEMORY_DATA_DIR`, else the platform local-data dir.
+fn resolve_data_dir(data_dir: Option<&Path>) -> PathBuf {
+ data_dir
+ .map(Path::to_path_buf)
+ .or_else(|| std::env::var_os("AI_MEMORY_DATA_DIR").map(PathBuf::from))
+ .unwrap_or_else(|| {
+ dirs::data_local_dir()
+ .unwrap_or_else(|| PathBuf::from("."))
+ .join("ai-memory")
+ })
+}
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rs
index d8ac4e8f..bb2eff86 100644
--- a/crates/ai-memory-cli/src/commands/hook_capture.rs
+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs
@@ -110,35 +110,44 @@ pub fn build_client() -> reqwest::Client {
.unwrap_or_else(|_| reqwest::Client::new())
}
-/// POST the payload as JSON, best-effort. 0.5s budget (parity with the
-/// shell `--max-time 0.5`). Network errors are swallowed — a hook must
-/// never block or fail the agent.
+/// POST the payload as JSON, best-effort. Returns `true` when the server
+/// acknowledged with a 2xx (the engine answers `202 queued`), `false` on any
+/// non-2xx or transport error — never errors, so a hook/flush never fails the
+/// agent. `timeout` is caller-chosen: the per-tool-call hot path no longer
+/// POSTs at all (it spools); only the session-boundary drain calls this, with a
+/// generous budget that tolerates a remote/slow server.
pub async fn post_hook(
client: &reqwest::Client,
url: &str,
body: &str,
token: Option<&str>,
-) -> anyhow::Result<()> {
+ timeout: Duration,
+) -> bool {
let mut req = client
.post(url)
.header("Content-Type", "application/json")
- .timeout(Duration::from_millis(500))
+ .timeout(timeout)
.body(body.to_owned());
if let Some(t) = token {
req = req.bearer_auth(t);
}
- let _ = req.send().await; // best-effort: ignore the result
- Ok(())
+ match req.send().await {
+ Ok(resp) => resp.status().is_success(),
+ Err(_) => false,
+ }
}
-/// GET the handoff text, 1s budget (parity with the shell handoff GET).
-/// Returns None on any error or an empty body.
+/// GET the handoff text with a caller-chosen budget. Returns None on any error
+/// or an empty body. This is the one synchronous read on the agent's critical
+/// path (session-start injects it as context), so the budget is larger than a
+/// loopback default to tolerate a remote server.
pub async fn get_handoff(
client: &reqwest::Client,
url: &str,
token: Option<&str>,
+ timeout: Duration,
) -> Option<String> {
- let mut req = client.get(url).timeout(Duration::from_millis(1000));
+ let mut req = client.get(url).timeout(timeout);
if let Some(t) = token {
req = req.bearer_auth(t);
}
@@ -175,17 +184,19 @@ mod tests {
}
#[tokio::test]
- async fn post_hook_returns_ok_even_when_server_unreachable() {
- // Port 1 is unroutable; best-effort means this still resolves Ok.
+ async fn post_hook_returns_false_when_server_unreachable() {
+ // Port 1 is unroutable; best-effort means this resolves to `false`
+ // (no 2xx) rather than panicking or erroring.
let client = build_client();
- let r = post_hook(
+ let ok = post_hook(
&client,
"http://127.0.0.1:1/hook?event=pre-tool-use",
"{}",
None,
+ Duration::from_millis(500),
)
.await;
- assert!(r.is_ok());
+ assert!(!ok);
}
/// Happy-path TOML parser: extracts each declared root-level
diff --git a/crates/ai-memory-cli/src/commands/hook_spool.rs b/crates/ai-memory-cli/src/commands/hook_spool.rs
new file mode 100644
index 00000000..64311f03
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/hook_spool.rs
@@ -0,0 +1,430 @@
+//! Local spool for lifecycle-hook events — decouples capture from the network.
+//!
+//! Per-tool-call hooks (`pre-tool-use`, `post-tool-use`, `user-prompt-submit`,
+//! `stop`) append an event here (an instant local write) instead of POSTing
+//! synchronously. The spool is drained to the server at **session boundaries**
+//! (a cleanup pass at `session-start`, the main flush at `session-end`), where a
+//! few seconds of latency is acceptable — unlike the per-tool-call hot path,
+//! which must never block the agent.
+//!
+//! This makes capture reliable against a remote/slow server (no event is lost:
+//! a file persists until the server answers 2xx) without ever blocking a tool
+//! call. It also fits ai-memory's model: consolidation runs on `session-end`,
+//! after the drain has delivered the session's observations in order.
+//!
+//! Each event carries its own auth so a single global spool can hold events
+//! for several instances: a static token is stored inline (file mode 0600);
+//! an OIDC event stores only the mode and is resolved + refreshed from
+//! `auth.json` at drain time (so a token that expired while the event waited is
+//! renewed rather than rejected).
+
+use std::path::{Path, PathBuf};
+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::{build_client, post_hook};
+
+/// Drop a spooled event after this many failed drain passes — bounds retries of
+/// a permanently-undeliverable event (e.g. a server URL that never comes back).
+const MAX_ATTEMPTS: u32 = 8;
+/// Drop a spooled event older than this regardless of attempts (7 days), so a
+/// long-dead instance can't leave the spool growing without bound.
+const MAX_AGE_MS: u64 = 7 * 24 * 60 * 60 * 1000;
+
+/// How a spooled event authenticates to the server when drained.
+#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
+pub enum AuthMode {
+ /// A static bearer stored inline (`token`) — service-account / edge token.
+ #[serde(rename = "static")]
+ Static,
+ /// Resolve + refresh a stored OIDC device-grant token from `auth.json`.
+ #[serde(rename = "oidc")]
+ Oidc,
+ /// No bearer (loopback / no-auth server).
+ #[serde(rename = "none")]
+ Anonymous,
+}
+
+/// One spooled hook event: the full request plus how to authenticate it.
+#[derive(Serialize, Deserialize, Debug)]
+pub struct SpoolEntry {
+ /// Full hook URL including the `?event=…&agent=…[&cwd&workspace&project]`
+ /// query the agent's payload resolved to.
+ pub url: String,
+ /// The raw JSON event payload to POST.
+ pub body: String,
+ /// Enqueue time (Unix ms) — for ordering + future TTL pruning.
+ pub created_ms: u64,
+ /// How to authenticate this event at drain time.
+ pub auth_mode: AuthMode,
+ /// Static bearer, present only when `auth_mode == Static`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub token: Option<String>,
+ /// Failed delivery attempts so far — incremented on each drain miss and used
+ /// (with `created_ms`) to drop a permanently-undeliverable event.
+ #[serde(default)]
+ pub attempts: u32,
+}
+
+/// `<data_dir>/hook-spool` — the spool directory.
+#[must_use]
+pub fn spool_dir(data_dir: &Path) -> PathBuf {
+ data_dir.join("hook-spool")
+}
+
+fn now_ms() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis()
+ .try_into()
+ .unwrap_or(u64::MAX)
+}
+
+/// Append an event to the spool, atomically (temp file + rename) and 0600 on
+/// Unix. Never touches the network. Each hook invocation enqueues exactly one
+/// event, so the `<ms>-<pid>` name is unique.
+///
+/// # Errors
+/// Returns an error only when the spool file cannot be written.
+pub fn enqueue(spool: &Path, entry: &SpoolEntry) -> std::io::Result<()> {
+ std::fs::create_dir_all(spool)?;
+ let name = format!("{:013}-{}.json", entry.created_ms, std::process::id());
+ let tmp = spool.join(format!("{name}.tmp"));
+ let final_path = spool.join(&name);
+ let bytes = serde_json::to_vec(entry)?;
+ write_private(&tmp, &bytes)?;
+ std::fs::rename(&tmp, &final_path)
+}
+
+fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
+ use std::io::Write as _;
+ let mut opts = std::fs::OpenOptions::new();
+ opts.create(true).truncate(true).write(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt as _;
+ opts.mode(0o600);
+ }
+ let mut file = opts.open(path)?;
+ file.write_all(bytes)?;
+ file.sync_all()
+}
+
+/// Build a [`SpoolEntry`] for the current event, choosing the auth mode from
+/// the hook's flags + stored credentials (no network, no token I/O):
+/// an explicit `--auth-token` → `Static`; else a present OIDC `auth.json`
+/// entry → `Oidc`; else `Anonymous`.
+#[must_use]
+pub fn entry_for(
+ url: String,
+ body: String,
+ auth_token: Option<&str>,
+ oidc_present: bool,
+) -> SpoolEntry {
+ let (auth_mode, token) = match auth_token {
+ Some(t) => (AuthMode::Static, Some(t.to_string())),
+ None if oidc_present => (AuthMode::Oidc, None),
+ None => (AuthMode::Anonymous, None),
+ };
+ SpoolEntry {
+ url,
+ body,
+ created_ms: now_ms(),
+ auth_mode,
+ token,
+ attempts: 0,
+ }
+}
+
+/// Outcome of a drain pass.
+#[derive(Debug, Default, PartialEq, Eq)]
+pub struct DrainResult {
+ /// Events delivered (server answered 2xx) and removed from the spool.
+ pub sent: usize,
+ /// Events still queued (failed this pass, or skipped when the budget ran out).
+ pub remaining: usize,
+ /// Events discarded as undeliverable (too old or too many failed attempts).
+ pub dropped: usize,
+}
+
+/// Drain the spool to the server, oldest-first, within `total_budget`. Each
+/// event that gets a 2xx is deleted; failures stay for the next boundary.
+/// OIDC bearer is resolved + refreshed at most once per drain and cached.
+///
+/// Best-effort: returns counts and never errors, so a session boundary is never
+/// blocked beyond the budget and never fails the agent.
+pub async fn drain(
+ spool: &Path,
+ data_dir: &Path,
+ total_budget: Duration,
+ per_event_timeout: Duration,
+) -> DrainResult {
+ let mut files = match list_entries(spool) {
+ Some(f) => f,
+ None => return DrainResult::default(),
+ };
+ files.sort();
+
+ let client = build_client();
+ let started = Instant::now();
+ let mut oidc_cache: Option<Option<String>> = None; // outer None = not yet resolved
+ let mut result = DrainResult::default();
+
+ for path in files {
+ if started.elapsed() >= total_budget {
+ result.remaining += 1;
+ continue;
+ }
+ let Ok(bytes) = std::fs::read(&path) else {
+ result.remaining += 1;
+ continue;
+ };
+ let Ok(mut entry) = serde_json::from_slice::<SpoolEntry>(&bytes) else {
+ // Unparseable spool file: drop it so it can't wedge the queue.
+ let _ = std::fs::remove_file(&path);
+ result.dropped += 1;
+ continue;
+ };
+
+ // Prune events too old to be worth retrying (a long-dead instance).
+ if now_ms().saturating_sub(entry.created_ms) > MAX_AGE_MS {
+ let _ = std::fs::remove_file(&path);
+ result.dropped += 1;
+ continue;
+ }
+
+ let bearer: Option<String> = match entry.auth_mode {
+ AuthMode::Static => entry.token.clone(),
+ AuthMode::Anonymous => None,
+ AuthMode::Oidc => {
+ if oidc_cache.is_none() {
+ oidc_cache = Some(resolve_oidc(&client, data_dir).await);
+ }
+ oidc_cache.clone().flatten()
+ }
+ };
+
+ if post_hook(
+ &client,
+ &entry.url,
+ &entry.body,
+ bearer.as_deref(),
+ per_event_timeout,
+ )
+ .await
+ {
+ let _ = std::fs::remove_file(&path);
+ result.sent += 1;
+ } else {
+ entry.attempts += 1;
+ if entry.attempts >= MAX_ATTEMPTS {
+ let _ = std::fs::remove_file(&path);
+ result.dropped += 1;
+ } else {
+ // Persist the bumped attempt count for the next boundary.
+ let _ = rewrite_entry(&path, &entry);
+ result.remaining += 1;
+ }
+ }
+ }
+ result
+}
+
+/// Overwrite a spool file in place with the updated entry (atomic temp+rename),
+/// used to persist a bumped attempt count after a failed delivery.
+fn rewrite_entry(path: &Path, entry: &SpoolEntry) -> std::io::Result<()> {
+ let mut tmp = path.as_os_str().to_owned();
+ tmp.push(".tmp");
+ let tmp = PathBuf::from(tmp);
+ let bytes = serde_json::to_vec(entry)?;
+ write_private(&tmp, &bytes)?;
+ std::fs::rename(&tmp, path)
+}
+
+/// Resolve the bearer for a synchronous request (the session-start handoff
+/// GET): a static `--auth-token` wins, else the stored OIDC token
+/// (refreshed if stale), else none.
+pub async fn resolve_bearer(
+ client: &reqwest::Client,
+ 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
+ {
+ let _ = refreshed.save(&auth_path);
+ token = refreshed;
+ }
+ Some(token.access.expose_secret().to_string())
+}
+
+/// List `*.json` spool files (ignoring in-flight `*.json.tmp`), or None when the
+/// directory doesn't exist yet.
+fn list_entries(spool: &Path) -> Option<Vec<PathBuf>> {
+ let read = std::fs::read_dir(spool).ok()?;
+ let mut out = Vec::new();
+ for ent in read.flatten() {
+ let path = ent.path();
+ if path.extension().and_then(|e| e.to_str()) == Some("json") {
+ out.push(path);
+ }
+ }
+ Some(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn entry_for_picks_auth_mode() {
+ let s = entry_for("u".into(), "{}".into(), Some("tok"), false);
+ assert_eq!(s.auth_mode, AuthMode::Static);
+ assert_eq!(s.token.as_deref(), Some("tok"));
+
+ let o = entry_for("u".into(), "{}".into(), None, true);
+ assert_eq!(o.auth_mode, AuthMode::Oidc);
+ assert!(o.token.is_none());
+
+ let a = entry_for("u".into(), "{}".into(), None, false);
+ assert_eq!(a.auth_mode, AuthMode::Anonymous);
+ }
+
+ #[test]
+ fn enqueue_then_list_round_trips() {
+ let tmp = tempfile::tempdir().unwrap();
+ let spool = spool_dir(tmp.path());
+ let entry = entry_for(
+ "https://x/hook?event=stop".into(),
+ "{\"session_id\":\"s\"}".into(),
+ Some("tok"),
+ false,
+ );
+ enqueue(&spool, &entry).unwrap();
+ let files = list_entries(&spool).unwrap();
+ assert_eq!(files.len(), 1);
+ let loaded: SpoolEntry =
+ serde_json::from_slice(&std::fs::read(&files[0]).unwrap()).unwrap();
+ assert_eq!(loaded.url, "https://x/hook?event=stop");
+ assert_eq!(loaded.auth_mode, AuthMode::Static);
+ assert_eq!(loaded.token.as_deref(), Some("tok"));
+ }
+
+ #[tokio::test]
+ async fn drain_unreachable_leaves_events_queued() {
+ let tmp = tempfile::tempdir().unwrap();
+ let spool = spool_dir(tmp.path());
+ // Two anonymous events pointing at an unroutable port.
+ for i in 0..2 {
+ let e = entry_for(
+ format!("http://127.0.0.1:1/hook?event=e{i}"),
+ "{}".into(),
+ None,
+ false,
+ );
+ // Distinct filenames: enqueue uses ms+pid, so space them out.
+ enqueue(&spool, &e).unwrap();
+ std::fs::rename(
+ spool.join(format!("{:013}-{}.json", e.created_ms, std::process::id())),
+ spool.join(format!("evt-{i}.json")),
+ )
+ .unwrap();
+ }
+ let r = drain(
+ &spool,
+ tmp.path(),
+ Duration::from_secs(2),
+ Duration::from_millis(200),
+ )
+ .await;
+ assert_eq!(r.sent, 0);
+ assert_eq!(r.remaining, 2);
+ // Files survive for the next boundary.
+ assert_eq!(list_entries(&spool).unwrap().len(), 2);
+ }
+
+ #[tokio::test]
+ async fn drain_empty_spool_is_noop() {
+ let tmp = tempfile::tempdir().unwrap();
+ let r = drain(
+ &spool_dir(tmp.path()),
+ tmp.path(),
+ Duration::from_secs(1),
+ Duration::from_millis(200),
+ )
+ .await;
+ assert_eq!(r, DrainResult::default());
+ }
+
+ #[tokio::test]
+ async fn drain_drops_event_after_max_attempts() {
+ let tmp = tempfile::tempdir().unwrap();
+ let spool = spool_dir(tmp.path());
+ let e = entry_for(
+ "http://127.0.0.1:1/hook?event=dead".into(),
+ "{}".into(),
+ None,
+ false,
+ );
+ enqueue(&spool, &e).unwrap();
+ let mut dropped = 0;
+ for _ in 0..MAX_ATTEMPTS {
+ dropped += drain(
+ &spool,
+ tmp.path(),
+ Duration::from_secs(2),
+ Duration::from_millis(100),
+ )
+ .await
+ .dropped;
+ }
+ assert_eq!(
+ dropped, 1,
+ "the dead event is dropped once it hits MAX_ATTEMPTS"
+ );
+ assert!(
+ list_entries(&spool).unwrap().is_empty(),
+ "spool is empty after the drop"
+ );
+ }
+
+ #[tokio::test]
+ async fn drain_drops_stale_event() {
+ let tmp = tempfile::tempdir().unwrap();
+ let spool = spool_dir(tmp.path());
+ std::fs::create_dir_all(&spool).unwrap();
+ let mut e = entry_for(
+ "http://127.0.0.1:1/hook?event=old".into(),
+ "{}".into(),
+ None,
+ false,
+ );
+ e.created_ms = now_ms().saturating_sub(MAX_AGE_MS + 1);
+ std::fs::write(spool.join("stale.json"), serde_json::to_vec(&e).unwrap()).unwrap();
+ let r = drain(
+ &spool,
+ tmp.path(),
+ Duration::from_secs(2),
+ Duration::from_millis(100),
+ )
+ .await;
+ assert_eq!(r.dropped, 1);
+ assert_eq!(r.sent, 0);
+ assert!(list_entries(&spool).unwrap().is_empty());
+ }
+}
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index 6161d807..48edac85 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -17,6 +17,7 @@ pub mod forget_sweep;
pub mod generate_auth_token;
pub mod hook;
pub mod hook_capture;
+pub mod hook_spool;
pub mod init;
pub mod install_hooks;
pub mod install_instructions;
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 2793f18c..8e624ebc 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -340,6 +340,13 @@ pub(crate) enum HookCommandPlatform {
/// Claude Code on Windows; see
/// `docs/windows.md#native-hook-command-claude-code-on-windows`.
WindowsNative,
+ /// POSIX (Linux/macOS), native: invoke the `ai-memory` binary directly
+ /// (`<exe> hook --event …`) instead of the `.sh` script, so the hook gets
+ /// the local spool + OIDC-token fallback. **Opt-in** via
+ /// `AI_MEMORY_HOOK_PLATFORM=posix-native` — never the default, because the
+ /// Docker wrapper renders for the host with no local binary (it keeps the
+ /// `.sh` path). Use it when ai-memory is installed as a native binary.
+ PosixNative,
}
impl HookCommandPlatform {
@@ -351,6 +358,7 @@ impl HookCommandPlatform {
}
Ok(v) if v.eq_ignore_ascii_case("windows-bash") => Self::WindowsBash,
Ok(v) if v.eq_ignore_ascii_case("windows-native") => Self::WindowsNative,
+ Ok(v) if v.eq_ignore_ascii_case("posix-native") => Self::PosixNative,
_ if cfg!(windows) => Self::Windows,
_ => Self::Posix,
}
@@ -367,6 +375,7 @@ impl HookCommandPlatform {
}
Ok(v) if v.eq_ignore_ascii_case("windows-bash") => Self::WindowsBash,
Ok(v) if v.eq_ignore_ascii_case("windows-native") => Self::WindowsNative,
+ Ok(v) if v.eq_ignore_ascii_case("posix-native") => Self::PosixNative,
_ if cfg!(windows) => Self::WindowsNative,
_ => Self::Posix,
}
@@ -436,6 +445,7 @@ fn build_hook_payload_for_platform(
fn script_for_platform(script: &str, platform: HookCommandPlatform) -> Cow<'_, str> {
match platform {
HookCommandPlatform::Posix
+ | HookCommandPlatform::PosixNative
| HookCommandPlatform::WindowsBash
| HookCommandPlatform::WindowsNative => Cow::Borrowed(script),
HookCommandPlatform::Windows => match script.strip_suffix(".sh") {
@@ -518,6 +528,28 @@ fn hook_command(
}
cmd
}
+ HookCommandPlatform::PosixNative => {
+ // Native POSIX (opt-in): invoke the binary directly so the hook
+ // gets the local spool + OIDC fallback, instead of the `.sh` script
+ // that POSTs via curl. Mirrors `WindowsNative` but with POSIX
+ // single-quote quoting. The event name is the script stem.
+ let exe = std::env::current_exe()
+ .map(|p| p.to_string_lossy().into_owned())
+ .unwrap_or_else(|_| "ai-memory".to_string());
+ let event = script
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .unwrap_or_default();
+ let mut cmd = format!(
+ "{} hook --event {event} --agent claude-code --server-url {}",
+ shell_quote(&exe),
+ shell_quote(server_url),
+ );
+ if let Some(t) = auth_token {
+ cmd.push_str(&format!(" --auth-token {}", shell_quote(t)));
+ }
+ cmd
+ }
}
}
@@ -1069,6 +1101,43 @@ mod tests {
assert_eq!(s, "session-start.sh");
}
+ #[test]
+ fn posix_native_hook_command_invokes_binary_directly() {
+ let cmd = hook_command(
+ &PathBuf::from("/home/alice/.local/share/ai-memory/hooks/claude-code/session-start.sh"),
+ "https://my-server.example.com",
+ Some("tok123"),
+ HookCommandPlatform::PosixNative,
+ );
+ assert!(
+ cmd.contains("hook --event session-start"),
+ "invokes the binary subcommand with the event stem: {cmd}"
+ );
+ assert!(cmd.contains("--agent claude-code"), "{cmd}");
+ assert!(cmd.contains("https://my-server.example.com"), "{cmd}");
+ assert!(
+ cmd.contains("--auth-token") && cmd.contains("tok123"),
+ "{cmd}"
+ );
+ assert!(
+ !cmd.contains("session-start.sh"),
+ "must NOT reference the .sh script: {cmd}"
+ );
+ assert!(!cmd.starts_with("bash -c"), "no shell wrapper: {cmd}");
+ }
+
+ #[test]
+ fn posix_native_hook_command_omits_token_when_absent() {
+ let cmd = hook_command(
+ &PathBuf::from("/home/alice/hooks/pre-tool-use.sh"),
+ "http://localhost:49374",
+ None,
+ HookCommandPlatform::PosixNative,
+ );
+ assert!(cmd.contains("hook --event pre-tool-use"), "{cmd}");
+ assert!(!cmd.contains("--auth-token"), "no token expected: {cmd}");
+ }
+
#[test]
fn windows_bash_payload_uses_bash_c_and_sh_hooks() {
let root = PathBuf::from(r"C:\Users\alice\.local\share\ai-memory\hooks\claude-code");
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index c9d48eec..991ef9b3 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -611,6 +611,12 @@ impl Config {
self.auth_token_path()
}
+ /// Shared OIDC device-grant token file path.
+ #[must_use]
+ pub fn oidc_device_token_path(&self) -> PathBuf {
+ self.auth_token_path()
+ }
+
/// GitHub token resolved for Copilot auth login/provider use.
#[must_use]
pub fn copilot_github_token(&self) -> Option<SecretString> {
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index 83543266..a3a8b6bc 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -31,12 +31,15 @@ async fn main() -> Result<()> {
// Hooks fire on every tool call: they must be cheap and must emit ONLY
// their JSON object to stdout. Short-circuit before config load and
// tracing init (added latency + possible stdout noise). The hook reads
- // its server URL + token from flags, so it needs no config.
+ // its server URL + token from flags; it only needs the data-dir to locate
+ // a stored OIDC token when no explicit `--auth-token` is given, so we pass
+ // the bare path rather than loading the full config.
if matches!(cli.command, Command::Hook(_)) {
+ let data_dir = cli.data_dir.clone();
let Command::Hook(args) = cli.command else {
unreachable!()
};
- return commands::hook::run(args).await;
+ return commands::hook::run(data_dir, args).await;
}
let config_path = cli.config.clone();
diff --git a/crates/ai-memory-llm/src/lib.rs b/crates/ai-memory-llm/src/lib.rs
index eecd599f..cd089fe9 100644
--- a/crates/ai-memory-llm/src/lib.rs
+++ b/crates/ai-memory-llm/src/lib.rs
@@ -35,6 +35,7 @@ pub mod factory;
pub mod gemini;
pub mod google;
pub mod health;
+pub mod oidc;
pub mod openai;
pub mod openai_compat;
pub mod openai_oauth;
@@ -63,6 +64,10 @@ pub use google::{DEFAULT_MODEL as GOOGLE_DEFAULT_EMBED_MODEL, GoogleEmbedder};
pub use health::{
ProviderHealth, ProviderHealthSnapshot, ProviderHealthStatus, ProviderRoleHealthSnapshot,
};
+pub use oidc::{
+ DeviceAuthorizationResponse, OIDC_DEFAULT_SCOPE, OidcDiscovery, OidcToken, OidcTokenResponse,
+ PollOutcome, discover, poll_token_once, refresh_access_token, request_device_code,
+};
pub use openai::OpenAiProvider;
pub use openai_compat::OpenAiCompatProvider;
pub use openai_oauth::{
diff --git a/crates/ai-memory-llm/src/oidc.rs b/crates/ai-memory-llm/src/oidc.rs
new file mode 100644
index 00000000..54883c9f
--- /dev/null
+++ b/crates/ai-memory-llm/src/oidc.rs
@@ -0,0 +1,431 @@
+//! Generic OIDC Device Authorization Grant provider.
+//!
+//! Lets a developer sign the ai-memory CLI in against any OIDC issuer (e.g.
+//! Keycloak) with the device-authorization grant, so headless lifecycle hooks
+//! can POST to the server's `/hook` and `/handoff` routes carrying a
+//! **per-developer** JWT instead of a shared static token. The stored token is
+//! refreshed on demand from the hook fast-path.
+//!
+//! Storage mirrors [`crate::openai_oauth`]: the same shared `auth.json` file,
+//! under the `"oidc"` key, with `type: "oauth"` so the shared loader accepts it.
+//! The server side is unchanged — its auth layer already validates a Keycloak
+//! JWT on the hook routes (requiring the `mcp:read` realm role).
+
+use std::path::Path;
+
+use secrecy::{ExposeSecret as _, SecretString};
+use serde::{Deserialize, Serialize};
+
+use crate::auth_file::{load_entry, now_ms, save_entry};
+use crate::error::{LlmError, LlmResult};
+use crate::response::{provider_error_body, response_json_limited};
+
+/// Refresh once the access token is within this margin of expiry.
+const REFRESH_MARGIN_MS: u64 = 60_000;
+
+/// Default device-flow scopes: `openid` (ID token), `profile` (so the access
+/// token carries `preferred_username` → `X-Memory-Actor-User` on the server),
+/// and `offline_access` (refresh token). The `mcp:read` authorization the
+/// server requires is a **realm role** on the user, not a scope.
+pub const OIDC_DEFAULT_SCOPE: &str = "openid profile offline_access";
+
+/// Stored OIDC device-grant token.
+#[derive(Clone)]
+pub struct OidcToken {
+ /// Access token sent as the bearer to the ai-memory server.
+ pub access: SecretString,
+ /// Refresh token used to mint a new access token.
+ pub refresh: SecretString,
+ /// Expiry in milliseconds since the Unix epoch.
+ pub expires_at_ms: u64,
+ /// OIDC issuer this token was minted by (kept for `status` display).
+ pub issuer: String,
+ /// Public client id used for the device + refresh grants.
+ pub client_id: String,
+ /// Token endpoint resolved at login, so refresh needs no re-discovery.
+ pub token_endpoint: String,
+}
+
+impl std::fmt::Debug for OidcToken {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("OidcToken")
+ .field("access", &"<redacted>")
+ .field("refresh", &"<redacted>")
+ .field("expires_at_ms", &self.expires_at_ms)
+ .field("issuer", &self.issuer)
+ .field("client_id", &self.client_id)
+ .field("token_endpoint", &self.token_endpoint)
+ .finish()
+ }
+}
+
+impl OidcToken {
+ /// Build a token from a token-endpoint response. `previous_refresh` is used
+ /// when a refresh response omits a new `refresh_token` (the old one stays
+ /// valid), mirroring the OpenAI OAuth provider.
+ ///
+ /// # Errors
+ /// Returns [`LlmError::Auth`] when no refresh token is available — the
+ /// device flow must request the `offline_access` scope.
+ pub fn from_token_response(
+ resp: &OidcTokenResponse,
+ issuer: impl Into<String>,
+ client_id: impl Into<String>,
+ token_endpoint: impl Into<String>,
+ previous_refresh: Option<&str>,
+ ) -> LlmResult<Self> {
+ let refresh = resp
+ .refresh_token
+ .clone()
+ .or_else(|| previous_refresh.map(str::to_string))
+ .ok_or_else(|| {
+ LlmError::Auth(
+ "OIDC token response carried no refresh_token; request the \
+ `offline_access` scope and enable it on the Keycloak client"
+ .to_string(),
+ )
+ })?;
+ Ok(Self {
+ access: SecretString::from(resp.access_token.clone()),
+ refresh: SecretString::from(refresh),
+ expires_at_ms: now_ms()
+ .saturating_add(resp.expires_in.unwrap_or(300).saturating_mul(1000)),
+ issuer: issuer.into(),
+ client_id: client_id.into(),
+ token_endpoint: token_endpoint.into(),
+ })
+ }
+
+ /// True when the access token is expired or within the refresh margin.
+ #[must_use]
+ pub fn needs_refresh(&self) -> bool {
+ now_ms().saturating_add(REFRESH_MARGIN_MS) >= self.expires_at_ms
+ }
+
+ /// Load the OIDC token from the shared `auth.json` file.
+ ///
+ /// # Errors
+ /// Returns [`LlmError::Auth`] when the file exists but cannot be read/parsed.
+ pub fn load(path: &Path) -> LlmResult<Option<Self>> {
+ let Some(entry) = load_entry::<OidcEntry>(path, "oidc")? else {
+ return Ok(None);
+ };
+ if entry.kind != "oauth" {
+ return Ok(None);
+ }
+ Ok(Some(Self {
+ access: SecretString::from(entry.access),
+ refresh: SecretString::from(entry.refresh),
+ expires_at_ms: entry.expires,
+ issuer: entry.issuer,
+ client_id: entry.client_id,
+ token_endpoint: entry.token_endpoint,
+ }))
+ }
+
+ /// Save the token into the shared `auth.json` file, preserving other keys.
+ ///
+ /// # Errors
+ /// Returns [`LlmError::Auth`] when the file cannot be written.
+ pub fn save(&self, path: &Path) -> LlmResult<()> {
+ let entry = OidcEntry {
+ kind: "oauth".into(),
+ access: self.access.expose_secret().to_string(),
+ refresh: self.refresh.expose_secret().to_string(),
+ expires: self.expires_at_ms,
+ issuer: self.issuer.clone(),
+ client_id: self.client_id.clone(),
+ token_endpoint: self.token_endpoint.clone(),
+ };
+ save_entry(path, "oidc", Some(entry))
+ }
+
+ /// Remove the OIDC entry from the shared `auth.json` file.
+ ///
+ /// # Errors
+ /// Returns [`LlmError::Auth`] when the file cannot be updated.
+ pub fn remove(path: &Path) -> LlmResult<()> {
+ save_entry::<OidcEntry>(path, "oidc", None)
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+struct OidcEntry {
+ #[serde(rename = "type")]
+ kind: String,
+ access: String,
+ refresh: String,
+ expires: u64,
+ issuer: String,
+ client_id: String,
+ token_endpoint: String,
+}
+
+/// The two endpoints we need from `<issuer>/.well-known/openid-configuration`.
+#[derive(Debug, Deserialize)]
+pub struct OidcDiscovery {
+ /// Device-authorization endpoint (RFC 8628).
+ pub device_authorization_endpoint: String,
+ /// Token endpoint (device-code + refresh grants).
+ pub token_endpoint: String,
+}
+
+/// Device-authorization response (RFC 8628 §3.2).
+#[derive(Debug, Deserialize)]
+pub struct DeviceAuthorizationResponse {
+ /// Opaque device verification code, polled at the token endpoint.
+ pub device_code: String,
+ /// Short code the user types at the verification URI.
+ pub user_code: String,
+ /// URI the user opens to authorize the device.
+ pub verification_uri: String,
+ /// Verification URI with the `user_code` pre-filled, when provided.
+ #[serde(default)]
+ pub verification_uri_complete: Option<String>,
+ /// Minimum seconds to wait between polls (default 5).
+ #[serde(default)]
+ pub interval: Option<u64>,
+ /// Lifetime of the device code in seconds.
+ #[serde(default)]
+ pub expires_in: Option<u64>,
+}
+
+/// Token-endpoint success response.
+#[derive(Debug, Deserialize)]
+pub struct OidcTokenResponse {
+ /// Bearer access token for the ai-memory server.
+ pub access_token: String,
+ /// Refresh token (present when `offline_access` was granted).
+ #[serde(default)]
+ pub refresh_token: Option<String>,
+ /// Access-token lifetime in seconds.
+ #[serde(default)]
+ pub expires_in: Option<u64>,
+}
+
+#[derive(Debug, Deserialize)]
+struct TokenErrorResponse {
+ #[serde(default)]
+ error: Option<String>,
+}
+
+/// Outcome of one device-token poll (RFC 8628 §3.5).
+#[derive(Debug)]
+pub enum PollOutcome {
+ /// Keep polling at the current interval.
+ Pending,
+ /// Back off: increase the interval by 5s, per the spec.
+ SlowDown,
+ /// Authorization complete.
+ Token(Box<OidcTokenResponse>),
+ /// The user denied the request.
+ Denied,
+ /// The device code expired before authorization.
+ Expired,
+ /// Any other terminal `error` code from the token endpoint.
+ Other(String),
+}
+
+/// Resolve the device + token endpoints from the issuer's discovery document.
+///
+/// # Errors
+/// Returns [`LlmError`] on transport failure or a non-success status.
+pub async fn discover(client: &reqwest::Client, issuer: &str) -> LlmResult<OidcDiscovery> {
+ let url = format!(
+ "{}/.well-known/openid-configuration",
+ issuer.trim_end_matches('/')
+ );
+ let resp = client.get(&url).send().await.map_err(LlmError::from)?;
+ let status = resp.status();
+ if !status.is_success() {
+ let body = provider_error_body(resp).await;
+ return Err(LlmError::Auth(format!(
+ "OIDC discovery failed ({status}) for {url}: {body}"
+ )));
+ }
+ response_json_limited::<OidcDiscovery>(resp).await
+}
+
+/// Start the device-authorization grant for a public client.
+///
+/// # Errors
+/// Returns [`LlmError`] on transport failure or a non-success status.
+pub async fn request_device_code(
+ client: &reqwest::Client,
+ discovery: &OidcDiscovery,
+ client_id: &str,
+ scope: &str,
+) -> LlmResult<DeviceAuthorizationResponse> {
+ let resp = client
+ .post(&discovery.device_authorization_endpoint)
+ .form(&[("client_id", client_id), ("scope", scope)])
+ .send()
+ .await
+ .map_err(LlmError::from)?;
+ let status = resp.status();
+ if !status.is_success() {
+ let body = provider_error_body(resp).await;
+ return Err(LlmError::Auth(format!(
+ "device authorization request failed ({status}): {body}"
+ )));
+ }
+ response_json_limited::<DeviceAuthorizationResponse>(resp).await
+}
+
+/// Poll the token endpoint once with a device code.
+///
+/// # Errors
+/// Returns [`LlmError`] only on transport failure; OAuth `error` codes
+/// (`authorization_pending`, `slow_down`, …) are returned as [`PollOutcome`].
+pub async fn poll_token_once(
+ client: &reqwest::Client,
+ discovery: &OidcDiscovery,
+ client_id: &str,
+ device_code: &str,
+) -> LlmResult<PollOutcome> {
+ let resp = client
+ .post(&discovery.token_endpoint)
+ .form(&[
+ ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
+ ("device_code", device_code),
+ ("client_id", client_id),
+ ])
+ .send()
+ .await
+ .map_err(LlmError::from)?;
+ if resp.status().is_success() {
+ let token = response_json_limited::<OidcTokenResponse>(resp).await?;
+ return Ok(PollOutcome::Token(Box::new(token)));
+ }
+ let body = provider_error_body(resp).await;
+ let code = serde_json::from_str::<TokenErrorResponse>(&body)
+ .ok()
+ .and_then(|e| e.error);
+ Ok(match code.as_deref() {
+ Some("authorization_pending") => PollOutcome::Pending,
+ Some("slow_down") => PollOutcome::SlowDown,
+ Some("access_denied") => PollOutcome::Denied,
+ Some("expired_token") => PollOutcome::Expired,
+ Some(other) => PollOutcome::Other(other.to_string()),
+ None => PollOutcome::Other(body),
+ })
+}
+
+/// Exchange the refresh token for a fresh access token.
+///
+/// # Errors
+/// Returns [`LlmError::Auth`] when the refresh grant is rejected (the caller
+/// should fall back to the stale token or prompt a re-login).
+pub async fn refresh_access_token(
+ client: &reqwest::Client,
+ token: &OidcToken,
+) -> LlmResult<OidcToken> {
+ let resp = client
+ .post(&token.token_endpoint)
+ .form(&[
+ ("grant_type", "refresh_token"),
+ ("refresh_token", token.refresh.expose_secret()),
+ ("client_id", token.client_id.as_str()),
+ ])
+ .send()
+ .await
+ .map_err(LlmError::from)?;
+ let status = resp.status();
+ if !status.is_success() {
+ let body = provider_error_body(resp).await;
+ return Err(LlmError::Auth(format!(
+ "OIDC refresh failed ({status}): {body}. Run `ai-memory auth login oidc-device` again."
+ )));
+ }
+ let token_response = response_json_limited::<OidcTokenResponse>(resp).await?;
+ OidcToken::from_token_response(
+ &token_response,
+ token.issuer.clone(),
+ token.client_id.clone(),
+ token.token_endpoint.clone(),
+ Some(token.refresh.expose_secret()),
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn sample() -> OidcToken {
+ OidcToken {
+ access: SecretString::from("access-x".to_string()),
+ refresh: SecretString::from("refresh-y".to_string()),
+ expires_at_ms: now_ms() + 3_600_000,
+ issuer: "https://kc.example.com/realms/serpro".to_string(),
+ client_id: "ai-memory-dev".to_string(),
+ token_endpoint: "https://kc.example.com/realms/serpro/protocol/openid-connect/token"
+ .to_string(),
+ }
+ }
+
+ #[test]
+ fn token_round_trips_through_auth_file() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("auth.json");
+ let token = sample();
+ token.save(&path).unwrap();
+ let loaded = OidcToken::load(&path).unwrap().unwrap();
+ assert_eq!(loaded.access.expose_secret(), "access-x");
+ assert_eq!(loaded.refresh.expose_secret(), "refresh-y");
+ assert_eq!(loaded.client_id, "ai-memory-dev");
+ assert_eq!(
+ loaded.token_endpoint,
+ "https://kc.example.com/realms/serpro/protocol/openid-connect/token"
+ );
+ }
+
+ #[test]
+ fn save_preserves_sibling_entries() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("auth.json");
+ std::fs::write(
+ &path,
+ serde_json::to_vec_pretty(&serde_json::json!({
+ "openai": { "type": "oauth", "access": "a", "refresh": "b", "expires": 1 }
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+ sample().save(&path).unwrap();
+ let value =
+ serde_json::from_slice::<serde_json::Value>(&std::fs::read(&path).unwrap()).unwrap();
+ assert!(value.get("openai").is_some(), "sibling entry preserved");
+ assert_eq!(value["oidc"]["client_id"], "ai-memory-dev");
+ assert_eq!(value["oidc"]["type"], "oauth");
+ }
+
+ #[test]
+ fn remove_clears_only_the_oidc_entry() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("auth.json");
+ sample().save(&path).unwrap();
+ OidcToken::remove(&path).unwrap();
+ assert!(OidcToken::load(&path).unwrap().is_none());
+ }
+
+ #[test]
+ fn needs_refresh_true_when_expired() {
+ let mut token = sample();
+ token.expires_at_ms = now_ms();
+ assert!(token.needs_refresh());
+ }
+
+ #[test]
+ fn from_response_requires_a_refresh_token() {
+ let resp = OidcTokenResponse {
+ access_token: "a".into(),
+ refresh_token: None,
+ expires_in: Some(300),
+ };
+ let err = OidcToken::from_token_response(&resp, "iss", "cid", "tok", None);
+ assert!(err.is_err(), "missing refresh token must error");
+ // ...unless a previous refresh token is carried forward.
+ let ok = OidcToken::from_token_response(&resp, "iss", "cid", "tok", Some("old-refresh"));
+ assert_eq!(ok.unwrap().refresh.expose_secret(), "old-refresh");
+ }
+}
diff --git a/docs/windows.md b/docs/windows.md
index 276f7698..de51e04e 100644
--- a/docs/windows.md
+++ b/docs/windows.md
@@ -208,11 +208,16 @@ native on an i7-6700HQ). Notes:
cmd.exe and Git Bash.
- The `.sh`/`.ps1` scripts stay bundled as a fallback — the Docker /
`setup-agent` flow (no local binary) keeps emitting the shell command.
-- `AI_MEMORY_HOOK_PLATFORM` accepts three values:
+- `AI_MEMORY_HOOK_PLATFORM` accepts four values:
- `windows-native` — direct binary call (default on native Windows).
- `windows-bash` — `bash -c` + `.sh` through Git Bash (the previous
default; set this to opt back in).
- `posix` — POSIX `.sh` (default on macOS / Linux).
+ - `posix-native` — direct binary call on macOS / Linux (`<exe> hook
+ --event …`) instead of the `.sh` script, so the hook uses the local
+ event spool + OIDC-token fallback. **Opt-in** (never the default,
+ because the Docker wrapper renders for the host with no local binary).
+ Set it when ai-memory is installed as a native binary (cargo / release).
Set the env var before running `install-hooks` so the chosen platform
is baked into the rendered hook commands.