Skip to content

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

chore: files changed crates/openhuman-core/src/memory/brain.rs,crates/openhuman-core/src/memory/sour

Steven Enamakel7d462c7c333f
diff --git a/crates/openhuman-core/src/memory/brain.rs b/crates/openhuman-core/src/memory/brain.rs
index fbb99b9735..a92b019ecf 100644
--- a/crates/openhuman-core/src/memory/brain.rs
+++ b/crates/openhuman-core/src/memory/brain.rs
@@ -11,7 +11,7 @@
//! the identity in scope (the default root outside an agent).
use serde::{Deserialize, Serialize};
-use tinymemory_api::{ExploreRequest, Facet, Hit, Namespace, StoreItem, WriteOptions};
+use tinymemory_api::{Error, Hit, Namespace, StoreItem, WriteOptions};
use tinymemory_integrations::documents::RawDocument;
use tinymemory_tools::layout::placement::{brain_node_with, files_source};
use tinymemory_tools::{Brain, BrainSource, MemoryLayout};
@@ -21,21 +21,19 @@ use crate::config::Config;
use super::engine;
use super::lifecycle::jobs;
-use tinymemory_api::{Error, Result};
+use tinymemory_api::Result;
+
+pub use tinymemory_tools::{BrainSourceCount, BrainSourcesView};
/// Largest file `memory_brain_ingest` reads, in bytes.
-pub const MAX_INGEST_BYTES: u64 = 25 * 1024 * 1024;
+pub const MAX_INGEST_BYTES: u64 = tinymemory_integrations::brain::MAX_INGEST_BYTES;
/// The brain source a synced item belongs to: the connector it came from,
/// so removing it erases one source. GitHub to `github`, links and feeds to
/// `web`, and local files, whatever their format, to `files`.
#[must_use]
pub fn brain_source(kind: MemorySourceKind) -> BrainSource {
- match kind {
- MemorySourceKind::Github => BrainSource::Github,
- MemorySourceKind::Link | MemorySourceKind::Rss => BrainSource::Web,
- MemorySourceKind::Folder | MemorySourceKind::File => files_source(),
- }
+ tinymemory_integrations::brain::brain_source(kind.source_kind())
}
/// The node `item` of `source` is filed at: the source's node, or, for
@@ -69,28 +67,12 @@ fn brain(
}
fn parse_source(raw: &str) -> Result<BrainSource> {
- raw.parse()
- .map_err(|error: tinymemory_api::Error| Error::InvalidRequest(error.to_string()))
-}
-
-/// One brain source and how many documents it holds.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
-pub struct BrainSourceCount {
- /// The source id (`pdf`, `notion`, …).
- pub source: String,
- /// Documents stored under it.
- pub documents: u64,
-}
-
-/// `memory_brain_sources` result.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
-pub struct BrainSourcesView {
- /// The layout root the brain lives under.
- pub root: String,
- /// Each source with documents, most first.
- pub sources: Vec<BrainSourceCount>,
- /// Documents outside any source node (stored before the brain layout).
- pub unfiled: u64,
+ tinymemory_integrations::brain::parse_source(raw).map_err(|error| match error {
+ tinymemory_integrations::documents::Error::Invalid(message) => {
+ Error::InvalidRequest(message)
+ }
+ error => Error::InvalidRequest(error.to_string()),
+ })
}
/// `memory_brain_sources`: the brain's sources and their sizes.
@@ -98,42 +80,7 @@ pub async fn sources(
config: &Config,
identity: &tinymemory_tools::layout::identity::Identity,
) -> Result<BrainSourcesView> {
- let bound = engine::resolve(config).engine()?;
- let layout = layout(config, identity);
- let page = bound
- .engine
- .explore(ExploreRequest {
- facet: Facet::Namespace,
- filter: layout.brain_filter(None),
- limit: 200,
- scan_limit: 20_000,
- })
- .await?;
- // A source's collections (`source:github/project:…`) count as the
- // source's own documents.
- let source_of = |node: &str| -> Option<String> {
- let node: Namespace = node.parse().ok()?;
- let segment = node.segments().get(layout.root().depth())?;
- (segment.kind() == tinymemory_api::SegmentKind::Source).then(|| segment.id().to_string())
- };
- let mut counts = std::collections::BTreeMap::<String, u64>::new();
- let mut unfiled = 0;
- for bucket in page.buckets {
- match source_of(&bucket.value) {
- Some(source) => *counts.entry(source).or_default() += bucket.count,
- None => unfiled += bucket.count,
- }
- }
- let mut sources: Vec<BrainSourceCount> = counts
- .into_iter()
- .map(|(source, documents)| BrainSourceCount { source, documents })
- .collect();
- sources.sort_by(|a, b| b.documents.cmp(&a.documents).then(a.source.cmp(&b.source)));
- Ok(BrainSourcesView {
- root: layout.root().to_string(),
- sources,
- unfiled: unfiled + page.missing,
- })
+ brain(config, identity)?.sources().await
}
/// `memory_brain_search` params.
@@ -239,11 +186,14 @@ pub async fn ingest(
let size = std::fs::metadata(path)
.map_err(|error| Error::InvalidRequest(format!("cannot read the file: {error}")))?
.len();
- if size > MAX_INGEST_BYTES {
- return Err(Error::InvalidRequest(format!(
- "the file is {size} bytes; the limit is {MAX_INGEST_BYTES}"
- )));
- }
+ tinymemory_integrations::brain::check_ingest_size(size).map_err(|error| match error {
+ tinymemory_integrations::documents::Error::TooLarge { .. } => {
+ Error::InvalidRequest(format!(
+ "the file is {size} bytes; the limit is {MAX_INGEST_BYTES}"
+ ))
+ }
+ error => Error::InvalidRequest(error.to_string()),
+ })?;
let bytes = tokio::fs::read(path)
.await
.map_err(|error| Error::InvalidRequest(format!("cannot read the file: {error}")))?;
diff --git a/crates/openhuman-core/src/memory/sources/mod.rs b/crates/openhuman-core/src/memory/sources/mod.rs
index 11e4f2043c..34b1675bd0 100644
--- a/crates/openhuman-core/src/memory/sources/mod.rs
+++ b/crates/openhuman-core/src/memory/sources/mod.rs
@@ -148,44 +148,24 @@ pub fn layout_of_source(
config: &Config,
source: &MemorySourceConfig,
) -> tinymemory_tools::MemoryLayout {
- let default = || {
- tinymemory_tools::layout::identity::Identity::root()
- .resolve(&crate::memory::scope::identity_pins(config))
- .layout
- };
- let Some(raw) = source
- .namespace
- .as_deref()
- .filter(|raw| !raw.trim().is_empty())
- else {
- return default();
- };
- raw.parse::<tinymemory_api::Namespace>()
- .map_err(|error| error.to_string())
- .and_then(|root| tinymemory_tools::MemoryLayout::new(root).map_err(|error| error.to_string()))
- .unwrap_or_else(|error| {
- tracing::warn!(id = %source.id, %error, "[memory:sources] invalid root; using the configured one");
- default()
- })
+ tinymemory_integrations::sources::layout_of_source(&configured_layout(config), source)
}
/// The layout the configured source `source_id` files into; the configured
/// root for an unknown id.
#[must_use]
pub fn layout_of(config: &Config, source_id: &str) -> tinymemory_tools::MemoryLayout {
- config
- .memory
- .sources
- .iter()
- .find(|source| source.id == source_id)
- .map_or_else(
- || {
- tinymemory_tools::layout::identity::Identity::root()
- .resolve(&crate::memory::scope::identity_pins(config))
- .layout
- },
- |source| layout_of_source(config, source),
- )
+ tinymemory_integrations::sources::layout_of(
+ &configured_layout(config),
+ &config.memory.sources,
+ source_id,
+ )
+}
+
+fn configured_layout(config: &Config) -> tinymemory_tools::MemoryLayout {
+ tinymemory_tools::layout::identity::Identity::root()
+ .resolve(&crate::memory::scope::identity_pins(config))
+ .layout
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/memory/sources/state.rs b/crates/openhuman-core/src/memory/sources/state.rs
index a5fa55adbd..a26d723645 100644
--- a/crates/openhuman-core/src/memory/sources/state.rs
+++ b/crates/openhuman-core/src/memory/sources/state.rs
@@ -9,31 +9,11 @@ use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};
-use chrono::{DateTime, Utc};
-use serde::{Deserialize, Serialize};
-
-use crate::memory::types::SourceStatus;
+pub use tinymemory_integrations::sources::{SourceState, SourceStatus};
/// Serialises state-file read-modify-writes in this process.
static LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
-/// What the last sync of one source left behind.
-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct SourceState {
- /// When the last sync finished.
- #[serde(default)]
- pub last_sync_at: Option<DateTime<Utc>>,
- /// Current status.
- #[serde(default)]
- pub status: SourceStatus,
- /// Why the last sync failed.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub error: Option<String>,
- /// Items stored by the last successful sync.
- #[serde(default)]
- pub items: u64,
-}
-
fn path(workspace_dir: &Path) -> PathBuf {
workspace_dir.join("memory").join("sources_state.json")
}
@@ -99,14 +79,11 @@ pub fn reset_interrupted(workspace_dir: &Path) {
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let mut all = read_all(workspace_dir);
- let mut changed = false;
- for state in all.values_mut() {
- if state.status == SourceStatus::Syncing {
- state.status = SourceStatus::Idle;
- changed = true;
- }
- }
+ let changed = all
+ .values()
+ .any(|state| state.status == SourceStatus::Syncing);
if changed {
+ tinymemory_integrations::sources::reset_interrupted(&mut all);
write_all(workspace_dir, &all);
}
}
diff --git a/crates/openhuman-core/src/memory/types.rs b/crates/openhuman-core/src/memory/types.rs
index 607f32244a..e01c304bf7 100644
--- a/crates/openhuman-core/src/memory/types.rs
+++ b/crates/openhuman-core/src/memory/types.rs
@@ -11,6 +11,7 @@ use tinymemory_api::{
Citation, EngineDescriptor, FetchMode, Hit, LearningKind, MemoryMeta, MetaFilter,
};
use tinymemory_integrations::import::ImportState;
+pub use tinymemory_integrations::sources::SourceStatus;
use crate::config::schema::MemorySourceKind;
@@ -247,19 +248,6 @@ pub struct ItemsListView {
pub next_cursor: Option<String>,
}
-/// A source's sync status.
-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum SourceStatus {
- /// Not syncing.
- #[default]
- Idle,
- /// A sync is running.
- Syncing,
- /// The last sync failed.
- Error,
-}
-
/// One document source, as the UI sees it.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SourceView {