keep-rs 0.2.0

Rust HTTP client SDK for Keep Memory and Knowledge
Documentation
pub mod error;
pub mod knowledge;
pub mod memory;
pub mod scope;

use std::fmt;
use std::time::Duration;

use reqwest::Url;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::Value;

pub use error::{ConfigError, ErrorCode, Head, KeepError, Result, UnavailableReason};
pub use knowledge::{
    Allowance, Citation, Episode, FORGET_SOURCES_LIMIT, ForgetSourceReceipt, ForgottenSource,
    IngestReport, ItemRef, KnowledgeCitations, KnowledgeCiteRequest, KnowledgeClient,
    KnowledgeFetchRequest, KnowledgeForgetSourceResult, KnowledgeForgetSourcesResult,
    KnowledgeIndexRequest, KnowledgeIngestRequest, KnowledgeIngestResult, KnowledgeRebuildResult,
    KnowledgeSearchRequest, KnowledgeSearchResult, KnowledgeStatus, KnowledgeSummarizeRequest,
    KnowledgeSummary, KnowledgeTraverseRequest, SOURCE_ALLOWLIST_LIMIT, SearchHit, TokenUsage,
};
pub use memory::{
    ExportedFile, ForgetReceipt, InstructionFilesPolicy, ListedFile, MemoryClient, MemoryContext,
    MemoryContextRequest, MemoryDeleteRequest, MemoryEdit, MemoryEntry, MemoryExport,
    MemoryExportRequest, MemoryFile, MemoryForgetRequest, MemoryHistory, MemoryList,
    MemoryListRequest, MemoryReadRequest, MemoryRevision, MemoryTarget, MemoryUndoRequest,
    MemoryUpdateMetadataRequest, MemoryWriteRequest, MetadataOutcome, WriteOutcome,
};
pub use scope::Scope;

pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);

#[derive(Clone)]
pub struct KeepConfig {
    endpoint: Url,
    token: Option<String>,
    connect_timeout: Duration,
    timeout: Duration,
}

impl fmt::Debug for KeepConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("KeepConfig")
            .field("endpoint", &self.endpoint.as_str())
            .field("token", &self.token.as_ref().map(|_| "[REDACTED]"))
            .field("connect_timeout", &self.connect_timeout)
            .field("timeout", &self.timeout)
            .finish()
    }
}

impl KeepConfig {
    pub fn new(endpoint: &str) -> std::result::Result<Self, ConfigError> {
        let endpoint = parse_origin(endpoint)?;
        Ok(Self {
            endpoint,
            token: None,
            connect_timeout: DEFAULT_CONNECT_TIMEOUT,
            timeout: DEFAULT_TIMEOUT,
        })
    }

    pub fn from_env() -> std::result::Result<Option<Self>, ConfigError> {
        let raw = match std::env::var("KEEP_ENDPOINT") {
            Ok(v) if !v.trim().is_empty() => v.trim().to_string(),
            _ => return Ok(None),
        };
        let endpoint = parse_origin(&raw)?;
        let token = match std::env::var("KEEP_TOKEN") {
            Ok(v) if !v.trim().is_empty() => Some(v.trim().to_string()),
            _ => match std::env::var("KEEP_TOKEN_FILE") {
                Ok(path) if !path.trim().is_empty() => {
                    let contents = std::fs::read_to_string(path.trim())?;
                    let trimmed = contents.trim();
                    if trimmed.is_empty() {
                        None
                    } else {
                        Some(trimmed.to_string())
                    }
                }
                _ => None,
            },
        };
        Ok(Some(Self {
            endpoint,
            token,
            connect_timeout: DEFAULT_CONNECT_TIMEOUT,
            timeout: DEFAULT_TIMEOUT,
        }))
    }

    pub fn endpoint(&self) -> &str {
        self.endpoint.as_str()
    }

    pub fn token(mut self, token: impl Into<String>) -> Self {
        let t = token.into();
        self.token = if t.trim().is_empty() { None } else { Some(t) };
        self
    }

    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = timeout;
        self
    }

    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }
}

fn parse_origin(raw: &str) -> std::result::Result<Url, ConfigError> {
    let url = Url::parse(raw.trim()).map_err(|_| ConfigError::InvalidEndpoint)?;
    if !matches!(url.scheme(), "http" | "https")
        || !url.username().is_empty()
        || url.password().is_some()
        || url.query().is_some()
        || url.fragment().is_some()
        || url.path() != "/"
    {
        return Err(ConfigError::InvalidEndpoint);
    }
    Ok(url)
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HealthInfo {
    pub status: String,
    #[serde(default)]
    pub version: Option<String>,
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolDescriptor {
    pub name: String,
    pub method: String,
    pub path: String,
    pub description: String,
    pub read_only: bool,
    pub destructive: bool,
    pub input_schema: Value,
}

#[derive(Debug, Deserialize)]
struct ToolsResponse {
    tools: Vec<ToolDescriptor>,
}

#[derive(Debug, Deserialize)]
struct WireErrorBody {
    error: WireError,
}

#[derive(Debug, Deserialize)]
struct WireError {
    code: String,
    #[serde(default)]
    message: String,
    #[serde(default)]
    reason: Option<String>,
    #[serde(default)]
    details: Option<Value>,
}

#[derive(Clone)]
pub struct KeepClient {
    http: reqwest::Client,
    endpoint: Url,
    token: Option<String>,
}

impl fmt::Debug for KeepClient {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("KeepClient")
            .field("endpoint", &self.endpoint.as_str())
            .field("token", &self.token.as_ref().map(|_| "[REDACTED]"))
            .finish()
    }
}

impl KeepClient {
    pub fn new(config: KeepConfig) -> std::result::Result<Self, ConfigError> {
        let http = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .connect_timeout(config.connect_timeout)
            .timeout(config.timeout)
            .build()
            .map_err(|e| ConfigError::Http(e.to_string()))?;
        Ok(Self {
            http,
            endpoint: config.endpoint,
            token: config.token,
        })
    }

    pub fn from_env() -> std::result::Result<Option<Self>, ConfigError> {
        KeepConfig::from_env()?.map(Self::new).transpose()
    }

    pub fn endpoint(&self) -> &str {
        self.endpoint.as_str()
    }

    pub fn scope(&self, scope: Scope) -> ScopedClient<'_> {
        ScopedClient {
            client: self,
            scope,
        }
    }

    pub fn memory(&self) -> MemoryClient<'_> {
        MemoryClient::new(self, None)
    }

    pub fn knowledge(&self) -> KnowledgeClient<'_> {
        KnowledgeClient::new(self, None)
    }

    pub async fn health(&self) -> Result<HealthInfo> {
        self.get_json("/v1/health", false).await
    }

    pub async fn ready(&self) -> Result<HealthInfo> {
        self.get_json("/v1/health/ready", false).await
    }

    pub async fn tools(&self) -> Result<Vec<ToolDescriptor>> {
        let resp: ToolsResponse = self.get_json("/v1/tools", true).await?;
        Ok(resp.tools)
    }

    fn url_for(&self, path: &str) -> Url {
        let mut url = self.endpoint.clone();
        url.set_path(path);
        url
    }

    async fn get_json<T: DeserializeOwned>(&self, path: &str, with_auth: bool) -> Result<T> {
        let mut req = self.http.get(self.url_for(path));
        if with_auth && let Some(token) = &self.token {
            req = req.bearer_auth(token);
        }
        let resp = req.send().await.map_err(map_transport_err)?;
        self.decode_response(resp, path == "/v1/health/ready").await
    }

    pub(crate) async fn post_json<T: DeserializeOwned>(
        &self,
        path: &str,
        body: Value,
    ) -> Result<T> {
        let mut req = self.http.post(self.url_for(path)).json(&body);
        if let Some(token) = &self.token {
            req = req.bearer_auth(token);
        }
        let resp = req.send().await.map_err(map_transport_err)?;
        self.decode_response(resp, false).await
    }

    async fn decode_response<T: DeserializeOwned>(
        &self,
        resp: reqwest::Response,
        is_readiness: bool,
    ) -> Result<T> {
        let status = resp.status();
        let bytes = resp.bytes().await.map_err(map_transport_err)?;
        if status.is_success() {
            return serde_json::from_slice(&bytes).map_err(|e| KeepError::Unavailable {
                reason: UnavailableReason::InvalidResponse,
                status: Some(status.as_u16()),
                message: e.to_string(),
            });
        }
        if is_readiness && status.as_u16() == 503 {
            return Err(KeepError::Unavailable {
                reason: UnavailableReason::NotReady,
                status: Some(503),
                message: String::from_utf8_lossy(&bytes).into_owned(),
            });
        }
        if let Ok(wire) = serde_json::from_slice::<WireErrorBody>(&bytes) {
            let code = ErrorCode::parse(&wire.error.code);
            return Err(KeepError::Api {
                status: status.as_u16(),
                code,
                message: wire.error.message,
                reason: wire.error.reason,
                details: wire.error.details,
            });
        }
        Err(KeepError::Unavailable {
            reason: if status.as_u16() == 503 {
                UnavailableReason::NotReady
            } else {
                UnavailableReason::InvalidResponse
            },
            status: Some(status.as_u16()),
            message: String::from_utf8_lossy(&bytes).into_owned(),
        })
    }
}

#[derive(Debug, Clone)]
pub struct ScopedClient<'a> {
    client: &'a KeepClient,
    scope: Scope,
}

impl<'a> ScopedClient<'a> {
    pub fn scope(&self) -> &Scope {
        &self.scope
    }

    pub fn memory(&self) -> MemoryClient<'_> {
        MemoryClient::new(self.client, Some(&self.scope))
    }

    pub fn knowledge(&self) -> KnowledgeClient<'_> {
        KnowledgeClient::new(self.client, Some(&self.scope))
    }
}

fn map_transport_err(err: reqwest::Error) -> KeepError {
    let reason = if err.is_timeout() {
        UnavailableReason::Timeout
    } else {
        UnavailableReason::Unreachable
    };
    KeepError::Unavailable {
        reason,
        status: err.status().map(|s| s.as_u16()),
        message: err.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn debug_redacts_bearer_token() {
        let secret = "super-secret-token-value";
        let config = KeepConfig::new("http://127.0.0.1:7357")
            .unwrap()
            .token(secret);
        let client = KeepClient::new(config.clone()).unwrap();

        let config_dbg = format!("{config:?}");
        let client_dbg = format!("{client:?}");
        assert!(!config_dbg.contains(secret));
        assert!(!client_dbg.contains(secret));
        assert!(config_dbg.contains("[REDACTED]"));
        assert!(client_dbg.contains("[REDACTED]"));
    }

    #[test]
    fn unknown_error_code_and_timeout_retryability() {
        assert_eq!(ErrorCode::parse("future_error"), ErrorCode::Unknown);
        let timeout = KeepError::Unavailable {
            reason: UnavailableReason::Timeout,
            status: None,
            message: "timed out".into(),
        };
        assert!(!timeout.is_retryable());
        let unreachable = KeepError::Unavailable {
            reason: UnavailableReason::Unreachable,
            status: None,
            message: "connection refused".into(),
        };
        assert!(unreachable.is_retryable());
    }
}