Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(threads): add transcript key to thread store backend

Steven Enamakel5c3e7856421f
diff --git a/crates/openhuman-core/src/threads/store/backend.rs b/crates/openhuman-core/src/threads/store/backend.rs
index b8da07dcbc..065f6d3eba 100644
--- a/crates/openhuman-core/src/threads/store/backend.rs
+++ b/crates/openhuman-core/src/threads/store/backend.rs
@@ -94,8 +94,8 @@ fn describe(error: &ConversationError, subject: Subject<'_>) -> String {
/// A conversation store bound to one workspace's storage backend.
#[derive(Clone)]
pub struct ConversationStore {
- ctx: DispatchCtx,
- workspace_dir: PathBuf,
+ pub(super) ctx: DispatchCtx,
+ pub(super) workspace_dir: PathBuf,
}
impl ConversationStore {
@@ -105,6 +105,10 @@ impl ConversationStore {
Self { ctx, workspace_dir }
}
+ pub(super) fn conversation_scope(&self) -> Result<Scope, String> {
+ conversation_scope(&self.ctx)
+ }
+
/// The driver store for this call, its schema declared once per backend
/// and scope, and the legacy JSONL conversations imported once.
fn open(&self) -> Result<DriverConversationStore, String> {
@@ -286,16 +290,20 @@ impl ConversationStore {
/// Soft-deletes a thread; whether it existed.
pub fn delete_thread(&self, thread_id: &str, deleted_at: &str) -> Result<bool, String> {
let (id, at) = (thread_id.to_string(), deleted_at.to_string());
- self.run("delete_thread", thread(thread_id), |s| async move {
+ let deleted = self.run("delete_thread", thread(thread_id), |s| async move {
s.delete_thread(&id, &at).await
- })
+ })?;
+ self.forget_transcript_key(thread_id);
+ Ok(deleted)
}
/// Removes every thread.
pub fn purge_threads(&self) -> Result<ConversationPurgeStats, String> {
- self.run("purge_threads", NONE, |s| async move {
+ let stats = self.run("purge_threads", NONE, |s| async move {
s.purge_threads().await.map(ConversationPurgeStats::from)
- })
+ })?;
+ self.forget_all_transcript_keys();
+ Ok(stats)
}
}
diff --git a/crates/openhuman-core/src/threads/store/mod.rs b/crates/openhuman-core/src/threads/store/mod.rs
index 3fd99689dd..14256ef165 100644
--- a/crates/openhuman-core/src/threads/store/mod.rs
+++ b/crates/openhuman-core/src/threads/store/mod.rs
@@ -33,6 +33,7 @@ pub mod blocking;
mod bus;
mod legacy_import;
+mod transcript_key;
#[cfg(test)]
#[path = "legacy_import_tests.rs"]
mod legacy_import_tests;
diff --git a/crates/openhuman-core/src/threads/store/transcript_key.rs b/crates/openhuman-core/src/threads/store/transcript_key.rs
new file mode 100644
index 0000000000..535ce632c1
--- /dev/null
+++ b/crates/openhuman-core/src/threads/store/transcript_key.rs
@@ -0,0 +1,116 @@
+//! The session-store key a thread's transcripts were written under.
+//!
+//! A thread's transcripts live in the session store of the agent key the
+//! session host wrote them under (`agent::session_store::agent_key_for`:
+//! `<profile>~<agent>` for a SaaS profile, else the agent, else the chat
+//! agent). That key follows `[agent] chat_agent_id`, so after an operator
+//! changes the chat agent, a reader that re-derives the key from the current
+//! config looks in a different store and loses the thread's earlier turns.
+//!
+//! The key is therefore recorded with the thread the first time a session is
+//! bound to it (first writer wins), and readers, edit and regenerate use the
+//! recorded key. A thread with no record falls back to the current rule.
+
+use anyhow::Result;
+use serde_json::{json, Value};
+use tinystoragedrivers::{CollectionSpec, ErrorKind, Filter, Precondition};
+
+use super::backend::ConversationStore;
+use crate::storage::documents::Repo;
+use crate::storage::{self};
+
+const DOMAIN: &str = "threads::transcript_key";
+const COLLECTION: &str = "threads_transcript_keys";
+const LOG_PREFIX: &str = "[conversations:transcript-key]";
+
+fn collections() -> Vec<CollectionSpec> {
+ vec![CollectionSpec::new(COLLECTION)]
+}
+
+impl ConversationStore {
+ fn key_repo(&self) -> Result<Repo, String> {
+ let scope = self.conversation_scope()?;
+ let backend = storage::local::backend_for(&self.workspace_dir)
+ .map_err(|e| format!("{LOG_PREFIX} open the storage backend: {e:#}"))?;
+ Repo::on(&backend, &scope, DOMAIN, collections).map_err(|e| format!("{LOG_PREFIX} {e:#}"))
+ }
+
+ /// The key `thread_id`'s transcripts were first written under, if recorded.
+ pub fn transcript_key(&self, thread_id: &str) -> Result<Option<String>, String> {
+ let repo = self.key_repo()?;
+ let id = thread_id.to_string();
+ let doc = repo
+ .run(|docs| async move { docs.get(COLLECTION, &id).await })
+ .map_err(|e| format!("{LOG_PREFIX} read: {e:#}"))?;
+ Ok(doc.and_then(|d| crate::storage::documents::text(&d.doc, "key").map(str::to_string)))
+ }
+
+ /// Records `key` as the thread's transcript key unless one is already
+ /// recorded, and returns the key in effect (the first one recorded).
+ pub fn record_transcript_key(&self, thread_id: &str, key: &str) -> Result<String, String> {
+ let repo = self.key_repo()?;
+ let (id, wanted) = (thread_id.to_string(), key.to_string());
+ let recorded = repo
+ .run(|docs| async move {
+ let body: Value = json!({ "key": wanted });
+ match docs
+ .put(COLLECTION, &id, body, Precondition::Absent)
+ .await
+ {
+ Ok(_) => Ok(None),
+ Err(error) if error.kind() == ErrorKind::Conflict => {
+ let stored = docs.get(COLLECTION, &id).await?;
+ Ok(stored.and_then(|d| {
+ crate::storage::documents::text(&d.doc, "key").map(str::to_string)
+ }))
+ }
+ Err(error) => Err(error),
+ }
+ })
+ .map_err(|e| format!("{LOG_PREFIX} record: {e:#}"))?;
+ match recorded {
+ Some(existing) => {
+ log::debug!("{LOG_PREFIX} kept the recorded key for a thread");
+ Ok(existing)
+ }
+ None => {
+ log::debug!("{LOG_PREFIX} recorded the key for a thread");
+ Ok(key.to_string())
+ }
+ }
+ }
+
+ /// Forgets `thread_id`'s recorded key (the thread was deleted).
+ pub(super) fn forget_transcript_key(&self, thread_id: &str) {
+ let outcome = self.key_repo().and_then(|repo| {
+ let id = thread_id.to_string();
+ repo.run(|docs| async move {
+ docs.delete(COLLECTION, &id, Precondition::Any).await
+ })
+ .map(|_| ())
+ .map_err(|e| format!("{e:#}"))
+ });
+ if let Err(error) = outcome {
+ log::warn!("{LOG_PREFIX} forget failed: {error}");
+ }
+ }
+
+ /// Forgets every recorded key (all threads were purged).
+ pub(super) fn forget_all_transcript_keys(&self) {
+ let outcome = self.key_repo().and_then(|repo| {
+ repo.run(|docs| async move {
+ docs.delete_where(COLLECTION, &Filter::exists("key", true))
+ .await
+ })
+ .map(|_| ())
+ .map_err(|e| format!("{e:#}"))
+ });
+ if let Err(error) = outcome {
+ log::warn!("{LOG_PREFIX} forget-all failed: {error}");
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "transcript_key_tests.rs"]
+mod tests;