Skip to content

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

refactor(memory): replace Error::invalid with Error::InvalidRequest

Steven Enamakel14387d0809d6
diff --git a/crates/openhuman-core/src/flows/memory_tools.rs b/crates/openhuman-core/src/flows/memory_tools.rs
index 7a0f8dc593..7f3ce2efc4 100644
--- a/crates/openhuman-core/src/flows/memory_tools.rs
+++ b/crates/openhuman-core/src/flows/memory_tools.rs
@@ -135,9 +135,9 @@ pub fn flow_meta(flow_id: &str, extra: &[String]) -> MemoryMeta {
/// off forgets nothing.
pub async fn forget_matching(config: &Config, filter: MetaFilter) -> Result<usize> {
if filter.is_empty() {
- return Err(Error::invalid(
+ return Err(Error::InvalidRequest((
"refusing to forget with an empty filter",
- ));
+ ).into()));
}
let bound = match crate::memory::engine::resolve(config).engine() {
Ok(bound) => bound,
diff --git a/crates/openhuman-core/src/memory/backfill.rs b/crates/openhuman-core/src/memory/backfill.rs
index 0bc530184f..d3800f09e1 100644
--- a/crates/openhuman-core/src/memory/backfill.rs
+++ b/crates/openhuman-core/src/memory/backfill.rs
@@ -216,9 +216,9 @@ pub async fn start(
params: BackfillStartParams,
) -> Result<BackfillView> {
if !params.consent {
- return Err(Error::invalid(
+ return Err(Error::InvalidRequest((
"storing past chats uploads them to the selected engine; pass consent: true",
- ));
+ ).into()));
}
let bound = engine::resolve(config).engine()?;
let workspace_dir = config.workspace_dir.clone();
diff --git a/crates/openhuman-core/src/memory/brain.rs b/crates/openhuman-core/src/memory/brain.rs
index 60a63d59b9..51beda6fa4 100644
--- a/crates/openhuman-core/src/memory/brain.rs
+++ b/crates/openhuman-core/src/memory/brain.rs
@@ -68,7 +68,7 @@ fn brain(config: &Config, identity: &MemoryIdentity) -> Result<Brain> {
fn parse_source(raw: &str) -> Result<BrainSource> {
raw.parse()
- .map_err(|error: tinymemory_api::Error| Error::invalid(error.to_string()))
+ .map_err(|error: tinymemory_api::Error| Error::InvalidRequest((error.to_string()).into()))
}
/// One brain source and how many documents it holds.
@@ -159,7 +159,7 @@ pub async fn search(
) -> Result<BrainSearchView> {
let query = params.query.trim();
if query.is_empty() {
- return Err(Error::invalid("the query is blank"));
+ return Err(Error::InvalidRequest(("the query is blank").into()));
}
let source = params.source.as_deref().map(parse_source).transpose()?;
let limit = super::types::clamp_limit(params.limit);
@@ -215,7 +215,7 @@ async fn ingest_path(config: &Config, path: &str) -> Result<std::path::PathBuf>
);
policy.validate_path(path.trim()).await.map_err(|error| {
tracing::warn!("[memory:brain] ingest path refused by the security policy");
- Error::invalid(format!("cannot read the file: {error}"))
+ Error::InvalidRequest(format!("cannot read the file: {error}"))
})
}
@@ -232,16 +232,16 @@ pub async fn ingest(
let resolved = ingest_path(config, path).await?;
let path = resolved.as_path();
let size = std::fs::metadata(path)
- .map_err(|error| Error::invalid(format!("cannot read the file: {error}")))?
+ .map_err(|error| Error::InvalidRequest(format!("cannot read the file: {error}")))?
.len();
if size > MAX_INGEST_BYTES {
- return Err(Error::invalid(format!(
+ return Err(Error::InvalidRequest(format!(
"the file is {size} bytes; the limit is {MAX_INGEST_BYTES}"
)));
}
let bytes = tokio::fs::read(path)
.await
- .map_err(|error| Error::invalid(format!("cannot read the file: {error}")))?;
+ .map_err(|error| Error::InvalidRequest(format!("cannot read the file: {error}")))?;
let mut raw = RawDocument::new(bytes);
if let Some(name) = path.file_name().and_then(|name| name.to_str()) {
raw = raw.with_filename(name);
@@ -255,12 +255,12 @@ pub async fn ingest(
meta,
)
.await
- .map_err(|error| Error::invalid(format!("cannot convert the file: {error}")))?
+ .map_err(|error| Error::InvalidRequest(format!("cannot convert the file: {error}")))?
}
(None, Some(text)) => {
tinymemory_tools::BrainDocument::new(source.unwrap_or_else(files_source), text)
}
- _ => return Err(Error::invalid("pass exactly one of `path` or `text`")),
+ _ => return Err(Error::InvalidRequest(("pass exactly one of `path` or `text`").into())),
};
if let Some(title) = params.title.filter(|title| !title.trim().is_empty()) {
document = document.titled(title);
diff --git a/crates/openhuman-core/src/memory/confine.rs b/crates/openhuman-core/src/memory/confine.rs
index d505e22e59..432e68d090 100644
--- a/crates/openhuman-core/src/memory/confine.rs
+++ b/crates/openhuman-core/src/memory/confine.rs
@@ -53,7 +53,7 @@ pub fn confine_reach(reach: Option<Reach>, allowed: &Reach) -> Result<Reach> {
allowed = %allowed.at,
"[memory:confine] refused a reach outside the caller's root"
);
- Err(Error::invalid(format!(
+ Err(Error::InvalidRequest(format!(
"the reach `{}` is outside this caller's memory (`{}`)",
reach.at, allowed.at
)))
@@ -98,7 +98,7 @@ pub fn confine_learn_meta(
allowed = %allowed.at,
"[memory:confine] refused a learning outside the caller's root"
);
- return Err(Error::invalid(format!(
+ return Err(Error::InvalidRequest(format!(
"the namespace `{}` is outside this caller's memory (`{}`)",
meta.namespace, allowed.at
)));
diff --git a/crates/openhuman-core/src/memory/engine.rs b/crates/openhuman-core/src/memory/engine.rs
index baa713d58e..d1d11c02b7 100644
--- a/crates/openhuman-core/src/memory/engine.rs
+++ b/crates/openhuman-core/src/memory/engine.rs
@@ -630,7 +630,7 @@ pub fn read_cortexdb_key(config: &Config) -> anyhow::Result<Option<String>> {
pub fn store_cortexdb_key(config: &Config, key: &str) -> Result<()> {
let key = key.trim();
if key.is_empty() {
- return Err(Error::invalid("the API key is blank"));
+ return Err(Error::InvalidRequest(("the API key is blank").into()));
}
AuthService::from_config(config)
.store_provider_token(
diff --git a/crates/openhuman-core/src/memory/explore.rs b/crates/openhuman-core/src/memory/explore.rs
index caf35eafc0..58af2d00f2 100644
--- a/crates/openhuman-core/src/memory/explore.rs
+++ b/crates/openhuman-core/src/memory/explore.rs
@@ -79,7 +79,7 @@ pub struct ItemsGetView {
/// value the facet cannot take (blank, or an unknown kind).
pub fn narrowed(filter: Option<MetaFilter>, path: &[PathStep]) -> Result<MetaFilter> {
if path.len() > MAX_PATH_STEPS {
- return Err(Error::invalid(format!(
+ return Err(Error::InvalidRequest(format!(
"an explorer path takes at most {MAX_PATH_STEPS} steps"
)));
}
diff --git a/crates/openhuman-core/src/memory/import.rs b/crates/openhuman-core/src/memory/import.rs
index b9c522de03..23269e6fd9 100644
--- a/crates/openhuman-core/src/memory/import.rs
+++ b/crates/openhuman-core/src/memory/import.rs
@@ -105,7 +105,7 @@ pub(crate) fn listed_unconfirmed(workspace_dir: &Path) -> bool {
}
fn import_error(error: &ImportError) -> Error {
- Error::invalid(error.to_string())
+ Error::InvalidRequest((error.to_string()).into())
}
fn importer(
@@ -315,11 +315,11 @@ async fn launch(
// Items written to the legacy tree while it is being moved would be
// left behind there.
if super::layout_migration::service::is_running(config) {
- return Err(Error::invalid(if mode == Mode::Import {
+ return Err(Error::InvalidRequest((if mode == Mode::Import {
"memory is being organized; import once that finishes"
} else {
"memory is being organized; retry once that finishes"
- }));
+ }).into()));
}
RUNNING
.lock()
diff --git a/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs b/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs
index 0227663db7..b8776c1529 100644
--- a/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs
@@ -178,7 +178,7 @@ fn errors_keep_their_wire_codes_across_the_module_boundary() {
for error in [
Error::Off("x".into()),
Error::Unsupported("x".into()),
- Error::invalid("x"),
+ Error::InvalidRequest(("x").into()),
Error::Unauthorized("x".into()),
Error::Unavailable("x".into()),
Error::InsufficientCredits("[USER_INSUFFICIENT_CREDITS] x".into()),
diff --git a/crates/openhuman-core/src/memory/lifecycle/jobs.rs b/crates/openhuman-core/src/memory/lifecycle/jobs.rs
index e4c6cf4b34..19c227125a 100644
--- a/crates/openhuman-core/src/memory/lifecycle/jobs.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/jobs.rs
@@ -121,7 +121,7 @@ pub async fn run(config: &Config, selection: Selection) -> Result<Vec<JobRun>> {
)
.await
.map_err(|error| match error {
- QueueError::NoSuchJob(_) => Error::invalid(error.to_string()),
+ QueueError::NoSuchJob(_) => Error::InvalidRequest((error.to_string()).into()),
})
}
diff --git a/crates/openhuman-core/src/memory/lifecycle/mod.rs b/crates/openhuman-core/src/memory/lifecycle/mod.rs
index bc0403c0ef..dd999cd223 100644
--- a/crates/openhuman-core/src/memory/lifecycle/mod.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/mod.rs
@@ -103,7 +103,7 @@ pub fn named_agent_memory(
}
let memory = agent_memory(config, &identity).map_err(|error| match error {
Error::InvalidRequest(message) => {
- Error::invalid(format!("agent `{}`: {message}", identity.agent_id))
+ Error::InvalidRequest(format!("agent `{}`: {message}", identity.agent_id))
}
other => other,
})?;
diff --git a/crates/openhuman-core/src/memory/lifecycle/views.rs b/crates/openhuman-core/src/memory/lifecycle/views.rs
index f1fab9c738..896c5c07c1 100644
--- a/crates/openhuman-core/src/memory/lifecycle/views.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/views.rs
@@ -91,7 +91,7 @@ fn within<T: PartialOrd + std::fmt::Display + Copy>(
max: T,
) -> Result<Option<T>> {
match value {
- Some(value) if value < min || value > max => Err(Error::invalid(format!(
+ Some(value) if value < min || value > max => Err(Error::InvalidRequest(format!(
"{name} must be between {min} and {max}"
))),
other => Ok(other),
@@ -168,9 +168,9 @@ fn validate_build_delay_secs(value: Option<u64>) -> Result<Option<u64>> {
.and_then(|delay| chrono::Utc::now().checked_sub_signed(delay))
.is_none()
{
- return Err(Error::invalid(
+ return Err(Error::InvalidRequest((
"build_delay_secs must fit within the supported date range",
- ));
+ ).into()));
}
Ok(Some(seconds))
}
diff --git a/crates/openhuman-core/src/memory/ops.rs b/crates/openhuman-core/src/memory/ops.rs
index f9db884602..3db341baeb 100644
--- a/crates/openhuman-core/src/memory/ops.rs
+++ b/crates/openhuman-core/src/memory/ops.rs
@@ -92,9 +92,9 @@ pub fn apply_engine_set(config: &mut Config, params: &EngineSetParams) -> Result
// Turning memory off keeps every engine's endpoint and key, so
// switching back needs no re-entry.
if params.endpoint.is_some() || params.api_key.is_some() {
- return Err(Error::invalid(
+ return Err(Error::InvalidRequest((
"disabling memory takes no endpoint or API key",
- ));
+ ).into()));
}
config.memory.engine = DISABLED_ENGINE.to_string();
tracing::info!("[memory:ops] memory disabled");
@@ -104,7 +104,7 @@ pub fn apply_engine_set(config: &mut Config, params: &EngineSetParams) -> Result
.iter()
.any(|descriptor| descriptor.id == engine_id)
{
- return Err(Error::invalid(format!(
+ return Err(Error::InvalidRequest(format!(
"unknown memory engine `{engine_id}`"
)));
}
@@ -129,11 +129,11 @@ pub fn apply_engine_set(config: &mut Config, params: &EngineSetParams) -> Result
}
CORTEXDB_ENGINE => engine::store_cortexdb_key(config, key)?,
TINYHUMANS_ENGINE => {
- return Err(Error::invalid(
+ return Err(Error::InvalidRequest((
"the tinyhumans engine uses your sign-in, not an API key",
- ))
+ ).into()))
}
- _ => return Err(Error::invalid("this engine takes no API key")),
+ _ => return Err(Error::InvalidRequest(("this engine takes no API key").into())),
}
}
config.memory.engine = engine_id.to_string();
@@ -143,11 +143,11 @@ pub fn apply_engine_set(config: &mut Config, params: &EngineSetParams) -> Result
fn validate_endpoint(endpoint: &str) -> Result<()> {
let parsed = url::Url::parse(endpoint)
- .map_err(|_| Error::invalid("the endpoint is not a valid URL"))?;
+ .map_err(|_| Error::InvalidRequest(("the endpoint is not a valid URL").into()))?;
if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
- return Err(Error::invalid(
+ return Err(Error::InvalidRequest((
"the endpoint must be an http(s) URL with a host",
- ));
+ ).into()));
}
Ok(())
}
@@ -260,7 +260,7 @@ pub fn learning_item(
) -> Result<StoreItem> {
let confidence = params.confidence.unwrap_or(DEFAULT_LEARNING_CONFIDENCE);
if !(0.0..=1.0).contains(&confidence) {
- return Err(Error::invalid("confidence must be between 0 and 1"));
+ return Err(Error::InvalidRequest(("confidence must be between 0 and 1").into()));
}
let mut meta = params.meta.unwrap_or_default();
if let Some(host) = host_meta {
@@ -376,7 +376,7 @@ pub async fn forget(config: &Config, params: ForgetParams) -> Result<ForgetView>
.map(ItemId)
.collect();
if ids.is_empty() {
- return Err(Error::invalid("forget needs at least one id"));
+ return Err(Error::InvalidRequest(("forget needs at least one id").into()));
}
let bound = bound(config)?;
// A SaaS user forgets only what lies in their own tree.
@@ -421,9 +421,9 @@ pub async fn erase_all(
params: EraseAllParams,
) -> Result<EraseAllView> {
if !params.confirm {
- return Err(Error::invalid(
+ return Err(Error::InvalidRequest((
"erasing all memory needs confirm: true; nothing erased comes back",
- ));
+ ).into()));
}
let bound = bound(config)?;
// Earlier durable tool writes must finish or be discarded before the
diff --git a/crates/openhuman-core/src/memory/schemas/handlers.rs b/crates/openhuman-core/src/memory/schemas/handlers.rs
index fe61d70f8e..775ab4adb0 100644
--- a/crates/openhuman-core/src/memory/schemas/handlers.rs
+++ b/crates/openhuman-core/src/memory/schemas/handlers.rs
@@ -60,7 +60,7 @@ where
fn parse<T: DeserializeOwned>(params: Map<String, Value>) -> Result<T, String> {
serde_json::from_value(Value::Object(params))
- .map_err(|error| Error::invalid(format!("invalid params: {error}")).into())
+ .map_err(|error| Error::InvalidRequest(format!("invalid params: {error}")).into())
}
fn to_json<T: Serialize>(value: T) -> Result<Value, String> {
diff --git a/crates/openhuman-core/src/memory/sources/mod.rs b/crates/openhuman-core/src/memory/sources/mod.rs
index b44f668846..03f70ac459 100644
--- a/crates/openhuman-core/src/memory/sources/mod.rs
+++ b/crates/openhuman-core/src/memory/sources/mod.rs
@@ -59,7 +59,7 @@ pub fn list(config: &Config) -> Vec<SourceView> {
pub fn normalize_target(kind: MemorySourceKind, target: &str) -> Result<String> {
let target = target.trim();
if target.is_empty() {
- return Err(Error::invalid("target must not be empty"));
+ return Err(Error::InvalidRequest(("target must not be empty").into()));
}
match kind {
MemorySourceKind::Folder | MemorySourceKind::File => Ok(target.to_string()),
@@ -72,9 +72,9 @@ pub fn normalize_target(kind: MemorySourceKind, target: &str) -> Result<String>
(Some(owner), Some(repo), None) if !owner.is_empty() && !repo.is_empty() => {
Ok(format!("https://github.com/{owner}/{repo}"))
}
- _ => Err(Error::invalid(
+ _ => Err(Error::InvalidRequest((
"a GitHub target is `owner/repo` or a repository URL",
- )),
+ ).into())),
}
}
MemorySourceKind::Link | MemorySourceKind::Rss => http_url(target),
@@ -82,9 +82,9 @@ pub fn normalize_target(kind: MemorySourceKind, target: &str) -> Result<String>
}
fn http_url(target: &str) -> Result<String> {
- let url = url::Url::parse(target).map_err(|_| Error::invalid("target is not a URL"))?;
+ let url = url::Url::parse(target).map_err(|_| Error::InvalidRequest(("target is not a URL").into()))?;
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
- return Err(Error::invalid("target must be an http(s) URL"));
+ return Err(Error::InvalidRequest(("target must be an http(s) URL").into()));
}
Ok(url.to_string())
}
@@ -96,7 +96,7 @@ pub fn apply_add(
params: &SourcesAddParams,
) -> Result<MemorySourceConfig> {
let kind = MemorySourceKind::parse(&params.kind).ok_or_else(|| {
- Error::invalid(format!(
+ Error::InvalidRequest(format!(
"unknown source kind `{}` (folder, file, link, github, rss)",
params.kind.trim()
))
@@ -104,7 +104,7 @@ pub fn apply_add(
let target = normalize_target(kind, &params.target)?;
if let Some(mins) = params.schedule_mins {
if mins < MIN_SCHEDULE_MINS {
- return Err(Error::invalid(format!(
+ return Err(Error::InvalidRequest(format!(
"schedule_mins must be at least {MIN_SCHEDULE_MINS}"
)));
}
@@ -115,7 +115,7 @@ pub fn apply_add(
.iter()
.any(|source| source.kind == kind && source.target == target)
{
- return Err(Error::invalid("that source is already added"));
+ return Err(Error::InvalidRequest(("that source is already added").into()));
}
let label = params
.label
@@ -127,7 +127,7 @@ pub fn apply_add(
None | Some("") => None,
Some(raw) => Some(
raw.parse::<tinymemory_api::Namespace>()
- .map_err(|error| Error::invalid(error.to_string()))?
+ .map_err(|error| Error::InvalidRequest((error.to_string()).into()))?
.to_string(),
),
};
diff --git a/crates/openhuman-core/src/memory/sources/sync.rs b/crates/openhuman-core/src/memory/sources/sync.rs
index cbaf144410..062fe61e7f 100644
--- a/crates/openhuman-core/src/memory/sources/sync.rs
+++ b/crates/openhuman-core/src/memory/sources/sync.rs
@@ -45,7 +45,7 @@ fn registered(source: &MemorySourceConfig) -> RegisteredSource {
fn host_error(error: SyncError) -> Error {
match error {
- SyncError::Invalid(message) => Error::invalid(message),
+ SyncError::Invalid(message) => Error::InvalidRequest((message).into()),
SyncError::Read(message) => {
Error::Engine(format!("reading the source failed: {message}"))
}
diff --git a/crates/openhuman-core/src/memory/tool_writes.rs b/crates/openhuman-core/src/memory/tool_writes.rs
index 433725df58..03b1b072e8 100644
--- a/crates/openhuman-core/src/memory/tool_writes.rs
+++ b/crates/openhuman-core/src/memory/tool_writes.rs
@@ -173,16 +173,16 @@ pub(super) fn enqueue(
let operation = match args.get("action").and_then(serde_json::Value::as_str) {
Some("learn") => {
let mut params: LearnParams = serde_json::from_value(args.clone())
- .map_err(|_| Error::invalid("invalid learning arguments"))?;
+ .map_err(|_| Error::InvalidRequest(("invalid learning arguments").into()))?;
params.meta = None;
let mut item = super::ops::learning_item(params, Some(facts.learn_meta()))?;
if let Some(root) = confinement {
super::user_scope::clamp_item(&mut item, &root);
}
if !super::user_scope::within(&item.meta().namespace, &reach.at) || reach.inherit {
- return Err(Error::invalid(
+ return Err(Error::InvalidRequest((
"learning namespace is outside the trusted reach",
- ));
+ ).into()));
}
WriteOperation::Learn {
item: super::guard::scrub(item),
@@ -190,7 +190,7 @@ pub(super) fn enqueue(
}
Some("forget") => {
let params: ForgetParams = serde_json::from_value(args.clone())
- .map_err(|_| Error::invalid("invalid forgetting arguments"))?;
+ .map_err(|_| Error::InvalidRequest(("invalid forgetting arguments").into()))?;
let mut ids: Vec<_> = params
.ids
.into_iter()
@@ -200,11 +200,11 @@ pub(super) fn enqueue(
ids.sort();
ids.dedup();
if ids.is_empty() {
- return Err(Error::invalid("forget needs at least one id"));
+ return Err(Error::InvalidRequest(("forget needs at least one id").into()));
}
WriteOperation::Forget { ids, reach }
}
- _ => return Err(Error::invalid("expected a memory write")),
+ _ => return Err(Error::InvalidRequest(("expected a memory write").into())),
};
let _guard = LOCK
.lock()
diff --git a/crates/openhuman-core/src/memory/user_scope.rs b/crates/openhuman-core/src/memory/user_scope.rs
index 1e384cd164..ef647250f5 100644
--- a/crates/openhuman-core/src/memory/user_scope.rs
+++ b/crates/openhuman-core/src/memory/user_scope.rs
@@ -45,9 +45,9 @@ pub fn confinement_in(saas: bool, config: &Config) -> Result<Option<Namespace>>
root = raw,
"[memory:user_scope] no valid confinement root in SaaS mode"
);
- Err(Error::invalid(
+ Err(Error::InvalidRequest((
"memory is unavailable: this agent has no valid memory root",
- ))
+ ).into()))
}
}
}