Skip to main content

keep_rs/
lib.rs

1pub mod error;
2pub mod knowledge;
3pub mod memory;
4pub mod scope;
5
6use std::fmt;
7use std::time::Duration;
8
9use reqwest::Url;
10use serde::de::DeserializeOwned;
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13
14pub use error::{ConfigError, ErrorCode, Head, KeepError, Result, UnavailableReason};
15pub use knowledge::{
16    Allowance, Citation, Episode, FORGET_SOURCES_LIMIT, ForgetSourceReceipt, ForgottenSource,
17    IngestReport, ItemRef, KnowledgeCitations, KnowledgeCiteRequest, KnowledgeClient,
18    KnowledgeFetchRequest, KnowledgeForgetSourceResult, KnowledgeForgetSourcesResult,
19    KnowledgeIndexRequest, KnowledgeIngestRequest, KnowledgeIngestResult, KnowledgeRebuildResult,
20    KnowledgeSearchRequest, KnowledgeSearchResult, KnowledgeStatus, KnowledgeSummarizeRequest,
21    KnowledgeSummary, KnowledgeTraverseRequest, SOURCE_ALLOWLIST_LIMIT, SearchHit, TokenUsage,
22};
23pub use memory::{
24    ExportedFile, ForgetReceipt, InstructionFilesPolicy, ListedFile, MemoryClient, MemoryContext,
25    MemoryContextRequest, MemoryDeleteRequest, MemoryEdit, MemoryEntry, MemoryExport,
26    MemoryExportRequest, MemoryFile, MemoryForgetRequest, MemoryHistory, MemoryList,
27    MemoryListRequest, MemoryReadRequest, MemoryRevision, MemoryTarget, MemoryUndoRequest,
28    MemoryUpdateMetadataRequest, MemoryWriteRequest, MetadataOutcome, WriteOutcome,
29};
30pub use scope::Scope;
31
32pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
33pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);
34
35#[derive(Clone)]
36pub struct KeepConfig {
37    endpoint: Url,
38    token: Option<String>,
39    connect_timeout: Duration,
40    timeout: Duration,
41}
42
43impl fmt::Debug for KeepConfig {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        f.debug_struct("KeepConfig")
46            .field("endpoint", &self.endpoint.as_str())
47            .field("token", &self.token.as_ref().map(|_| "[REDACTED]"))
48            .field("connect_timeout", &self.connect_timeout)
49            .field("timeout", &self.timeout)
50            .finish()
51    }
52}
53
54impl KeepConfig {
55    pub fn new(endpoint: &str) -> std::result::Result<Self, ConfigError> {
56        let endpoint = parse_origin(endpoint)?;
57        Ok(Self {
58            endpoint,
59            token: None,
60            connect_timeout: DEFAULT_CONNECT_TIMEOUT,
61            timeout: DEFAULT_TIMEOUT,
62        })
63    }
64
65    pub fn from_env() -> std::result::Result<Option<Self>, ConfigError> {
66        let raw = match std::env::var("KEEP_ENDPOINT") {
67            Ok(v) if !v.trim().is_empty() => v.trim().to_string(),
68            _ => return Ok(None),
69        };
70        let endpoint = parse_origin(&raw)?;
71        let token = match std::env::var("KEEP_TOKEN") {
72            Ok(v) if !v.trim().is_empty() => Some(v.trim().to_string()),
73            _ => match std::env::var("KEEP_TOKEN_FILE") {
74                Ok(path) if !path.trim().is_empty() => {
75                    let contents = std::fs::read_to_string(path.trim())?;
76                    let trimmed = contents.trim();
77                    if trimmed.is_empty() {
78                        None
79                    } else {
80                        Some(trimmed.to_string())
81                    }
82                }
83                _ => None,
84            },
85        };
86        Ok(Some(Self {
87            endpoint,
88            token,
89            connect_timeout: DEFAULT_CONNECT_TIMEOUT,
90            timeout: DEFAULT_TIMEOUT,
91        }))
92    }
93
94    pub fn endpoint(&self) -> &str {
95        self.endpoint.as_str()
96    }
97
98    pub fn token(mut self, token: impl Into<String>) -> Self {
99        let t = token.into();
100        self.token = if t.trim().is_empty() { None } else { Some(t) };
101        self
102    }
103
104    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
105        self.connect_timeout = timeout;
106        self
107    }
108
109    pub fn timeout(mut self, timeout: Duration) -> Self {
110        self.timeout = timeout;
111        self
112    }
113}
114
115fn parse_origin(raw: &str) -> std::result::Result<Url, ConfigError> {
116    let url = Url::parse(raw.trim()).map_err(|_| ConfigError::InvalidEndpoint)?;
117    if !matches!(url.scheme(), "http" | "https")
118        || !url.username().is_empty()
119        || url.password().is_some()
120        || url.query().is_some()
121        || url.fragment().is_some()
122        || url.path() != "/"
123    {
124        return Err(ConfigError::InvalidEndpoint);
125    }
126    Ok(url)
127}
128
129#[non_exhaustive]
130#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
131pub struct HealthInfo {
132    pub status: String,
133    #[serde(default)]
134    pub version: Option<String>,
135    #[serde(flatten)]
136    pub extra: serde_json::Map<String, Value>,
137}
138
139#[non_exhaustive]
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141#[serde(rename_all = "camelCase")]
142pub struct ToolDescriptor {
143    pub name: String,
144    pub method: String,
145    pub path: String,
146    pub description: String,
147    pub read_only: bool,
148    pub destructive: bool,
149    pub input_schema: Value,
150}
151
152#[derive(Debug, Deserialize)]
153struct ToolsResponse {
154    tools: Vec<ToolDescriptor>,
155}
156
157#[derive(Debug, Deserialize)]
158struct WireErrorBody {
159    error: WireError,
160}
161
162#[derive(Debug, Deserialize)]
163struct WireError {
164    code: String,
165    #[serde(default)]
166    message: String,
167    #[serde(default)]
168    reason: Option<String>,
169    #[serde(default)]
170    details: Option<Value>,
171}
172
173#[derive(Clone)]
174pub struct KeepClient {
175    http: reqwest::Client,
176    endpoint: Url,
177    token: Option<String>,
178}
179
180impl fmt::Debug for KeepClient {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        f.debug_struct("KeepClient")
183            .field("endpoint", &self.endpoint.as_str())
184            .field("token", &self.token.as_ref().map(|_| "[REDACTED]"))
185            .finish()
186    }
187}
188
189impl KeepClient {
190    pub fn new(config: KeepConfig) -> std::result::Result<Self, ConfigError> {
191        let http = reqwest::Client::builder()
192            .redirect(reqwest::redirect::Policy::none())
193            .connect_timeout(config.connect_timeout)
194            .timeout(config.timeout)
195            .build()
196            .map_err(|e| ConfigError::Http(e.to_string()))?;
197        Ok(Self {
198            http,
199            endpoint: config.endpoint,
200            token: config.token,
201        })
202    }
203
204    pub fn from_env() -> std::result::Result<Option<Self>, ConfigError> {
205        KeepConfig::from_env()?.map(Self::new).transpose()
206    }
207
208    pub fn endpoint(&self) -> &str {
209        self.endpoint.as_str()
210    }
211
212    pub fn scope(&self, scope: Scope) -> ScopedClient<'_> {
213        ScopedClient {
214            client: self,
215            scope,
216        }
217    }
218
219    pub fn memory(&self) -> MemoryClient<'_> {
220        MemoryClient::new(self, None)
221    }
222
223    pub fn knowledge(&self) -> KnowledgeClient<'_> {
224        KnowledgeClient::new(self, None)
225    }
226
227    pub async fn health(&self) -> Result<HealthInfo> {
228        self.get_json("/v1/health", false).await
229    }
230
231    pub async fn ready(&self) -> Result<HealthInfo> {
232        self.get_json("/v1/health/ready", false).await
233    }
234
235    pub async fn tools(&self) -> Result<Vec<ToolDescriptor>> {
236        let resp: ToolsResponse = self.get_json("/v1/tools", true).await?;
237        Ok(resp.tools)
238    }
239
240    fn url_for(&self, path: &str) -> Url {
241        let mut url = self.endpoint.clone();
242        url.set_path(path);
243        url
244    }
245
246    async fn get_json<T: DeserializeOwned>(&self, path: &str, with_auth: bool) -> Result<T> {
247        let mut req = self.http.get(self.url_for(path));
248        if with_auth && let Some(token) = &self.token {
249            req = req.bearer_auth(token);
250        }
251        let resp = req.send().await.map_err(map_transport_err)?;
252        self.decode_response(resp, path == "/v1/health/ready").await
253    }
254
255    pub(crate) async fn post_json<T: DeserializeOwned>(
256        &self,
257        path: &str,
258        body: Value,
259    ) -> Result<T> {
260        let mut req = self.http.post(self.url_for(path)).json(&body);
261        if let Some(token) = &self.token {
262            req = req.bearer_auth(token);
263        }
264        let resp = req.send().await.map_err(map_transport_err)?;
265        self.decode_response(resp, false).await
266    }
267
268    async fn decode_response<T: DeserializeOwned>(
269        &self,
270        resp: reqwest::Response,
271        is_readiness: bool,
272    ) -> Result<T> {
273        let status = resp.status();
274        let bytes = resp.bytes().await.map_err(map_transport_err)?;
275        if status.is_success() {
276            return serde_json::from_slice(&bytes).map_err(|e| KeepError::Unavailable {
277                reason: UnavailableReason::InvalidResponse,
278                status: Some(status.as_u16()),
279                message: e.to_string(),
280            });
281        }
282        if is_readiness && status.as_u16() == 503 {
283            return Err(KeepError::Unavailable {
284                reason: UnavailableReason::NotReady,
285                status: Some(503),
286                message: String::from_utf8_lossy(&bytes).into_owned(),
287            });
288        }
289        if let Ok(wire) = serde_json::from_slice::<WireErrorBody>(&bytes) {
290            let code = ErrorCode::parse(&wire.error.code);
291            return Err(KeepError::Api {
292                status: status.as_u16(),
293                code,
294                message: wire.error.message,
295                reason: wire.error.reason,
296                details: wire.error.details,
297            });
298        }
299        Err(KeepError::Unavailable {
300            reason: if status.as_u16() == 503 {
301                UnavailableReason::NotReady
302            } else {
303                UnavailableReason::InvalidResponse
304            },
305            status: Some(status.as_u16()),
306            message: String::from_utf8_lossy(&bytes).into_owned(),
307        })
308    }
309}
310
311#[derive(Debug, Clone)]
312pub struct ScopedClient<'a> {
313    client: &'a KeepClient,
314    scope: Scope,
315}
316
317impl<'a> ScopedClient<'a> {
318    pub fn scope(&self) -> &Scope {
319        &self.scope
320    }
321
322    pub fn memory(&self) -> MemoryClient<'_> {
323        MemoryClient::new(self.client, Some(&self.scope))
324    }
325
326    pub fn knowledge(&self) -> KnowledgeClient<'_> {
327        KnowledgeClient::new(self.client, Some(&self.scope))
328    }
329}
330
331fn map_transport_err(err: reqwest::Error) -> KeepError {
332    let reason = if err.is_timeout() {
333        UnavailableReason::Timeout
334    } else {
335        UnavailableReason::Unreachable
336    };
337    KeepError::Unavailable {
338        reason,
339        status: err.status().map(|s| s.as_u16()),
340        message: err.to_string(),
341    }
342}
343
344#[cfg(test)]
345mod tests {
346    use super::*;
347
348    #[test]
349    fn debug_redacts_bearer_token() {
350        let secret = "super-secret-token-value";
351        let config = KeepConfig::new("http://127.0.0.1:7357")
352            .unwrap()
353            .token(secret);
354        let client = KeepClient::new(config.clone()).unwrap();
355
356        let config_dbg = format!("{config:?}");
357        let client_dbg = format!("{client:?}");
358        assert!(!config_dbg.contains(secret));
359        assert!(!client_dbg.contains(secret));
360        assert!(config_dbg.contains("[REDACTED]"));
361        assert!(client_dbg.contains("[REDACTED]"));
362    }
363
364    #[test]
365    fn unknown_error_code_and_timeout_retryability() {
366        assert_eq!(ErrorCode::parse("future_error"), ErrorCode::Unknown);
367        let timeout = KeepError::Unavailable {
368            reason: UnavailableReason::Timeout,
369            status: None,
370            message: "timed out".into(),
371        };
372        assert!(!timeout.is_retryable());
373        let unreachable = KeepError::Unavailable {
374            reason: UnavailableReason::Unreachable,
375            status: None,
376            message: "connection refused".into(),
377        };
378        assert!(unreachable.is_retryable());
379    }
380}