use std::fmt;
use std::sync::Arc;
use futures::future::BoxFuture;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MemoryScope {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tenant: Option<String>,
pub agent: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub user: Option<String>,
}
impl MemoryScope {
pub fn agent(tenant: Option<String>, agent: impl Into<String>) -> Self {
Self { tenant, agent: agent.into(), user: None }
}
pub fn user(tenant: Option<String>, agent: impl Into<String>, user: impl Into<String>) -> Self {
Self { tenant, agent: agent.into(), user: Some(user.into()) }
}
pub fn agent_level(&self) -> Self {
Self { tenant: self.tenant.clone(), agent: self.agent.clone(), user: None }
}
pub fn validate(&self) -> Result<(), MemoryError> {
check_name("agent", &self.agent)?;
if let Some(tenant) = &self.tenant {
check_name("tenant", tenant)?;
}
if let Some(user) = &self.user {
check_user(user)?;
}
Ok(())
}
}
pub fn check_name(what: &str, name: &str) -> Result<(), MemoryError> {
let ok = !name.is_empty()
&& name.len() <= 128
&& !name.starts_with('.')
&& name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'));
if ok {
Ok(())
} else {
Err(MemoryError::new(
"memory_scope",
format!("{what} `{name}` must be 1 to 128 letters, digits, `.`, `_` or `-`, not starting with `.`"),
))
}
}
pub fn check_user(user: &str) -> Result<(), MemoryError> {
let id = UserSource::split(user).map_or(user, |(_, id)| id);
let ok = !id.trim().is_empty() && id.chars().count() <= 256 && !id.chars().any(char::is_control);
if ok { Ok(()) } else { Err(MemoryError::new("memory_scope", "a user id must be 1 to 256 visible characters")) }
}
pub const USER_SOURCE_VAR: &str = "user_source";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum UserSource {
Verified,
Api,
Channel,
}
impl UserSource {
#[cfg(test)]
const ALL: [Self; 3] = [Self::Verified, Self::Api, Self::Channel];
pub fn of_caller(verified: bool) -> Self {
if verified { Self::Verified } else { Self::Api }
}
pub fn as_str(self) -> &'static str {
match self {
Self::Verified => "user",
Self::Api => "api",
Self::Channel => "channel",
}
}
pub fn parse(word: &str) -> Option<Self> {
match word {
"user" => Some(Self::Verified),
"api" => Some(Self::Api),
"channel" => Some(Self::Channel),
_ => None,
}
}
pub fn scoped(self, id: &str) -> String {
format!("{}/{id}", self.as_str())
}
pub fn split(user: &str) -> Option<(Self, &str)> {
let (word, id) = user.split_once('/')?;
Some((Self::parse(word)?, id))
}
}
pub fn owner_named_user(user: &str) -> String {
scoped_as(user, UserSource::Api)
}
pub fn scoped_as(user: &str, source: UserSource) -> String {
match UserSource::split(user) {
Some(_) => user.to_owned(),
None => source.scoped(user),
}
}
pub fn run_user_id(user: &str) -> &str {
UserSource::split(user).map_or(user, |(_, id)| id)
}
pub fn legacy_user(user: &str) -> Option<&str> {
let (_, id) = UserSource::split(user)?;
let plain = !id.trim().is_empty() && id.chars().count() <= 256 && !id.chars().any(char::is_control);
plain.then_some(id)
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MemoryKind {
Fact,
Preference,
Event,
#[default]
Note,
}
impl MemoryKind {
pub fn as_str(self) -> &'static str {
match self {
Self::Fact => "fact",
Self::Preference => "preference",
Self::Event => "event",
Self::Note => "note",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MemoryTrust {
Owner,
UserStated,
ModelInferred,
ModelAfterTools,
ToolDerived,
}
impl MemoryTrust {
pub fn as_str(self) -> &'static str {
match self {
Self::Owner => "owner",
Self::UserStated => "user_stated",
Self::ModelInferred => "model_inferred",
Self::ModelAfterTools => "model_after_tools",
Self::ToolDerived => "tool_derived",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MemoryStatus {
Active,
Pending,
}
impl MemoryStatus {
pub fn as_str(self) -> &'static str {
match self {
Self::Active => "active",
Self::Pending => "pending",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WritePolicy {
#[default]
Guarded,
Review,
Open,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemorySource {
pub actor: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub run_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub node_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub conversation_id: Option<String>,
}
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct NewMemory {
pub text: String,
pub kind: MemoryKind,
pub tags: Vec<String>,
pub trust: MemoryTrust,
pub policy: WritePolicy,
pub source: MemorySource,
pub secrets: Vec<String>,
}
impl NewMemory {
pub fn new(text: impl Into<String>, trust: MemoryTrust, source: MemorySource) -> Self {
Self {
text: text.into(),
kind: MemoryKind::Note,
tags: Vec::new(),
trust,
policy: WritePolicy::Guarded,
source,
secrets: Vec::new(),
}
}
pub fn kind(mut self, kind: MemoryKind) -> Self {
self.kind = kind;
self
}
pub fn tags(mut self, tags: Vec<String>) -> Self {
self.tags = tags;
self
}
pub fn policy(mut self, policy: WritePolicy) -> Self {
self.policy = policy;
self
}
pub fn secrets(mut self, secrets: Vec<String>) -> Self {
self.secrets = secrets;
self
}
}
impl fmt::Debug for NewMemory {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NewMemory")
.field("text", &self.text)
.field("kind", &self.kind)
.field("tags", &self.tags)
.field("trust", &self.trust)
.field("policy", &self.policy)
.field("source", &self.source)
.field("secrets", &format_args!("[{} masked]", self.secrets.len()))
.finish()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MemoryRecord {
pub id: String,
pub text: String,
pub kind: MemoryKind,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<String>,
pub status: MemoryStatus,
pub trust: MemoryTrust,
pub created_ms: u64,
pub updated_ms: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_ms: Option<u64>,
#[serde(default)]
pub last_used_ms: u64,
#[serde(default)]
pub uses: u64,
pub source: MemorySource,
}
impl MemoryRecord {
pub fn new(
id: impl Into<String>,
text: impl Into<String>,
kind: MemoryKind,
status: MemoryStatus,
trust: MemoryTrust,
source: MemorySource,
now_ms: u64,
) -> Self {
Self {
id: id.into(),
text: text.into(),
kind,
tags: Vec::new(),
status,
trust,
created_ms: now_ms,
updated_ms: now_ms,
expires_ms: None,
last_used_ms: now_ms,
uses: 0,
source,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct MemoryQuery {
pub text: String,
pub limit: usize,
pub touch: bool,
pub fill_recent: bool,
pub as_of_ms: Option<u64>,
}
impl MemoryQuery {
pub fn new(text: impl Into<String>) -> Self {
Self { text: text.into(), ..Self::default() }
}
pub fn limit(mut self, limit: usize) -> Self {
self.limit = limit;
self
}
pub fn touch(mut self) -> Self {
self.touch = true;
self
}
pub fn fill_recent(mut self) -> Self {
self.fill_recent = true;
self
}
pub fn as_of(mut self, ms: u64) -> Self {
self.as_of_ms = Some(ms);
self
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ExtractedFacts {
#[serde(default)]
pub entities: Vec<ExtractedEntity>,
#[serde(default)]
pub relations: Vec<ExtractedRelation>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ExtractedEntity {
pub name: String,
#[serde(default, rename = "type")]
pub kind: String,
#[serde(default)]
pub aliases: Vec<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ExtractedRelation {
pub source: String,
pub relation: String,
pub target: String,
#[serde(default)]
pub valid_from: Option<String>,
#[serde(default)]
pub valid_to: Option<String>,
#[serde(default)]
pub replaces: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HitKind {
Note,
Fact,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MemoryLevel {
User,
Agent,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MemoryHit {
pub kind: HitKind,
pub record: MemoryRecord,
pub level: MemoryLevel,
pub score: f32,
}
impl MemoryHit {
pub fn note(record: MemoryRecord, level: MemoryLevel, score: f32) -> Self {
Self { kind: HitKind::Note, record, level, score }
}
pub fn fact(record: MemoryRecord, level: MemoryLevel, score: f32) -> Self {
Self { kind: HitKind::Fact, record, level, score }
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ForgetTarget {
Id(String),
Query(String),
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("{message}")]
pub struct MemoryError {
pub kind: &'static str,
pub message: String,
}
impl MemoryError {
pub fn new(kind: &'static str, message: impl Into<String>) -> Self {
Self { kind, message: message.into() }
}
}
pub trait MemoryBank: Send + Sync + fmt::Debug {
fn remember<'a>(
&'a self,
scope: &'a MemoryScope,
note: NewMemory,
) -> BoxFuture<'a, Result<MemoryRecord, MemoryError>>;
fn recall<'a>(
&'a self,
scope: &'a MemoryScope,
query: &'a MemoryQuery,
) -> BoxFuture<'a, Result<Vec<MemoryHit>, MemoryError>>;
fn forget<'a>(
&'a self,
scope: &'a MemoryScope,
target: &'a ForgetTarget,
source: &'a MemorySource,
) -> BoxFuture<'a, Result<usize, MemoryError>>;
fn adopt<'a>(
&'a self,
scope: &'a MemoryScope,
source: &'a MemorySource,
) -> BoxFuture<'a, Result<bool, MemoryError>> {
let _ = (scope, source);
Box::pin(async { Ok(false) })
}
fn keeps_graph(&self) -> bool {
false
}
fn known_entities<'a>(
&'a self,
scope: &'a MemoryScope,
limit: usize,
) -> BoxFuture<'a, Result<Vec<String>, MemoryError>> {
let _ = (scope, limit);
Box::pin(async { Ok(Vec::new()) })
}
fn link<'a>(
&'a self,
scope: &'a MemoryScope,
note_id: &'a str,
facts: ExtractedFacts,
) -> BoxFuture<'a, Result<usize, MemoryError>> {
let _ = (scope, note_id, facts);
Box::pin(async { Err(MemoryError::new("memory_graph", "this memory store keeps no graph")) })
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct MemoryDefaults {
pub tenant: Option<String>,
pub agent: Option<String>,
}
#[derive(Clone, Debug)]
pub struct Memories(pub Arc<dyn MemoryBank>);
impl Memories {
pub fn new(bank: Arc<dyn MemoryBank>) -> Self {
Self(bank)
}
}
pub fn tokens(text: &str) -> Vec<String> {
let cjk = |c: char| matches!(u32::from(c), 0x3040..=0x30FF | 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xAC00..=0xD7AF | 0xF900..=0xFAFF);
let mut out = Vec::new();
let mut word = String::new();
for c in text.chars() {
if cjk(c) {
if !word.is_empty() {
out.push(std::mem::take(&mut word));
}
out.push(c.to_string());
} else if c.is_alphanumeric() {
word.extend(c.to_lowercase());
} else if !word.is_empty() {
out.push(std::mem::take(&mut word));
}
}
if !word.is_empty() {
out.push(word);
}
out
}
pub fn words(text: &str) -> Vec<String> {
tokens(text).into_iter().map(|word| stem(&word)).collect()
}
pub fn stem(word: &str) -> String {
if !word.is_ascii() || word.len() <= 3 {
return word.to_owned();
}
const SUFFIXES: [&str; 12] = ["ingly", "edly", "ing", "ies", "ied", "ly", "ed", "es", "s", "nya", "kan", "lah"];
for suffix in SUFFIXES {
if let Some(base) = word.strip_suffix(suffix) {
if base.len() < 3 || (suffix == "s" && (base.ends_with('s') || base.ends_with('u') || base.ends_with('i')))
{
continue;
}
if suffix == "es" && !["x", "sh", "ch", "ss", "z"].iter().any(|end| base.ends_with(end)) {
continue;
}
return match suffix {
"ies" | "ied" => format!("{base}y"),
_ => base.to_owned(),
};
}
}
word.to_owned()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_scoped_user_id_names_its_source_and_keeps_the_id_whole() {
assert_eq!(UserSource::Channel.scoped("shop:42"), "channel/shop:42");
assert_eq!(UserSource::Verified.scoped("a/b"), "user/a/b", "an id may hold slashes");
assert_eq!(UserSource::split("user/a/b"), Some((UserSource::Verified, "a/b")));
assert_eq!(UserSource::split("api/42"), Some((UserSource::Api, "42")));
assert_eq!(UserSource::split("42"), None, "an id stored before sources");
assert_eq!(UserSource::split("team/42"), None, "an unknown word is part of an old id");
assert_eq!(legacy_user("channel/shop:42"), Some("shop:42"));
assert_eq!(legacy_user("shop:42"), None);
assert_eq!(legacy_user("api/user/bob"), Some("user/bob"), "an old id, hashed apart from the scope");
assert_eq!(legacy_user("api/channel/"), Some("channel/"), "hashed as it was, never validated as scoped");
assert_eq!(legacy_user("api/ "), None, "an id the old rule refused");
assert_eq!(legacy_user("api/team/42"), Some("team/42"));
assert_eq!(owner_named_user("alice"), "api/alice", "what the key holder names");
assert_eq!(owner_named_user("channel/shop:42"), "channel/shop:42");
assert_eq!(owner_named_user("team/42"), "api/team/42");
assert_eq!(run_user_id("api/user/bob"), "user/bob", "the id the run named");
assert_eq!(run_user_id("shop:42"), "shop:42");
for source in UserSource::ALL {
assert_eq!(UserSource::parse(source.as_str()), Some(source));
match source {
UserSource::Verified | UserSource::Api | UserSource::Channel => {}
}
}
assert_eq!(UserSource::of_caller(true), UserSource::Verified);
assert_eq!(UserSource::of_caller(false), UserSource::Api);
assert_eq!(UserSource::parse("User"), None);
}
#[test]
fn the_same_id_of_two_sources_is_two_scopes() {
let ids: std::collections::HashSet<String> =
UserSource::ALL.into_iter().map(|source| source.scoped("42")).collect();
assert_eq!(ids.len(), 3);
assert!(!ids.contains("42"));
}
#[test]
fn the_length_rule_holds_for_the_id_after_the_source() {
let longest = "x".repeat(256);
assert!(check_user(&UserSource::Channel.scoped(&longest)).is_ok());
assert!(check_user(&UserSource::Channel.scoped(&format!("{longest}x"))).is_err());
assert!(check_user(&longest).is_ok());
assert!(check_user("api/ ").is_err(), "an empty id after the source");
assert!(check_user("api/a b").is_ok());
assert!(check_user("api/a\u{7}b").is_err());
}
#[test]
fn the_stemmer_joins_forms_of_a_word_and_leaves_others_alone() {
for (a, b) in [
("invoices", "invoice"),
("monthly", "month"),
("orders", "ordered"),
("boxes", "box"),
("cities", "city"),
("pesanannya", "pesanan"),
("kirimkan", "kirim"),
] {
assert_eq!(stem(a), stem(b), "{a} {b}");
}
for word in ["class", "bus", "this", "pdf", "日本"] {
assert_eq!(stem(word), word, "{word}");
}
}
#[test]
fn tokens_split_words_and_cjk() {
assert_eq!(tokens("Hello, World 42"), ["hello", "world", "42"]);
assert_eq!(tokens("東京へ行く"), ["東", "京", "へ", "行", "く"]);
}
}