Skip to main content

keep_rs/
memory.rs

1use serde::{Deserialize, Serialize};
2use serde_json::{Map, Value, json};
3
4use crate::KeepClient;
5use crate::error::{Head, KeepError, Result};
6use crate::scope::Scope;
7
8#[non_exhaustive]
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum MemoryTarget {
11    Path(String),
12    MemoryId(String),
13}
14
15impl MemoryTarget {
16    pub fn path(path: impl Into<String>) -> Self {
17        Self::Path(path.into())
18    }
19
20    pub fn memory_id(id: impl Into<String>) -> Self {
21        Self::MemoryId(id.into())
22    }
23
24    fn apply(&self, body: &mut Map<String, Value>) {
25        match self {
26            Self::Path(p) => {
27                body.insert("path".into(), json!(p));
28            }
29            Self::MemoryId(id) => {
30                body.insert("memory_id".into(), json!(id));
31            }
32        }
33    }
34}
35
36#[non_exhaustive]
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(tag = "command", rename_all = "snake_case")]
39pub enum MemoryEdit {
40    StrReplace {
41        old: String,
42        new: String,
43        #[serde(default)]
44        replace_all: bool,
45    },
46    Insert {
47        line: usize,
48        text: String,
49    },
50}
51
52#[non_exhaustive]
53#[derive(Debug, Clone, Default)]
54pub struct MemoryContextRequest {
55    pub budget_tokens: Option<usize>,
56    pub query: Option<String>,
57    pub referenced_paths: Vec<String>,
58    pub include_knowledge: Option<bool>,
59    pub include_personal: Option<bool>,
60}
61
62impl MemoryContextRequest {
63    pub fn new() -> Self {
64        Self::default()
65    }
66
67    pub fn budget_tokens(mut self, tokens: usize) -> Self {
68        self.budget_tokens = Some(tokens);
69        self
70    }
71
72    pub fn query(mut self, query: impl Into<String>) -> Self {
73        self.query = Some(query.into());
74        self
75    }
76
77    pub fn referenced_paths(mut self, paths: impl IntoIterator<Item = impl Into<String>>) -> Self {
78        self.referenced_paths = paths.into_iter().map(Into::into).collect();
79        self
80    }
81
82    pub fn include_knowledge(mut self, include: bool) -> Self {
83        self.include_knowledge = Some(include);
84        self
85    }
86
87    pub fn include_personal(mut self, include: bool) -> Self {
88        self.include_personal = Some(include);
89        self
90    }
91}
92
93#[non_exhaustive]
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95pub struct MemoryContext {
96    pub text: String,
97    pub tokens: u64,
98    pub scope: String,
99    #[serde(default)]
100    pub notes: Vec<String>,
101}
102
103#[non_exhaustive]
104#[derive(Debug, Clone, Default)]
105pub struct MemoryListRequest {
106    pub category: Option<String>,
107    pub include_trashed: bool,
108    pub after: Option<String>,
109    pub limit: Option<usize>,
110}
111
112impl MemoryListRequest {
113    pub fn new() -> Self {
114        Self::default()
115    }
116
117    pub fn category(mut self, category: impl Into<String>) -> Self {
118        self.category = Some(category.into());
119        self
120    }
121
122    pub fn include_trashed(mut self, include: bool) -> Self {
123        self.include_trashed = include;
124        self
125    }
126
127    pub fn after(mut self, after: impl Into<String>) -> Self {
128        self.after = Some(after.into());
129        self
130    }
131
132    pub fn limit(mut self, limit: usize) -> Self {
133        self.limit = Some(limit);
134        self
135    }
136}
137
138#[non_exhaustive]
139#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
140#[serde(rename_all = "camelCase")]
141pub struct ListedFile {
142    pub memory_id: String,
143    pub path: String,
144    pub revision_id: String,
145    pub version: String,
146    #[serde(default)]
147    pub trashed: bool,
148    #[serde(default)]
149    pub category: Option<String>,
150    #[serde(default)]
151    pub display_name: Option<String>,
152    #[serde(default)]
153    pub description: Option<String>,
154    #[serde(default)]
155    pub size_bytes: Option<u64>,
156    #[serde(default)]
157    pub updated_at: Option<String>,
158}
159
160#[non_exhaustive]
161#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
162#[serde(rename_all = "camelCase")]
163pub struct MemoryList {
164    pub scope: String,
165    #[serde(default)]
166    pub tree_revision: u64,
167    #[serde(default)]
168    pub total: usize,
169    #[serde(default)]
170    pub next_after: Option<String>,
171    #[serde(default)]
172    pub tree: String,
173    #[serde(default)]
174    pub files: Vec<ListedFile>,
175}
176
177#[non_exhaustive]
178#[derive(Debug, Clone)]
179pub struct MemoryReadRequest {
180    pub target: MemoryTarget,
181    pub revision_id: Option<String>,
182    pub include_entries: bool,
183}
184
185impl MemoryReadRequest {
186    pub fn path(path: impl Into<String>) -> Self {
187        Self {
188            target: MemoryTarget::path(path),
189            revision_id: None,
190            include_entries: false,
191        }
192    }
193
194    pub fn memory_id(id: impl Into<String>) -> Self {
195        Self {
196            target: MemoryTarget::memory_id(id),
197            revision_id: None,
198            include_entries: false,
199        }
200    }
201
202    pub fn target(target: MemoryTarget) -> Self {
203        Self {
204            target,
205            revision_id: None,
206            include_entries: false,
207        }
208    }
209
210    pub fn revision_id(mut self, revision_id: impl Into<String>) -> Self {
211        self.revision_id = Some(revision_id.into());
212        self
213    }
214
215    pub fn include_entries(mut self, include: bool) -> Self {
216        self.include_entries = include;
217        self
218    }
219}
220
221#[non_exhaustive]
222#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
223#[serde(rename_all = "camelCase")]
224pub struct MemoryEntry {
225    pub entry_id: String,
226    pub text: String,
227}
228
229#[non_exhaustive]
230#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
231#[serde(rename_all = "camelCase")]
232pub struct MemoryFile {
233    pub scope: String,
234    pub memory_id: String,
235    pub path: String,
236    #[serde(default)]
237    pub category: Option<String>,
238    #[serde(default)]
239    pub description: Option<String>,
240    pub revision_id: String,
241    pub version: String,
242    pub is_head: bool,
243    pub head: Head,
244    #[serde(default)]
245    pub updated_at: Option<String>,
246    pub text: String,
247    #[serde(default)]
248    pub entries: Vec<MemoryEntry>,
249}
250
251#[non_exhaustive]
252#[derive(Debug, Clone)]
253pub struct MemoryWriteRequest {
254    pub path: String,
255    pub text: Option<String>,
256    pub edit: Option<MemoryEdit>,
257    pub expected_revision_id: Option<String>,
258    pub merge: bool,
259    pub description: Option<String>,
260    pub idempotency_key: Option<String>,
261}
262
263impl MemoryWriteRequest {
264    pub fn text(path: impl Into<String>, text: impl Into<String>) -> Self {
265        Self {
266            path: path.into(),
267            text: Some(text.into()),
268            edit: None,
269            expected_revision_id: None,
270            merge: false,
271            description: None,
272            idempotency_key: None,
273        }
274    }
275
276    pub fn edit(path: impl Into<String>, edit: MemoryEdit) -> Self {
277        Self {
278            path: path.into(),
279            text: None,
280            edit: Some(edit),
281            expected_revision_id: None,
282            merge: false,
283            description: None,
284            idempotency_key: None,
285        }
286    }
287
288    pub fn expected_revision_id(mut self, revision_id: impl Into<String>) -> Self {
289        self.expected_revision_id = Some(revision_id.into());
290        self
291    }
292
293    pub fn merge(mut self, merge: bool) -> Self {
294        self.merge = merge;
295        self
296    }
297
298    pub fn description(mut self, description: impl Into<String>) -> Self {
299        self.description = Some(description.into());
300        self
301    }
302
303    pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
304        self.idempotency_key = Some(key.into());
305        self
306    }
307}
308
309#[non_exhaustive]
310#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
311#[serde(rename_all = "camelCase")]
312pub struct WriteOutcome {
313    pub memory_id: String,
314    pub head: Head,
315    pub seq: i64,
316    pub changed: bool,
317    pub replayed: bool,
318    pub revision_id: String,
319    #[serde(default)]
320    pub scope: Option<String>,
321    #[serde(default)]
322    pub path: Option<String>,
323}
324
325#[non_exhaustive]
326#[derive(Debug, Clone)]
327pub struct MemoryUpdateMetadataRequest {
328    pub target: MemoryTarget,
329    pub expected_revision_id: String,
330    pub description: Option<String>,
331    pub display_name: Option<String>,
332}
333
334impl MemoryUpdateMetadataRequest {
335    pub fn new(target: MemoryTarget, expected_revision_id: impl Into<String>) -> Self {
336        Self {
337            target,
338            expected_revision_id: expected_revision_id.into(),
339            description: None,
340            display_name: None,
341        }
342    }
343
344    pub fn description(mut self, description: impl Into<String>) -> Self {
345        self.description = Some(description.into());
346        self
347    }
348
349    pub fn display_name(mut self, display_name: impl Into<String>) -> Self {
350        self.display_name = Some(display_name.into());
351        self
352    }
353}
354
355#[non_exhaustive]
356#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
357#[serde(rename_all = "camelCase")]
358pub struct MetadataOutcome {
359    pub memory_id: String,
360    pub head: Head,
361    pub seq: i64,
362    pub changed: bool,
363    pub replayed: bool,
364    pub revision_id: String,
365    pub path: String,
366    pub display_name: String,
367    pub description: String,
368}
369
370#[non_exhaustive]
371#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
372#[serde(rename_all = "camelCase")]
373pub struct MemoryRevision {
374    pub revision_id: String,
375    pub seq: i64,
376    pub change: String,
377    pub created_at: String,
378    pub version: String,
379    pub path: String,
380    pub is_head: bool,
381}
382
383#[non_exhaustive]
384#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
385#[serde(rename_all = "camelCase")]
386pub struct MemoryHistory {
387    pub scope: String,
388    pub memory_id: String,
389    pub revisions: Vec<MemoryRevision>,
390}
391
392#[non_exhaustive]
393#[derive(Debug, Clone)]
394pub struct MemoryUndoRequest {
395    pub target: MemoryTarget,
396    pub expected_revision_id: String,
397    pub target_revision_id: Option<String>,
398}
399
400impl MemoryUndoRequest {
401    pub fn new(target: MemoryTarget, expected_revision_id: impl Into<String>) -> Self {
402        Self {
403            target,
404            expected_revision_id: expected_revision_id.into(),
405            target_revision_id: None,
406        }
407    }
408
409    pub fn target_revision_id(mut self, revision_id: impl Into<String>) -> Self {
410        self.target_revision_id = Some(revision_id.into());
411        self
412    }
413}
414
415#[non_exhaustive]
416#[derive(Debug, Clone)]
417pub struct MemoryDeleteRequest {
418    pub target: MemoryTarget,
419    pub expected_revision_id: String,
420}
421
422impl MemoryDeleteRequest {
423    pub fn new(target: MemoryTarget, expected_revision_id: impl Into<String>) -> Self {
424        Self {
425            target,
426            expected_revision_id: expected_revision_id.into(),
427        }
428    }
429}
430
431#[non_exhaustive]
432#[derive(Debug, Clone, Default)]
433pub struct MemoryForgetRequest {
434    pub target: Option<MemoryTarget>,
435    pub entry_id: Option<String>,
436    pub text: Option<String>,
437}
438
439impl MemoryForgetRequest {
440    pub fn file(target: MemoryTarget) -> Self {
441        Self {
442            target: Some(target),
443            entry_id: None,
444            text: None,
445        }
446    }
447
448    pub fn entry(target: MemoryTarget, entry_id: impl Into<String>) -> Self {
449        Self {
450            target: Some(target),
451            entry_id: Some(entry_id.into()),
452            text: None,
453        }
454    }
455
456    pub fn text(text: impl Into<String>) -> Self {
457        Self {
458            target: None,
459            entry_id: None,
460            text: Some(text.into()),
461        }
462    }
463
464    pub fn in_file(mut self, target: MemoryTarget) -> Self {
465        self.target = Some(target);
466        self
467    }
468}
469
470#[non_exhaustive]
471#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
472#[serde(rename_all = "camelCase")]
473pub struct ForgetReceipt {
474    pub erasure_seq: i64,
475    pub files_affected: Vec<String>,
476    pub files_purged: Vec<String>,
477    pub revisions_purged: i64,
478}
479
480#[non_exhaustive]
481#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
482pub struct MemoryForgetResponse {
483    pub scope: String,
484    pub receipt: ForgetReceipt,
485}
486
487#[non_exhaustive]
488#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
489#[serde(rename_all = "snake_case")]
490pub enum InstructionFilesPolicy {
491    Refuse,
492    Skip,
493    AllowMarked,
494}
495
496impl InstructionFilesPolicy {
497    fn as_str(self) -> &'static str {
498        match self {
499            Self::Refuse => "refuse",
500            Self::Skip => "skip",
501            Self::AllowMarked => "allow_marked",
502        }
503    }
504}
505
506#[non_exhaustive]
507#[derive(Debug, Clone, Default)]
508pub struct MemoryExportRequest {
509    pub instruction_files: Option<InstructionFilesPolicy>,
510}
511
512impl MemoryExportRequest {
513    pub fn new() -> Self {
514        Self::default()
515    }
516
517    pub fn instruction_files(mut self, policy: InstructionFilesPolicy) -> Self {
518        self.instruction_files = Some(policy);
519        self
520    }
521}
522
523#[non_exhaustive]
524#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
525pub struct ExportedFile {
526    pub path: String,
527    pub text: String,
528}
529
530#[non_exhaustive]
531#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
532#[serde(rename_all = "camelCase")]
533pub struct MemoryExport {
534    pub scope: String,
535    pub files: Vec<ExportedFile>,
536    #[serde(default)]
537    pub skipped_instruction_files: Vec<String>,
538    #[serde(default)]
539    pub marked_instruction_files: Vec<String>,
540    #[serde(default)]
541    pub manifest: Value,
542}
543
544#[derive(Debug, Clone, Copy)]
545pub struct MemoryClient<'a> {
546    client: &'a KeepClient,
547    scope: Option<&'a Scope>,
548}
549
550impl<'a> MemoryClient<'a> {
551    pub(crate) fn new(client: &'a KeepClient, scope: Option<&'a Scope>) -> Self {
552        Self { client, scope }
553    }
554
555    fn base_body(&self) -> Map<String, Value> {
556        let mut body = Map::new();
557        if let Some(scope) = self.scope
558            && !scope.is_empty()
559        {
560            body.insert("scope".into(), json!(scope));
561        }
562        body
563    }
564
565    pub async fn context(&self, req: MemoryContextRequest) -> Result<MemoryContext> {
566        let mut body = self.base_body();
567        if let Some(budget_tokens) = req.budget_tokens {
568            body.insert("budget_tokens".into(), json!(budget_tokens));
569        }
570        if let Some(query) = req.query {
571            body.insert("query".into(), json!(query));
572        }
573        if !req.referenced_paths.is_empty() {
574            body.insert("referenced_paths".into(), json!(req.referenced_paths));
575        }
576        if let Some(include_knowledge) = req.include_knowledge {
577            body.insert("include_knowledge".into(), json!(include_knowledge));
578        }
579        if let Some(include_personal) = req.include_personal {
580            body.insert("include_personal".into(), json!(include_personal));
581        }
582        self.client
583            .post_json("/v1/memory/context", Value::Object(body))
584            .await
585    }
586
587    pub async fn list(&self, req: MemoryListRequest) -> Result<MemoryList> {
588        let mut body = self.base_body();
589        if let Some(category) = req.category {
590            body.insert("category".into(), json!(category));
591        }
592        if req.include_trashed {
593            body.insert("include_trashed".into(), json!(true));
594        }
595        if let Some(after) = req.after {
596            body.insert("after".into(), json!(after));
597        }
598        if let Some(limit) = req.limit {
599            body.insert("limit".into(), json!(limit));
600        }
601        self.client
602            .post_json("/v1/memory/list", Value::Object(body))
603            .await
604    }
605
606    pub async fn list_all(&self, mut req: MemoryListRequest) -> Result<Vec<ListedFile>> {
607        let mut all = Vec::new();
608        loop {
609            let page = self.list(req.clone()).await?;
610            all.extend(page.files);
611            match page.next_after {
612                Some(cursor) => req.after = Some(cursor),
613                None => return Ok(all),
614            }
615        }
616    }
617
618    pub async fn read(&self, req: MemoryReadRequest) -> Result<MemoryFile> {
619        let mut body = self.base_body();
620        req.target.apply(&mut body);
621        if let Some(revision_id) = req.revision_id {
622            body.insert("revision_id".into(), json!(revision_id));
623        }
624        if req.include_entries {
625            body.insert("include_entries".into(), json!(true));
626        }
627        self.client
628            .post_json("/v1/memory/read", Value::Object(body))
629            .await
630    }
631
632    pub async fn read_optional(&self, req: MemoryReadRequest) -> Result<Option<MemoryFile>> {
633        match self.read(req).await {
634            Ok(file) => Ok(Some(file)),
635            Err(err) if err.is_not_found() => Ok(None),
636            Err(err) => Err(err),
637        }
638    }
639
640    pub async fn write(&self, req: MemoryWriteRequest) -> Result<WriteOutcome> {
641        let mut body = self.base_body();
642        body.insert("path".into(), json!(req.path));
643        if let Some(text) = req.text {
644            body.insert("text".into(), json!(text));
645        }
646        if let Some(edit) = req.edit {
647            body.insert("edit".into(), json!(edit));
648        }
649        if let Some(expected_revision_id) = req.expected_revision_id {
650            body.insert("expected_revision_id".into(), json!(expected_revision_id));
651        }
652        if req.merge {
653            body.insert("merge".into(), json!(true));
654        }
655        if let Some(description) = req.description {
656            body.insert("description".into(), json!(description));
657        }
658        if let Some(idempotency_key) = req.idempotency_key {
659            body.insert("idempotency_key".into(), json!(idempotency_key));
660        }
661        self.client
662            .post_json("/v1/memory/write", Value::Object(body))
663            .await
664    }
665
666    pub async fn update_metadata(
667        &self,
668        req: MemoryUpdateMetadataRequest,
669    ) -> Result<MetadataOutcome> {
670        let mut body = self.base_body();
671        req.target.apply(&mut body);
672        body.insert(
673            "expected_revision_id".into(),
674            json!(req.expected_revision_id),
675        );
676        if let Some(description) = req.description {
677            body.insert("description".into(), json!(description));
678        }
679        if let Some(display_name) = req.display_name {
680            body.insert("display_name".into(), json!(display_name));
681        }
682        self.client
683            .post_json("/v1/memory/update_metadata", Value::Object(body))
684            .await
685    }
686
687    pub async fn history(&self, target: MemoryTarget) -> Result<MemoryHistory> {
688        let mut body = self.base_body();
689        target.apply(&mut body);
690        self.client
691            .post_json("/v1/memory/history", Value::Object(body))
692            .await
693    }
694
695    pub async fn undo(&self, req: MemoryUndoRequest) -> Result<WriteOutcome> {
696        let mut body = self.base_body();
697        req.target.apply(&mut body);
698        body.insert(
699            "expected_revision_id".into(),
700            json!(req.expected_revision_id),
701        );
702        if let Some(target_revision_id) = req.target_revision_id {
703            body.insert("target_revision_id".into(), json!(target_revision_id));
704        }
705        self.client
706            .post_json("/v1/memory/undo", Value::Object(body))
707            .await
708    }
709
710    pub async fn delete(&self, req: MemoryDeleteRequest) -> Result<WriteOutcome> {
711        let mut body = self.base_body();
712        req.target.apply(&mut body);
713        body.insert(
714            "expected_revision_id".into(),
715            json!(req.expected_revision_id),
716        );
717        self.client
718            .post_json("/v1/memory/delete", Value::Object(body))
719            .await
720    }
721
722    pub async fn restore(&self, target: MemoryTarget) -> Result<WriteOutcome> {
723        let mut body = self.base_body();
724        target.apply(&mut body);
725        self.client
726            .post_json("/v1/memory/restore", Value::Object(body))
727            .await
728    }
729
730    pub async fn forget(&self, req: MemoryForgetRequest) -> Result<ForgetReceipt> {
731        let mut body = self.base_body();
732        if let Some(target) = req.target {
733            target.apply(&mut body);
734        }
735        if let Some(entry_id) = req.entry_id {
736            body.insert("entry_id".into(), json!(entry_id));
737        }
738        if let Some(text) = req.text {
739            body.insert("text".into(), json!(text));
740        }
741        let resp: MemoryForgetResponse = self
742            .client
743            .post_json("/v1/memory/forget", Value::Object(body))
744            .await?;
745        Ok(resp.receipt)
746    }
747
748    pub async fn export(&self, req: MemoryExportRequest) -> Result<MemoryExport> {
749        let mut body = self.base_body();
750        if let Some(policy) = req.instruction_files {
751            body.insert("instruction_files".into(), json!(policy.as_str()));
752        }
753        self.client
754            .post_json("/v1/memory/export", Value::Object(body))
755            .await
756    }
757}
758
759pub fn is_not_found(err: &KeepError) -> bool {
760    err.is_not_found()
761}