Skip to content

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

chore(modules): remove unused ops module

Steven Enamakel5ae442d5a45a
diff --git a/crates/openhuman-core/src/modules/ops.rs b/crates/openhuman-core/src/modules/ops.rs
index 2e448c3900..6185b98d65 100644
--- a/crates/openhuman-core/src/modules/ops.rs
+++ b/crates/openhuman-core/src/modules/ops.rs
@@ -91,114 +91,6 @@ pub(crate) fn resolve_bundled_dir(
found
}
-/// Why a bounded [`ensure_loaded_within`] did not end with the module serving.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum LoadError {
- /// Terminal for the process. Carries a message suitable for a user or a
- /// model: no artifact for this host, downloads disabled, a refused
- /// artifact, or a previous failure in this process.
- Failed(String),
- /// The module is still being downloaded, verified, or initialised, and the
- /// caller's bound passed first. Asking again later can succeed.
- StillLoading,
- /// The module's `[components]` switch is off. Nothing was downloaded,
- /// mapped or registered. Carries the component name.
- Disabled(&'static str),
-}
-
-impl LoadError {
- /// The message for a caller that cannot distinguish the two cases.
- #[must_use]
- pub fn into_message(self) -> String {
- match self {
- Self::Failed(message) => message,
- Self::StillLoading => "the module is still loading; try again shortly".to_string(),
- Self::Disabled(component) => {
- format!("COMPONENT_DISABLED:{component}")
- }
- }
- }
-}
-
-/// Ensure `id` is loaded and serving, loading it if this is the first ask.
-///
-/// Waits without bound. Prefer [`ensure_loaded_within`] from any path that has
-/// a deadline of its own.
-///
-/// # Errors
-///
-/// Returns a message suitable for surfacing to a user or a model when the module
-/// cannot be loaded: no artifact for this host, downloads disabled, a refused
-/// artifact, or a previous failure in this process.
-pub async fn ensure_loaded(config: &Config, id: &str) -> Result<(), String> {
- ensure_loaded_within(config, id, None)
- .await
- .map_err(LoadError::into_message)
-}
-
-/// [`ensure_loaded`] with a bound on how long this caller waits.
-///
-/// The bound is on the *wait*, never on the resolution: a caller that gives up
-/// leaves the download running and the slot intact, and a later call finds the
-/// outcome. `None` waits without bound.
-///
-/// # Errors
-///
-/// [`LoadError::Failed`] when the module cannot be loaded in this process;
-/// [`LoadError::StillLoading`] when `within` passed first.
-pub async fn ensure_loaded_within(
- config: &Config,
- id: &str,
- within: Option<Duration>,
-) -> Result<(), LoadError> {
- if !config.modules.enabled {
- if let Some(record) = registry::find(id) {
- super::failure::report(record, super::failure::Reason::Disabled);
- }
- return Err(LoadError::Failed(format!(
- "module '{id}' is unavailable: modules are disabled in configuration"
- )));
- }
- let record =
- registry::find(id).ok_or_else(|| LoadError::Failed(format!("unknown module '{id}'")))?;
- if let Some(component) = disabled_component(config, id) {
- log::debug!("[modules] '{id}' refused: component '{component}' is disabled");
- return Err(LoadError::Disabled(component));
- }
-
- let receiver = match resolution::global().claim(id) {
- Claim::Done(Resolution::Ready) => return Ok(()),
- Claim::Done(Resolution::Failed(reason)) => {
- // The original resolution may have completed before a Sentry
- // client was bound. Revisit reporting at the actual cached caller
- // boundary; the report key suppresses duplicates once captured.
- report_resolution_failure(id, &reason);
- return Err(LoadError::Failed(reason));
- }
- Claim::Wait(receiver) => receiver,
- Claim::Run { sender, receiver } => {
- start_resolution(config.clone(), record, sender).await;
- receiver
- }
- };
- match resolution::global().wait(id, receiver, within).await {
- Waited::Ready => Ok(()),
- Waited::Failed(reason) => {
- report_resolution_failure(id, &reason);
- Err(LoadError::Failed(reason))
- }
- Waited::StillLoading => Err(LoadError::StillLoading),
- }
-}
-
-/// The disabled `[components]` switch that owns module `id`, if any.
-#[must_use]
-pub fn disabled_component(config: &Config, id: &str) -> Option<&'static str> {
- let component = registry::component_for(id)?;
- let set = crate::core::runtime::ComponentSet::from_config(&config.components);
- (!set.enabled(component)).then_some(component)
-}
-
/// Library file stems of every module whose component is off, for skipping
/// their search-path artifacts. Both `name` and `libname` spellings.
#[must_use]
@@ -213,109 +105,89 @@ pub fn disabled_lib_stems(config: &Config) -> Vec<String> {
.collect()
}
-/// The state of `id` as the resolution table reports it, without touching it.
+/// The disabled `[components]` switch that owns module `id`, if any.
#[must_use]
-pub fn state_of(id: &str) -> ModuleState {
- match resolution::global().peek(id) {
- ResolutionState::Unresolved => ModuleState::Available,
- ResolutionState::Loading => ModuleState::Loading,
- ResolutionState::Ready => ModuleState::Ready,
- ResolutionState::Failed(_) => ModuleState::Failed,
- }
+pub fn disabled_component(config: &Config, id: &str) -> Option<&'static str> {
+ let component = registry::component_for(id)?;
+ let set = crate::core::runtime::ComponentSet::from_config(&config.components);
+ (!set.enabled(component)).then_some(component)
}
-/// Run the resolution for `record` and record its outcome.
+/// A resolver over the compiled registry, configured from `config`.
///
-/// Spawned on the module runtime, which lives for the process: a caller
-/// runtime that shuts down mid-load — a test's, an embedder's — must not
-/// cancel a resolution other callers are waiting on. Without a module runtime
-/// there is nothing to load into, so the outcome is recorded inline instead.
-async fn start_resolution(
- config: Config,
- record: &'static ModuleRecord,
- sender: tokio::sync::watch::Sender<Option<Resolution>>,
-) {
- let id = record.id;
- let work = async move {
- log::info!("[modules] resolving '{id}' {}", record.version);
- let resolution = match resolve(&config, record).await {
- Ok(()) => {
- log::info!("[modules] '{id}' is serving");
- Resolution::Ready
+/// Cheap to build and to drop: the records are compiled constants, and the
+/// resolution table, the runtime and the reporter are process-wide. Building
+/// one starts nothing.
+#[must_use]
+pub fn resolver(config: &Config) -> Resolver {
+ let shared = Arc::new(config.clone());
+ let mut sources = std::collections::HashMap::new();
+ let mut linked_factories = std::collections::HashMap::new();
+ for record in registry::ALL {
+ let plan = source::plan(config, record.id);
+ log_plan_once(record, &plan);
+ match plan.served {
+ ModuleSource::LocalFile | ModuleSource::Source => {
+ if let Some(path) = plan.artifact {
+ sources.insert(
+ record.id.to_string(),
+ ResolverSource::LocalFile {
+ path: path.to_string_lossy().into_owned(),
+ },
+ );
+ }
}
- Err(reason) => {
- // Every resolution failure is terminal for the process (the
- // outcome is cached), whichever path produced it; marking here
- // makes later re-reports classify as `ModuleUnavailable`.
- let reason = mark_terminal(reason);
- report_resolution_failure(id, &reason);
- Resolution::Failed(reason)
+ ModuleSource::Linked => {
+ sources.insert(record.id.to_string(), ResolverSource::Linked);
+ if let Some(factory) = linked::factory_for(record.id) {
+ linked_factories.insert(record.id.to_string(), factory);
+ }
}
- };
- // The connector module's curated catalogs are cached in the host; a
- // module that has just been (re)resolved may serve other tables, so
- // drop the snapshot before any waiting caller is released. The next
- // connector call (or the boot warm-up) reads it again.
- if id == super::connectors::MODULE_ID {
- crate::integrations::composio::contract::curated::invalidate();
- }
- resolution::global().complete(id, resolution, sender);
- };
- match host::runtime().await {
- Ok(runtime) => {
- runtime.spawn(work);
- }
- Err(error) => {
- log::warn!("[modules] the module bus could not start: {error}");
- work.await;
+ ModuleSource::Release => {}
}
}
+ let gate_config = Arc::clone(&shared);
+ Resolver::new(ResolverInputs {
+ enabled: config.modules.enabled,
+ install_dir: install_dir(config),
+ allow_download: config.modules.allow_download,
+ bundled_dir: bundled_releases_dir(),
+ sources,
+ linked: linked_factories,
+ search_skip: disabled_lib_stems(config),
+ gate: Some(Arc::new(move |id| disabled_component(&gate_config, id))),
+ on_resolved: Some(Arc::new(on_resolved)),
+ records: registry::release_records(),
+ terminal_marker: tinytools::status::MODULE_FAULT_MARKER.to_string(),
+ runtime: Arc::new(|| Box::pin(runtime::runtime())),
+ module_config: Arc::new(move |id| module_config(&shared, id)),
+ reporter: report::reporter(),
+ })
}
-/// Report a module that did not load — once per process.
-///
-/// A resolution runs once and its failure is cached for every later caller
-/// (see the module docs), so this is the single Sentry event a broken install
-/// produces. The failed resolution itself reports here, and cached callers
-/// revisit this function in case the original resolution happened before a
-/// Sentry client was bound. Its stable report key suppresses repeats. The
-/// report goes through [`report_error`] directly so the observability
-/// classifier cannot swallow the original terminal event.
+/// A `tinybus::module::ModuleClient` that loads modules lazily through
+/// [`resolver`].
///
-/// [`report_error`]: crate::core::observability::report_error
-pub(super) fn report_resolution_failure(id: &str, reason: &str) {
- // Loader errors can include download URLs or user paths. Keep their detail
- // in the operation's returned error, never in the terminal Sentry report.
- let _ = reason;
- if let Some(record) = registry::find(id) {
- super::failure::report(record, super::failure::Reason::ResolutionFailed);
- }
+/// Constructing a client starts nothing. It needs neither a signed-in session
+/// nor a core runtime. Set the bundled releases directory through the module
+/// facade before the first call when artifacts ship with the host.
+#[must_use]
+pub fn client(config: Config) -> ModuleClient {
+ ModuleClient::new(resolver(&config))
}
-/// Do the actual work of getting `record` serving.
-async fn resolve(config: &Config, record: &'static ModuleRecord) -> Result<(), String> {
- let runtime = host::runtime().await.map_err(|_| {
- format!(
- "module '{}' is unavailable: the module bus could not start",
- record.id
- )
- })?;
-
- // Already serving — a module loaded from the search path at boot, or by an
- // earlier explicit `modules.load_local`.
- if runtime
- .host()
- .list()
- .iter()
- .any(|info| info.manifest.bus_name.as_str() == record.bus_name)
- {
- return Ok(());
+/// Log which source serves each module and warn about a local build whose
+/// gitlink is ahead of its released pin, once per id per process.
+fn log_plan_once(record: &ModuleRecord, plan: &source::SourcePlan) {
+ static LOGGED: OnceLock<Mutex<std::collections::HashSet<&'static str>>> = OnceLock::new();
+ let first = LOGGED
+ .get_or_init(Default::default)
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .insert(record.id);
+ if !first {
+ return;
}
-
- // The configured source decides first: a developer's own build is checked
- // before the pinned release so a module can be iterated on against a live
- // core. `release` (the default) falls straight through to the chain below.
- let plan = source::plan(config, record.id);
if let Some(reason) = plan.fallback {
log::warn!(
"[modules] id={} requested={} served=release: {reason}",
@@ -329,7 +201,6 @@ async fn resolve(config: &Config, record: &'static ModuleRecord) -> Result<(), S
plan.requested.as_str(),
plan.served
);
- // `resolve` runs once per id per process, so this is one line per id.
if let Some(line) = source::pin_ahead_warning(
record.id,
plan.served,
@@ -338,189 +209,72 @@ async fn resolve(config: &Config, record: &'static ModuleRecord) -> Result<(), S
) {
log::warn!("{line}");
}
- match plan.served {
- ModuleSource::LocalFile | ModuleSource::Source => {
- if let Some(path) = plan.artifact {
- let module_config = module_config(config, record.id);
- return blocking(move || load_local(runtime, &path, record.id, module_config))
- .await;
- }
- }
- ModuleSource::Linked => {
- let module_config = module_config(config, record.id);
- return blocking(move || load_linked(runtime, record.id, module_config)).await;
- }
- ModuleSource::Release => {}
- }
+}
- // The search path tinybus itself honours, including OPENHUMAN_MODULE_PATH.
- // A refused search-path artifact is ordinary — most directories hold
- // nothing, and tinybus reports each refusal with a sanitised reason — so the
- // errors are dropped here and only a match on the bus name counts.
- let bus_name = record.bus_name;
- let skip = disabled_lib_stems(config);
- let found_on_search_path = tokio::task::spawn_blocking(move || {
- super::search_path::load_enabled(runtime.host(), &skip)
- .into_iter()
- .flatten()
- .any(|info| info.manifest.bus_name.as_str() == bus_name)
- })
- .await
- .unwrap_or(false);
- if found_on_search_path {
- return Ok(());
+/// The connector module's curated catalogs are cached in the host; a module
+/// that has just been (re)resolved may serve other tables, so drop the snapshot
+/// before any waiting caller is released. The next connector call (or the boot
+/// warm-up) reads it again.
+fn on_resolved(id: &str) {
+ if id == super::connectors::MODULE_ID {
+ crate::integrations::composio::contract::curated::invalidate();
}
+}
- // The release cache: a verified artifact from an earlier launch, or a
- // download into the same place. Off the runtime worker — the cold path
- // fetches over the network, hashes the archive, extracts it and `dlopen`s
- // the result, all synchronously, and left inline it would stall every
- // other task sharing this worker for the length of a download on
- // whatever link the user has.
- let Some(root) = install_dir(config) else {
- return Err(format!(
- "module '{}' is unavailable: no directory is available to install modules into",
- record.id
- ));
- };
- let allow_download = config.modules.allow_download;
- let module_config = module_config(config, record.id);
- let cache_root = root.clone();
- let bundled = bundled_releases_dir();
- let outcome = blocking(move || {
- load_cached(
- runtime,
- record,
- &cache_root,
- module_config,
- allow_download,
- bundled.as_deref(),
- )
- })
- .await;
- match outcome {
- Ok(()) => {
- prune_stale_versions(&root, record.id, record.version);
- Ok(())
- }
- Err(reason) => Err(reason),
+/// The message for a caller that cannot distinguish the cases. A switched-off
+/// component keeps its typed `COMPONENT_DISABLED:<name>` spelling.
+#[must_use]
+pub fn load_error_message(error: LoadError) -> String {
+ match error {
+ LoadError::Disabled(component) => format!("COMPONENT_DISABLED:{component}"),
+ other => other.into_message(),
}
}
-/// Run a blocking module operation on the blocking pool.
+/// Ensure `id` is loaded and serving, loading it if this is the first ask.
///
-/// A panic in the loader is reported rather than propagated: it would otherwise
-/// take down whichever task happened to be awaiting the load.
+/// Waits without bound. Prefer [`ensure_loaded_within`] from any path that has
+/// a deadline of its own.
///
-/// Every loader error is terminal for the process and says so once: tinybus'
-/// release-cache path and [`load_local`] already carry the marker, the rest
-/// get it appended here.
-async fn blocking<F>(work: F) -> Result<(), String>
-where
- F: FnOnce() -> Result<(), String> + Send + 'static,
-{
- host::runtime()
- .await
- .map_err(|error| mark_terminal(format!("the module bus could not start: {error}")))?
- .blocking(work)
+/// # Errors
+///
+/// Returns a message suitable for surfacing to a user or a model when the module
+/// cannot be loaded: no artifact for this host, downloads disabled, a refused
+/// artifact, or a previous failure in this process.
+pub async fn ensure_loaded(config: &Config, id: &str) -> Result<(), String> {
+ ensure_loaded_within(config, id, None)
.await
- .map_err(mark_terminal)
-}
-
-/// Append the terminal-fault sentence to `error` unless it already has it.
-pub(super) fn mark_terminal(error: String) -> String {
- let marker = tinytools::status::MODULE_FAULT_MARKER;
- if error.contains(marker) {
- return error;
- }
- format!("{error}. {marker}; restart the app to try again")
+ .map_err(load_error_message)
}
-/// Load the pinned release for this host through the release cache.
+/// [`ensure_loaded`] with a bound on how long this caller waits.
///
-/// Tries the preferred artifact first and falls through on admission failure —
-/// a host newer than the newest published build runs that build, and one whose
-/// toolchain the newest artifact does not match falls back. Each artifact has
-/// its own directory under the version, so two builds of one release never
-/// share an extraction.
-fn load_cached(
- runtime: &'static host::ModuleRuntime,
- record: &'static ModuleRecord,
- install_root: &Path,
- module_config: serde_json::Value,
- allow_download: bool,
- bundled_root: Option<&Path>,
-) -> Result<(), String> {
- let assets: Vec<ReleaseAsset<'static>> = host_candidates()
- .iter()
- .filter_map(|key| record.asset_for(key))
- .map(|asset| ReleaseAsset {
- host_key: asset.host_key,
- archive: asset.archive,
- sha256: asset.sha256,
- })
- .collect();
- let plan = ReleasePlan {
- id: record.id,
- version: record.version,
- release_url: record.release_url,
- assets: &assets,
- install_root,
- bundled_root,
- allow_download,
- };
- load_first_admitted(runtime.host(), &plan, &module_config).map(|_| ())
-}
-
-/// Load a platform library from `path`.
-pub(super) fn load_local(
- runtime: &host::ModuleRuntime,
- path: &Path,
+/// The bound is on the *wait*, never on the resolution: a caller that gives up
+/// leaves the download running and the slot intact, and a later call finds the
+/// outcome. `None` waits without bound.
+///
+/// # Errors
+///
+/// [`LoadError::Failed`] when the module cannot be loaded in this process;
+/// [`LoadError::StillLoading`] when `within` passed first;
+/// [`LoadError::Disabled`] when its `[components]` switch is off.
+pub async fn ensure_loaded_within(
+ config: &Config,
id: &str,
- module_config: serde_json::Value,
-) -> Result<(), String> {
- match runtime.host().load_file_with_config(path, module_config) {
- Ok(_) => {
- log::info!("[modules] loaded '{id}' from a local artifact");
- Ok(())
- }
- Err(err) => Err(format!(
- "module '{id}' could not be loaded from its local artifact: {err}. This is terminal \
- for the running process; restart the app to try again"
- )),
- }
+ within: Option<Duration>,
+) -> Result<(), LoadError> {
+ resolver(config).ensure_loaded_within(id, within).await
}
-/// Attach the module linked into this executable for `id`.
-///
-/// Runs the same descriptor, manifest, dependency and init checks as a
-/// released module, with the same private configuration; the executable's
-/// digest is the attestation. Errors carry static text only.
-pub(super) fn load_linked(
- runtime: &host::ModuleRuntime,
- id: &str,
- module_config: serde_json::Value,
-) -> Result<(), String> {
- let Some(factory) = super::linked::factory_for(id) else {
- return Err(format!(
- "module '{id}' is unavailable: no linked factory is registered in this binary"
- ));
- };
- let module = factory().map_err(|err| {
- log::warn!("[modules] linked factory for '{id}' failed: {err}");
- format!("module '{id}' is unavailable: its linked factory could not be started")
- })?;
- match runtime
- .host()
- .attach_linked_with_config(module, module_config)
- {
- Ok(_) => {
- log::info!("[modules] loaded '{id}' from the linked executable");
- Ok(())
- }
- Err(err) => Err(format!(
- "module '{id}' could not be attached from the linked executable: {err}"
- )),
+/// The state of `id` as the resolution table reports it, without touching it.
+#[must_use]
+pub fn state_of(id: &str) -> ModuleState {
+ match resolver(&Config::default()).state_of(id) {
+ Availability::Available => ModuleState::Available,
+ Availability::Loading => ModuleState::Loading,
+ Availability::Ready => ModuleState::Ready,
+ Availability::Failed => ModuleState::Failed,
+ Availability::Unsupported => ModuleState::Unsupported,
}
}