keep-rs 0.2.0

Rust HTTP client SDK for Keep Memory and Knowledge
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};

use crate::KeepClient;
use crate::error::{Head, KeepError, Result};
use crate::scope::Scope;

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MemoryTarget {
    Path(String),
    MemoryId(String),
}

impl MemoryTarget {
    pub fn path(path: impl Into<String>) -> Self {
        Self::Path(path.into())
    }

    pub fn memory_id(id: impl Into<String>) -> Self {
        Self::MemoryId(id.into())
    }

    fn apply(&self, body: &mut Map<String, Value>) {
        match self {
            Self::Path(p) => {
                body.insert("path".into(), json!(p));
            }
            Self::MemoryId(id) => {
                body.insert("memory_id".into(), json!(id));
            }
        }
    }
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "command", rename_all = "snake_case")]
pub enum MemoryEdit {
    StrReplace {
        old: String,
        new: String,
        #[serde(default)]
        replace_all: bool,
    },
    Insert {
        line: usize,
        text: String,
    },
}

#[non_exhaustive]
#[derive(Debug, Clone, Default)]
pub struct MemoryContextRequest {
    pub budget_tokens: Option<usize>,
    pub query: Option<String>,
    pub referenced_paths: Vec<String>,
    pub include_knowledge: Option<bool>,
    pub include_personal: Option<bool>,
}

impl MemoryContextRequest {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn budget_tokens(mut self, tokens: usize) -> Self {
        self.budget_tokens = Some(tokens);
        self
    }

    pub fn query(mut self, query: impl Into<String>) -> Self {
        self.query = Some(query.into());
        self
    }

    pub fn referenced_paths(mut self, paths: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.referenced_paths = paths.into_iter().map(Into::into).collect();
        self
    }

    pub fn include_knowledge(mut self, include: bool) -> Self {
        self.include_knowledge = Some(include);
        self
    }

    pub fn include_personal(mut self, include: bool) -> Self {
        self.include_personal = Some(include);
        self
    }
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemoryContext {
    pub text: String,
    pub tokens: u64,
    pub scope: String,
    #[serde(default)]
    pub notes: Vec<String>,
}

#[non_exhaustive]
#[derive(Debug, Clone, Default)]
pub struct MemoryListRequest {
    pub category: Option<String>,
    pub include_trashed: bool,
    pub after: Option<String>,
    pub limit: Option<usize>,
}

impl MemoryListRequest {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn category(mut self, category: impl Into<String>) -> Self {
        self.category = Some(category.into());
        self
    }

    pub fn include_trashed(mut self, include: bool) -> Self {
        self.include_trashed = include;
        self
    }

    pub fn after(mut self, after: impl Into<String>) -> Self {
        self.after = Some(after.into());
        self
    }

    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListedFile {
    pub memory_id: String,
    pub path: String,
    pub revision_id: String,
    pub version: String,
    #[serde(default)]
    pub trashed: bool,
    #[serde(default)]
    pub category: Option<String>,
    #[serde(default)]
    pub display_name: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub size_bytes: Option<u64>,
    #[serde(default)]
    pub updated_at: Option<String>,
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryList {
    pub scope: String,
    #[serde(default)]
    pub tree_revision: u64,
    #[serde(default)]
    pub total: usize,
    #[serde(default)]
    pub next_after: Option<String>,
    #[serde(default)]
    pub tree: String,
    #[serde(default)]
    pub files: Vec<ListedFile>,
}

#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct MemoryReadRequest {
    pub target: MemoryTarget,
    pub revision_id: Option<String>,
    pub include_entries: bool,
}

impl MemoryReadRequest {
    pub fn path(path: impl Into<String>) -> Self {
        Self {
            target: MemoryTarget::path(path),
            revision_id: None,
            include_entries: false,
        }
    }

    pub fn memory_id(id: impl Into<String>) -> Self {
        Self {
            target: MemoryTarget::memory_id(id),
            revision_id: None,
            include_entries: false,
        }
    }

    pub fn target(target: MemoryTarget) -> Self {
        Self {
            target,
            revision_id: None,
            include_entries: false,
        }
    }

    pub fn revision_id(mut self, revision_id: impl Into<String>) -> Self {
        self.revision_id = Some(revision_id.into());
        self
    }

    pub fn include_entries(mut self, include: bool) -> Self {
        self.include_entries = include;
        self
    }
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryEntry {
    pub entry_id: String,
    pub text: String,
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryFile {
    pub scope: String,
    pub memory_id: String,
    pub path: String,
    #[serde(default)]
    pub category: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    pub revision_id: String,
    pub version: String,
    pub is_head: bool,
    pub head: Head,
    #[serde(default)]
    pub updated_at: Option<String>,
    pub text: String,
    #[serde(default)]
    pub entries: Vec<MemoryEntry>,
}

#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct MemoryWriteRequest {
    pub path: String,
    pub text: Option<String>,
    pub edit: Option<MemoryEdit>,
    pub expected_revision_id: Option<String>,
    pub merge: bool,
    pub description: Option<String>,
    pub idempotency_key: Option<String>,
}

impl MemoryWriteRequest {
    pub fn text(path: impl Into<String>, text: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            text: Some(text.into()),
            edit: None,
            expected_revision_id: None,
            merge: false,
            description: None,
            idempotency_key: None,
        }
    }

    pub fn edit(path: impl Into<String>, edit: MemoryEdit) -> Self {
        Self {
            path: path.into(),
            text: None,
            edit: Some(edit),
            expected_revision_id: None,
            merge: false,
            description: None,
            idempotency_key: None,
        }
    }

    pub fn expected_revision_id(mut self, revision_id: impl Into<String>) -> Self {
        self.expected_revision_id = Some(revision_id.into());
        self
    }

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

    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
        self.idempotency_key = Some(key.into());
        self
    }
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WriteOutcome {
    pub memory_id: String,
    pub head: Head,
    pub seq: i64,
    pub changed: bool,
    pub replayed: bool,
    pub revision_id: String,
    #[serde(default)]
    pub scope: Option<String>,
    #[serde(default)]
    pub path: Option<String>,
}

#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct MemoryUpdateMetadataRequest {
    pub target: MemoryTarget,
    pub expected_revision_id: String,
    pub description: Option<String>,
    pub display_name: Option<String>,
}

impl MemoryUpdateMetadataRequest {
    pub fn new(target: MemoryTarget, expected_revision_id: impl Into<String>) -> Self {
        Self {
            target,
            expected_revision_id: expected_revision_id.into(),
            description: None,
            display_name: None,
        }
    }

    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    pub fn display_name(mut self, display_name: impl Into<String>) -> Self {
        self.display_name = Some(display_name.into());
        self
    }
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MetadataOutcome {
    pub memory_id: String,
    pub head: Head,
    pub seq: i64,
    pub changed: bool,
    pub replayed: bool,
    pub revision_id: String,
    pub path: String,
    pub display_name: String,
    pub description: String,
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryRevision {
    pub revision_id: String,
    pub seq: i64,
    pub change: String,
    pub created_at: String,
    pub version: String,
    pub path: String,
    pub is_head: bool,
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryHistory {
    pub scope: String,
    pub memory_id: String,
    pub revisions: Vec<MemoryRevision>,
}

#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct MemoryUndoRequest {
    pub target: MemoryTarget,
    pub expected_revision_id: String,
    pub target_revision_id: Option<String>,
}

impl MemoryUndoRequest {
    pub fn new(target: MemoryTarget, expected_revision_id: impl Into<String>) -> Self {
        Self {
            target,
            expected_revision_id: expected_revision_id.into(),
            target_revision_id: None,
        }
    }

    pub fn target_revision_id(mut self, revision_id: impl Into<String>) -> Self {
        self.target_revision_id = Some(revision_id.into());
        self
    }
}

#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct MemoryDeleteRequest {
    pub target: MemoryTarget,
    pub expected_revision_id: String,
}

impl MemoryDeleteRequest {
    pub fn new(target: MemoryTarget, expected_revision_id: impl Into<String>) -> Self {
        Self {
            target,
            expected_revision_id: expected_revision_id.into(),
        }
    }
}

#[non_exhaustive]
#[derive(Debug, Clone, Default)]
pub struct MemoryForgetRequest {
    pub target: Option<MemoryTarget>,
    pub entry_id: Option<String>,
    pub text: Option<String>,
}

impl MemoryForgetRequest {
    pub fn file(target: MemoryTarget) -> Self {
        Self {
            target: Some(target),
            entry_id: None,
            text: None,
        }
    }

    pub fn entry(target: MemoryTarget, entry_id: impl Into<String>) -> Self {
        Self {
            target: Some(target),
            entry_id: Some(entry_id.into()),
            text: None,
        }
    }

    pub fn text(text: impl Into<String>) -> Self {
        Self {
            target: None,
            entry_id: None,
            text: Some(text.into()),
        }
    }

    pub fn in_file(mut self, target: MemoryTarget) -> Self {
        self.target = Some(target);
        self
    }
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ForgetReceipt {
    pub erasure_seq: i64,
    pub files_affected: Vec<String>,
    pub files_purged: Vec<String>,
    pub revisions_purged: i64,
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemoryForgetResponse {
    pub scope: String,
    pub receipt: ForgetReceipt,
}

#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InstructionFilesPolicy {
    Refuse,
    Skip,
    AllowMarked,
}

impl InstructionFilesPolicy {
    fn as_str(self) -> &'static str {
        match self {
            Self::Refuse => "refuse",
            Self::Skip => "skip",
            Self::AllowMarked => "allow_marked",
        }
    }
}

#[non_exhaustive]
#[derive(Debug, Clone, Default)]
pub struct MemoryExportRequest {
    pub instruction_files: Option<InstructionFilesPolicy>,
}

impl MemoryExportRequest {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn instruction_files(mut self, policy: InstructionFilesPolicy) -> Self {
        self.instruction_files = Some(policy);
        self
    }
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExportedFile {
    pub path: String,
    pub text: String,
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryExport {
    pub scope: String,
    pub files: Vec<ExportedFile>,
    #[serde(default)]
    pub skipped_instruction_files: Vec<String>,
    #[serde(default)]
    pub marked_instruction_files: Vec<String>,
    #[serde(default)]
    pub manifest: Value,
}

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

impl<'a> MemoryClient<'a> {
    pub(crate) fn new(client: &'a KeepClient, scope: Option<&'a Scope>) -> Self {
        Self { client, scope }
    }

    fn base_body(&self) -> Map<String, Value> {
        let mut body = Map::new();
        if let Some(scope) = self.scope
            && !scope.is_empty()
        {
            body.insert("scope".into(), json!(scope));
        }
        body
    }

    pub async fn context(&self, req: MemoryContextRequest) -> Result<MemoryContext> {
        let mut body = self.base_body();
        if let Some(budget_tokens) = req.budget_tokens {
            body.insert("budget_tokens".into(), json!(budget_tokens));
        }
        if let Some(query) = req.query {
            body.insert("query".into(), json!(query));
        }
        if !req.referenced_paths.is_empty() {
            body.insert("referenced_paths".into(), json!(req.referenced_paths));
        }
        if let Some(include_knowledge) = req.include_knowledge {
            body.insert("include_knowledge".into(), json!(include_knowledge));
        }
        if let Some(include_personal) = req.include_personal {
            body.insert("include_personal".into(), json!(include_personal));
        }
        self.client
            .post_json("/v1/memory/context", Value::Object(body))
            .await
    }

    pub async fn list(&self, req: MemoryListRequest) -> Result<MemoryList> {
        let mut body = self.base_body();
        if let Some(category) = req.category {
            body.insert("category".into(), json!(category));
        }
        if req.include_trashed {
            body.insert("include_trashed".into(), json!(true));
        }
        if let Some(after) = req.after {
            body.insert("after".into(), json!(after));
        }
        if let Some(limit) = req.limit {
            body.insert("limit".into(), json!(limit));
        }
        self.client
            .post_json("/v1/memory/list", Value::Object(body))
            .await
    }

    pub async fn list_all(&self, mut req: MemoryListRequest) -> Result<Vec<ListedFile>> {
        let mut all = Vec::new();
        loop {
            let page = self.list(req.clone()).await?;
            all.extend(page.files);
            match page.next_after {
                Some(cursor) => req.after = Some(cursor),
                None => return Ok(all),
            }
        }
    }

    pub async fn read(&self, req: MemoryReadRequest) -> Result<MemoryFile> {
        let mut body = self.base_body();
        req.target.apply(&mut body);
        if let Some(revision_id) = req.revision_id {
            body.insert("revision_id".into(), json!(revision_id));
        }
        if req.include_entries {
            body.insert("include_entries".into(), json!(true));
        }
        self.client
            .post_json("/v1/memory/read", Value::Object(body))
            .await
    }

    pub async fn read_optional(&self, req: MemoryReadRequest) -> Result<Option<MemoryFile>> {
        match self.read(req).await {
            Ok(file) => Ok(Some(file)),
            Err(err) if err.is_not_found() => Ok(None),
            Err(err) => Err(err),
        }
    }

    pub async fn write(&self, req: MemoryWriteRequest) -> Result<WriteOutcome> {
        let mut body = self.base_body();
        body.insert("path".into(), json!(req.path));
        if let Some(text) = req.text {
            body.insert("text".into(), json!(text));
        }
        if let Some(edit) = req.edit {
            body.insert("edit".into(), json!(edit));
        }
        if let Some(expected_revision_id) = req.expected_revision_id {
            body.insert("expected_revision_id".into(), json!(expected_revision_id));
        }
        if req.merge {
            body.insert("merge".into(), json!(true));
        }
        if let Some(description) = req.description {
            body.insert("description".into(), json!(description));
        }
        if let Some(idempotency_key) = req.idempotency_key {
            body.insert("idempotency_key".into(), json!(idempotency_key));
        }
        self.client
            .post_json("/v1/memory/write", Value::Object(body))
            .await
    }

    pub async fn update_metadata(
        &self,
        req: MemoryUpdateMetadataRequest,
    ) -> Result<MetadataOutcome> {
        let mut body = self.base_body();
        req.target.apply(&mut body);
        body.insert(
            "expected_revision_id".into(),
            json!(req.expected_revision_id),
        );
        if let Some(description) = req.description {
            body.insert("description".into(), json!(description));
        }
        if let Some(display_name) = req.display_name {
            body.insert("display_name".into(), json!(display_name));
        }
        self.client
            .post_json("/v1/memory/update_metadata", Value::Object(body))
            .await
    }

    pub async fn history(&self, target: MemoryTarget) -> Result<MemoryHistory> {
        let mut body = self.base_body();
        target.apply(&mut body);
        self.client
            .post_json("/v1/memory/history", Value::Object(body))
            .await
    }

    pub async fn undo(&self, req: MemoryUndoRequest) -> Result<WriteOutcome> {
        let mut body = self.base_body();
        req.target.apply(&mut body);
        body.insert(
            "expected_revision_id".into(),
            json!(req.expected_revision_id),
        );
        if let Some(target_revision_id) = req.target_revision_id {
            body.insert("target_revision_id".into(), json!(target_revision_id));
        }
        self.client
            .post_json("/v1/memory/undo", Value::Object(body))
            .await
    }

    pub async fn delete(&self, req: MemoryDeleteRequest) -> Result<WriteOutcome> {
        let mut body = self.base_body();
        req.target.apply(&mut body);
        body.insert(
            "expected_revision_id".into(),
            json!(req.expected_revision_id),
        );
        self.client
            .post_json("/v1/memory/delete", Value::Object(body))
            .await
    }

    pub async fn restore(&self, target: MemoryTarget) -> Result<WriteOutcome> {
        let mut body = self.base_body();
        target.apply(&mut body);
        self.client
            .post_json("/v1/memory/restore", Value::Object(body))
            .await
    }

    pub async fn forget(&self, req: MemoryForgetRequest) -> Result<ForgetReceipt> {
        let mut body = self.base_body();
        if let Some(target) = req.target {
            target.apply(&mut body);
        }
        if let Some(entry_id) = req.entry_id {
            body.insert("entry_id".into(), json!(entry_id));
        }
        if let Some(text) = req.text {
            body.insert("text".into(), json!(text));
        }
        let resp: MemoryForgetResponse = self
            .client
            .post_json("/v1/memory/forget", Value::Object(body))
            .await?;
        Ok(resp.receipt)
    }

    pub async fn export(&self, req: MemoryExportRequest) -> Result<MemoryExport> {
        let mut body = self.base_body();
        if let Some(policy) = req.instruction_files {
            body.insert("instruction_files".into(), json!(policy.as_str()));
        }
        self.client
            .post_json("/v1/memory/export", Value::Object(body))
            .await
    }
}

pub fn is_not_found(err: &KeepError) -> bool {
    err.is_not_found()
}