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()
}