The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
Merge upstream/main into backend-to-tinyhumans
Steven Enamakel9885b1791f44
diff --cc Cargo.lockindex 0674cbae49,0f386053f1..c8eacffe06--- a/Cargo.lock+++ b/Cargo.lock@@@ -5695,21 -5692,10 +5696,22 @@@ dependencies ="sentry","serde","serde_json",+ "sha2 0.10.9","tempfile","thiserror 2.0.20",++ "tiny-artifacts",+ "tinyagents-harness",+ "tinyagents-live",+ "tinybus","tinychannels-bus","tinyhumans-sdk",+ "tinyinference-core 0.4.1",+ "tinyinference-embeddings",+ "tinyinference-image",+ "tinyinference-llm 0.4.1",+ "tinyinference-providers",+ "tinyinference-video",+ "tinyinference-voice","tinyjevclient","tinytools","tinytools-jev",diff --cc crates/openhuman-app/Cargo.lockindex a0b0a450df,d5c83992a8..56de211968--- a/crates/openhuman-app/Cargo.lock+++ b/crates/openhuman-app/Cargo.lock@@@ -4007,18 -4006,9 +4008,19 @@@ dependencies ="reqwest 0.12.28","serde","serde_json",+ "sha2 0.10.9","thiserror 2.0.20",++ "tiny-artifacts",+ "tinyagents-live","tinychannels-bus","tinyhumans-sdk",+ "tinyinference-core",+ "tinyinference-embeddings",+ "tinyinference-image",+ "tinyinference-llm",+ "tinyinference-providers",+ "tinyinference-video",+ "tinyinference-voice","tinyjevclient","tinytools","tinytools-jev",diff --cc crates/openhuman-core/src/agent/artifacts/mod.rsindex 51b699390a,4da9b385a8..e9d1886fc9--- a/crates/openhuman-core/src/agent/artifacts/mod.rs+++ b/crates/openhuman-core/src/agent/artifacts/mod.rs@@@ -1,6 -1,8 +1,9 @@@pub mod files;pub mod migrate;pub mod ops;+ pub mod preview;+ pub mod production;++pub mod publisher_slot;pub mod schemas;pub mod store;mod store_documents;@@@ -10,6 -13,6 +14,10 @@@ pub mod version_documentspub(crate) use files::resolve_ready_file_meta;pub use files::{resolve_ready_file, FileRoots};pub use migrate::{migrate_legacy_artifacts, MigrationReport};++pub use publisher_slot::{++ artifact_publisher, register_artifact_publisher, register_artifact_publisher_in,++ unregister_artifact_publisher, ArtifactPublisherFactory,++};pub use schemas::{all_controller_schemas as all_artifacts_controller_schemas,all_registered_controllers as all_artifacts_registered_controllers,diff --cc crates/openhuman-core/src/agent/artifacts/ops.rsindex 1df3fffd63,91f9a45b6e..e1ec9edc86--- a/crates/openhuman-core/src/agent/artifacts/ops.rs+++ b/crates/openhuman-core/src/agent/artifacts/ops.rs@@@ -276,3 -276,74 +276,74 @@@ async fn regenerate_presentation#[cfg(test)]#[path = "ops_tests.rs"]mod tests;++ /// Save the user's edit of a versioned artifact as a new operator version+ /// (the preview panel's autosave). See+ /// [`super::tiny_store::save_operator_version`].+ pub async fn ai_save_artifact_version(+ config: &Config,+ artifact_id: &str,+ body: &str,+ ) -> Result<Outcome<Value>, String> {+ let saved = super::tiny_store::save_operator_version(+ &config.workspace_dir,+ super::files::FileRoots::from_config(config),+ artifact_id,+ body,+ )+ .await?;+ log::debug!(+ "[artifacts] ai_save_artifact_version id={artifact_id} version={} saved={}",+ saved.version,+ saved.saved+ );+ Ok(Outcome::new(+ json!({ "artifact_id": artifact_id, "version": saved.version, "saved": saved.saved }),+ vec![],+ ))+ }++ /// Share a version of an artifact through cloud file storage (the preview+ /// panel's Share button): uploads it and returns its link, which is also+ /// recorded on the version. A version that already has a live link of the same+ /// kind returns it without uploading again.+ pub async fn ai_share_artifact(+ config: &Config,+ artifact_id: &str,+ version: Option<u32>,+ public: bool,+ ) -> Result<Outcome<Value>, String> {- let publisher = crate::integrations::file_storage::artifact_publisher(config)++ let publisher = super::artifact_publisher(config)+ .ok_or_else(|| "sign in to share artifacts".to_string())?;+ let artifacts = super::tiny_store::artifacts_service(+ &config.workspace_dir,+ super::files::FileRoots::from_config(config),+ None,+ None,+ )+ .with_publisher(publisher);+ let options = tiny_artifacts::PublishOptions {+ public,+ ..tiny_artifacts::PublishOptions::default()+ };+ let shared = artifacts+ .publish(artifact_id, version, &options)+ .await+ .map_err(|e| e.to_string())?;+ log::debug!(+ "[artifacts] ai_share_artifact id={artifact_id} version={} public={public} reused={}",+ shared.version,+ shared.reused+ );+ Ok(Outcome::new(+ json!({+ "artifact_id": artifact_id,+ "version": shared.version,+ "url": shared.link.url,+ "public": shared.link.public,+ "expires_at_millis": shared.link.expires_at_millis,+ "reused": shared.reused,+ }),+ vec![],+ ))+ }diff --cc crates/openhuman-core/src/agent/artifacts/publisher_slot.rsindex 0000000000,0000000000..0593afb005new file mode 100644--- /dev/null+++ b/crates/openhuman-core/src/agent/artifacts/publisher_slot.rs@@@ -1,0 -1,0 +1,61 @@@++//! The artifact publisher slot: where an outside crate plugs in the service++//! that shares an artifact version and returns a link.++//!++//! `tiny-artifacts` defines the [`ArtifactPublisher`] port; the core builds++//! its artifact tools and the preview panel's Share action over whichever++//! publisher a registered factory returns for the current configuration. A++//! factory answers `None` when it cannot publish (no backend configured, not++//! signed in), and the core then offers no sharing.++//!++//! The registry is generic: it knows nothing about where a publisher uploads.++//! With nothing registered the core offers no sharing, unchanged.++++use std::sync::Arc;++++use tiny_artifacts::ArtifactPublisher;++++use crate::config::Config;++use crate::core::slots::{Extensions, HookSlot};++++/// A registered publisher factory.++pub type ArtifactPublisherFactory =++ Arc<dyn Fn(&Config) -> Option<Arc<dyn ArtifactPublisher>> + Send + Sync>;++++static PUBLISHERS: HookSlot<ArtifactPublisherFactory> = HookSlot::new("artifacts::publisher");++++/// Registers the publisher factory `id` for the whole process. The first++/// factory (registration order) that returns a publisher serves requests.++pub fn register_artifact_publisher<F>(id: impl Into<String>, factory: F)++where++ F: Fn(&Config) -> Option<Arc<dyn ArtifactPublisher>> + Send + Sync + 'static,++{++ PUBLISHERS.register(id, Arc::new(factory));++}++++/// Registers the publisher factory `id` for the context built from `extensions`.++pub fn register_artifact_publisher_in<F>(extensions: &Extensions, id: impl Into<String>, factory: F)++where++ F: Fn(&Config) -> Option<Arc<dyn ArtifactPublisher>> + Send + Sync + 'static,++{++ PUBLISHERS.register_in(extensions, id, Arc::new(factory));++}++++/// Removes the process-wide publisher factory `id`.++pub fn unregister_artifact_publisher(id: &str) -> bool {++ PUBLISHERS.unregister(id)++}++++/// The publisher for `config`, or `None` when no registered factory offers one.++pub fn artifact_publisher(config: &Config) -> Option<Arc<dyn ArtifactPublisher>> {++ for (id, factory) in PUBLISHERS.entries() {++ if let Some(publisher) = factory(config) {++ log::debug!("[artifacts] publisher `{id}` serves sharing");++ return Some(publisher);++ }++ }++ None++}++++#[cfg(test)]++#[path = "publisher_slot_tests.rs"]++mod tests;diff --cc crates/openhuman-core/src/agent/artifacts/publisher_slot_tests.rsindex 0000000000,0000000000..6817ed5968new file mode 100644--- /dev/null+++ b/crates/openhuman-core/src/agent/artifacts/publisher_slot_tests.rs@@@ -1,0 -1,0 +1,31 @@@++use super::*;++use tiny_artifacts::{ArtifactRecord, ArtifactVersion, PublishOptions, PublishedLink};++++struct FixedPublisher;++++#[async_trait::async_trait]++impl ArtifactPublisher for FixedPublisher {++ async fn publish(++ &self,++ _record: &ArtifactRecord,++ _version: &ArtifactVersion,++ _options: &PublishOptions,++ ) -> anyhow::Result<PublishedLink> {++ anyhow::bail!("not used")++ }++}++++#[test]++fn nothing_registered_offers_no_publisher() {++ assert!(artifact_publisher(&Config::default()).is_none());++}++++#[test]++fn the_first_factory_that_answers_serves_sharing() {++ register_artifact_publisher("declines", |_| None);++ assert!(artifact_publisher(&Config::default()).is_none());++ register_artifact_publisher("answers", |_| Some(Arc::new(FixedPublisher)));++ assert!(artifact_publisher(&Config::default()).is_some());++ assert!(unregister_artifact_publisher("answers"));++ assert!(artifact_publisher(&Config::default()).is_none());++}diff --cc crates/openhuman-core/src/agent/tinyagents/host/run_context.rsindex 6b19e7d3c5,6d45f0535b..55e0446b0b--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs@@@ -415,14 -415,13 +415,13 @@@ pub(crate) struct HarnessHostPolicypub(crate) tool_call_cap: Option<usize>,}- pub use super::operation_context::approval_for_tool;#[cfg(test)]pub(crate) use super::operation_context::tool_context_with_approval;--pub use super::operation_context::OpenHumanRunExt;++pub use super::operation_context::{approval_for_tool, OpenHumanRunExt};pub(crate) use super::operation_context::{- dispatch_ctx_for_tool, memory_identity_for_tool, parent_agent_id_for_tool,- sandbox_mode_for_tool, task_recency_window_for_tool, turn_origin_for_tool,- HostOperationContext,- approval_for_tool, dispatch_ctx_for_tool, memory_identity_for_tool, memory_in_prompt_for_tool,++ dispatch_ctx_for_tool, memory_identity_for_tool, memory_in_prompt_for_tool,+ parent_agent_id_for_tool, sandbox_mode_for_tool, task_recency_window_for_tool,+ turn_origin_for_tool, HostOperationContext,};impl Default for OpenHumanRunContext {diff --cc crates/openhuman-core/src/media/generation/README.mdindex 4a390c49da,9e46a77545..469d1fdf5a--- a/crates/openhuman-core/src/media/generation/README.md+++ b/crates/openhuman-core/src/media/generation/README.md@@@ -22,11 -20,11 +22,11 @@@ layers, each with a different owner| File | Role || --- | --- |-| [`provider.rs`](./provider.rs) | `managed_generators`: builds `MediaGenerators { image, video }` against the managed backend, or returns `None` when no backend transport is installed. Wraps each generator in a `Guard` that enforces local-only privacy mode and the egress disclosure before a request leaves the device, and the managed-credit budget gate before a billed submit. |-| [`tools.rs`](./tools.rs) | `build_media_tools`: registers `media_generate_image`, `media_generate_video`, and `media_list_models` as `Tool` implementations over the generators from `provider.rs`. Also defines `reference_policy`, which restricts local reference files (for image edits or video first/last frames) to the action directory or workspace directory. |+| [`provider.rs`](./provider.rs) | `MediaGenerators { image, video }` and `GeneratorRouter`: the pair the tools run over, with an optional router that rebuilds them around a turn's chat so egress disclosures reach it. The core ships no generators. |+| [`tools.rs`](./tools.rs) | `media_tools_for_config`: registers `media_generate_image`, `media_generate_video`, and `media_list_models` as `Tool` implementations over host-supplied generators. Also defines `reference_policy`, which restricts local reference files (for image edits or video first/last frames) to the action directory or workspace directory. |- | [`artifact_tool.rs`](./artifact_tool.rs) | `MediaArtifactTool`: wraps a generation tool so every file it saves is also tracked as an OpenHuman artifact, following the same `create_artifact` / `finalize_artifact` pattern the document and presentation tools use. Runs the inner tool unchanged, then files each reported output and stamps an `artifact_id` (or `artifact_error`) onto its entry. |+ | [`artifact_tool.rs`](./artifact_tool.rs) | `MediaArtifactTool`: wraps a generation tool so every file it saves is also tracked as an OpenHuman artifact, through the same `Production` flow (reserve, write, complete) the document and presentation tools use. Runs the inner tool unchanged, then files each reported output and stamps an `artifact_id` (or `artifact_error`) onto its entry. || [`progress.rs`](./progress.rs) | Progress for a long generation call: a heartbeat every 15s through `ToolRunContext::report_progress` while the inner tool runs, carrying the video job state the `WaitPolicy::progress` observer records on each poll. The harness emits these as `AgentEvent::ToolProgressDetail`, which the host publishes on the web channel as `tool_progress`; the chat UI does not render it yet. |-| [`mod.rs`](./mod.rs) | Re-exports: `MediaArtifactTool`, `managed_generators`, `MediaGenerators`, `OPENROUTER_PROXY_PATH`, `build_media_tools`, `media_tools_from`, `MediaListModelsTool`, and the three tool-name constants. |+| [`mod.rs`](./mod.rs) | Re-exports: `MediaArtifactTool`, `MediaGenerators`, `GeneratorRouter`, `media_tools_for_config`, `media_tools_from`, `MediaReferenceAllowlist`, `MediaListModelsTool`, and the three tool-name constants. |## Key typesdiff --cc crates/openhuman-core/src/tools/ops.rsindex 8e3ef39f2d,dfa8b509e2..0c4a98a1ee--- a/crates/openhuman-core/src/tools/ops.rs+++ b/crates/openhuman-core/src/tools/ops.rs@@@ -168,8 -168,11 +168,11 @@@ pub fn all_tools_with_runtime// default-OFF via `tools::user_filter` (their toggle IDs default off// in onboarding). The per-call permission ladder still gates them.]);- tools.extend(crate::agent::artifacts::tools::registered_tools(- config.clone(),+ tools.extend(crate::agent::artifacts::tiny_store::registered_tools(+ &config.workspace_dir,+ crate::agent::artifacts::FileRoots::from_config(&config),+ action_dir,- crate::integrations::file_storage::artifact_publisher(&config),++ crate::agent::artifacts::artifact_publisher(&config),));tools.extend(crate::integrations::task_sources::tools::registered_tools(config.clone(),diff --cc crates/openhuman-embed/src/host_internals.rsindex 7cd6d81bf5,9b38ebc982..2f74e08076--- a/crates/openhuman-embed/src/host_internals.rs+++ b/crates/openhuman-embed/src/host_internals.rs@@@ -281,129 -262,6 +281,140 @@@ pub mod util}}+// ---------------------------------------------------------------------------+// Extension points (tinyhumans). Generic, id-keyed registries the hosted layer+// fills at install time; the core knows nothing about what it is handed. Each+// `register_*` has an `_in` variant that binds to a `CoreBuilder::extensions`+// set instead of the process.+// ---------------------------------------------------------------------------++/// Tool sources: tools an outside crate appends to the agent catalogue.+pub mod tool_sources {+ pub use openhuman_core::tools::sources::{+ register_tool_source, register_tool_source_at, register_tool_source_in,+ registered_tool_source_placements, unregister_tool_source, ToolSourceCtx,+ ToolSourceFactory, ToolSourcePlacement, ANCHOR_AFTER_DELEGATE, ANCHOR_AFTER_SEARCH,+ };+}+++/// The artifact publisher slot: the service that shares an artifact version.++pub mod artifact_publisher {++ pub use openhuman_core::agent::artifacts::{++ register_artifact_publisher, register_artifact_publisher_in, unregister_artifact_publisher,++ ArtifactPublisherFactory,++ };++ // tinyhumans file-storage publisher: the protected-path guard it re-checks++ // before upload, and the store its tests save artifacts into.++ pub use openhuman_core::agent::artifacts::tiny_store::{refused_path, versioned_store};++}+++/// Egress disclosure, for hosted calls that leave the machine.+pub mod egress {+ pub use openhuman_core::security::egress::{+ emit_external_transfer, emit_external_transfer_in, enforce_egress, local_only_blocks,+ DataKind, EgressDescriptor, EgressLedger, EgressReason, IdentificationRisk,+ };+}++/// Config enrichers and the resolved fields they fill.+pub mod config_enrichers {+ pub use openhuman_core::config::schema::resolved_endpoints::ResolvedEndpoints;+ pub use openhuman_core::config::{+ register_enricher, register_enricher_in, run_enrichers, unregister_enricher, ConfigEnricher,+ };+}++/// Composio route builders (`composio.mode` -> route).+pub mod composio {+ pub use openhuman_core::integrations::composio::client::{+ register_composio_route_builder, unregister_composio_route_builder, ComposioRoute,+ ComposioRouteBuilder,+ };+ // The proxy route's target (origin + bearer) for `composio.mode = backend`.+ #[cfg(feature = "modules")]+ pub use openhuman_core::modules::connectors::{+ register_proxy_target, unregister_proxy_target, ProxyTarget, ProxyTargetResolver,+ };+}++/// Media-generation tool building over host-supplied generators (tinyhumans).+#[cfg(feature = "media")]+pub mod media {+ pub mod generation {+ pub use openhuman_core::media::generation::{+ media_tools_for_config, GeneratorRouter, MediaGenerators, MediaReferenceAllowlist,+ };+ }+}++/// The wallet module's authenticated backend hook (tinyhumans web3).+#[cfg(feature = "web3")]+pub mod wallet_backend {+ pub use openhuman_core::modules::wallet_backend::{+ register_wallet_backend, register_wallet_backend_in, unregister_wallet_backend,+ WalletBackendCall, WalletBackendFuture, WalletBackendHandler,+ };+}++/// Model-provider registries: chat models, embeddings, catalogs.+pub mod inference_registry {+ pub use openhuman_core::inference::provider::factory::PROVIDER_OPENHUMAN;+ pub use openhuman_core::inference::provider::openhuman_backend_model::REASONING_OFF_METADATA_KEY;+ pub use openhuman_core::inference::registry::{+ register_catalog, register_catalog_in, register_chat_model, register_chat_model_in,+ register_embedding, register_embedding_in, unregister_catalog, unregister_chat_model,+ unregister_embedding, BoxFuture, CatalogEntry, CatalogLimits, CatalogListing,+ ChatModelEntry, ChatModelFactory, ChatModelRequest, EmbeddingFactory, EmbeddingRequest,+ ReadinessProbe,+ };+}++/// Memory engines by id, and the free-background-work predicate.+pub mod memory_engines {+ pub use openhuman_core::memory::engine::{+ build_cached, rooted, BearerSource, Binding, BoundEngine, EngineCredential, EngineSettings,+ TINYHUMANS_ENGINE,+ };+ pub use openhuman_core::memory::engine_registry::{+ bound_engine, register_memory_engine, register_memory_engine_in, unregister_memory_engine,+ EngineBuilder, EngineEntry, EngineFuture, EngineRequest, FreeBackground,+ };+}++/// The channel callback slot.+#[cfg(feature = "channels")]+pub mod channel_callback {+ pub use openhuman_core::channels::callback_slot::{+ register_channel_callback, register_channel_callback_in, unregister_channel_callback,+ CallbackFuture, ChannelCallback, ChannelCallbackCtx,+ };+}++/// Voice provider registries: STT, TTS and live sessions by slug.+#[cfg(feature = "voice")]+pub mod voice_registry {+ pub use openhuman_core::config::schema::voice_live::{+ LIVE_PROVIDER_ELEVENLABS_HOSTED, LIVE_PROVIDER_GEMINI_HOSTED,+ };+ pub use openhuman_core::voice::factory::registry::{+ register_stt_provider, register_stt_provider_in, register_tts_provider,+ register_tts_provider_in, unregister_stt_provider, unregister_tts_provider,+ SttProviderFactory, TtsProviderFactory,+ };+ pub use openhuman_core::voice::factory::{+ create_stt_provider, create_tts_provider, SttProvider, SttResult, TtsProvider,+ };+ pub use openhuman_core::voice::live::ops::live_providers;+ pub use openhuman_core::voice::live::registry::{+ register_live_provider, register_live_provider_in, unregister_live_provider, ConfigureFn,+ ConfiguredFn, LiveFuture, LiveProviderEntry, LiveProviderPlacement, PrepareFn,+ };+ pub use openhuman_core::voice::live::types::{LiveProviderInfo, LiveProviderKind};+ pub use openhuman_core::voice::live::{+ LiveVoiceError, PreparedProvider, GEMINI_LANGUAGES, GEMINI_VOICES,+ };+}+// The rest is the rpc server alone.pub mod desktop {diff --cc crates/openhuman-tinyhumans/Cargo.tomlindex 35f83884fa,180b669b99..5e60fd1b0f--- a/crates/openhuman-tinyhumans/Cargo.toml+++ b/crates/openhuman-tinyhumans/Cargo.toml@@@ -67,6 -67,6 +67,7 @@@ tinyjevclient = { git = "https://github# The channel controller contract (result types, credential-provider keys)# for the managed Telegram/Discord link flows in `hosted::channel_link`. Same# vendored path as the core's, so the types unify. Sync and I/O-free.++tiny-artifacts = { path = "../../vendor/tiny-artifacts/crates/tiny-artifacts" }tinychannels-bus = { path = "../../vendor/tinychannels/crates/tinychannels-bus" }# AES-256-GCM decryption of the backend OAuth token handoff (hosted::oauth).aes-gcm = "0.10"diff --cc crates/openhuman-tinyhumans/src/integrations/file_storage/artifact_publisher.rsindex 0000000000,4b949e693a..01d00b9456mode 000000,100644..100644--- a/crates/openhuman-tinyhumans/src/integrations/file_storage/artifact_publisher.rs+++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/artifact_publisher.rs@@@ -1,0 -1,283 +1,284 @@@+ //! Sharing artifacts through managed cloud file storage.+ //!+ //! [`StorageArtifactPublisher`] is OpenHuman's implementation of the+ //! `tiny-artifacts` [`ArtifactPublisher`] port: it uploads one version of an+ //! artifact through the same backend routes the `storage_*` tools use and+ //! returns its link — a private presigned link by default, the stored file's+ //! public URL when asked. The crate records the link on that version.+ //!+ //! What is uploaded is exactly the version asked for: a text version's own+ //! content (so any version can be shared), or a file version's file. The+ //! same guards as the storage tools apply: nothing is shared under read-only+ //! autonomy, and the publisher only exists when the integration client does+ //! (a backend is configured and the user is signed in).++ use std::path::Path;+ use std::sync::Arc;++ use async_trait::async_trait;+ use serde_json::json;+ use tiny_artifacts::{+ ArtifactKind, ArtifactPublisher, ArtifactRecord, ArtifactVersion, PublishOptions, PublishedLink,+ };++ use super::tools::helpers::{file_path, mime_for_path, FILES_PATH};+ use super::types::{LinkResponse, UploadResponse};+ use crate::integrations::IntegrationClient;-use crate::security::approval::ApprovalTurnContext;-use crate::security::SecurityPolicy;++use openhuman_embed::__host::config::Config;++use openhuman_embed::__host::security::approval::ApprovalTurnContext;++use openhuman_embed::__host::security::SecurityPolicy;++ /// Lifetime of a private link when the caller does not choose: the backend's+ /// maximum, 7 days.+ const DEFAULT_LINK_SECONDS: u64 = 604_800;++ /// Shares artifact versions through the backend's file storage.+ pub struct StorageArtifactPublisher {+ client: Arc<IntegrationClient>,+ security: Arc<SecurityPolicy>,+ /// The turn the backend requests are reported to. A publisher is built+ /// once per tool set, not per call, so it reports outside any chat.+ approval: ApprovalTurnContext,+ }++ impl StorageArtifactPublisher {+ /// A publisher over `client`, refusing to share when `security` is+ /// read-only.+ pub fn new(client: Arc<IntegrationClient>, security: Arc<SecurityPolicy>) -> Self {+ Self {+ client,+ security,+ approval: ApprovalTurnContext::default(),+ }+ }+ }++ /// The publisher for `config`, or `None` when there is no integration client+ /// (no backend URL configured, or not signed in) — the same condition under+ /// which the `storage_*` tools are absent.-pub fn artifact_publisher(config: &crate::config::Config) -> Option<Arc<dyn ArtifactPublisher>> {++pub fn artifact_publisher(config: &Config) -> Option<Arc<dyn ArtifactPublisher>> {+ let client = crate::integrations::build_client(config)?;+ let security = Arc::new(SecurityPolicy::from_config(+ &config.autonomy,+ &config.workspace_dir,+ &config.action_dir,+ ));+ Some(Arc::new(StorageArtifactPublisher::new(client, security)))+ }++ /// The bytes, file name and media type a version uploads as.+ async fn upload_body(+ record: &ArtifactRecord,+ version: &ArtifactVersion,+ ) -> anyhow::Result<(Vec<u8>, String, &'static str)> {+ if record.holds_file() {+ let path = version+ .file+ .as_ref()+ .map_or(version.body.as_str(), |f| f.path.as_str());+ let path = Path::new(path);+ // The record was checked when written; check again on what the path+ // resolves to now, so nothing protected leaves the machine.+ let resolved = tokio::fs::canonicalize(path)+ .await+ .map_err(|e| anyhow::anyhow!("cannot read the artifact's file: {e}"))?;- if let Some(reason) = crate::agent::artifacts::tiny_store::refused_path(&resolved) {++ if let Some(reason) = openhuman_embed::__host::artifact_publisher::refused_path(&resolved) {+ anyhow::bail!("[policy-blocked] cannot share this artifact: {reason}");+ }+ let bytes = tokio::fs::read(&resolved)+ .await+ .map_err(|e| anyhow::anyhow!("cannot read the artifact's file: {e}"))?;+ // Named after the artifact: the file read may be a kept version copy+ // (`v2.pptx`), whose name means nothing to whoever opens the link.+ let name = match path.extension().and_then(|e| e.to_str()) {+ Some(ext) => format!("{}.{ext}", file_stem(&record.title)),+ None => file_stem(&record.title),+ };+ let mime = mime_for_path(path);+ return Ok((bytes, name, mime));+ }+ let ext = match record.kind {+ ArtifactKind::Markdown => "md",+ ArtifactKind::Html => "html",+ _ => "txt",+ };+ let name = format!("{}.{ext}", file_stem(&record.title));+ let mime = match record.kind {+ ArtifactKind::Markdown => "text/markdown",+ ArtifactKind::Html => "text/html",+ _ => "text/plain",+ };+ Ok((version.body.clone().into_bytes(), name, mime))+ }++ /// A file-name stem from a title: path separators and control characters+ /// dropped, never empty.+ fn file_stem(title: &str) -> String {+ let stem: String = title+ .chars()+ .filter(|c| !matches!(c, '/' | '\\' | '\0') && !c.is_control())+ .collect::<String>()+ .trim()+ .trim_matches('.')+ .to_string();+ if stem.is_empty() {+ "artifact".to_string()+ } else {+ stem+ }+ }++ fn millis(rfc3339: Option<&str>) -> Option<u64> {+ let at = chrono::DateTime::parse_from_rfc3339(rfc3339?).ok()?;+ u64::try_from(at.timestamp_millis()).ok()+ }++ /// Seconds a private link should last: what was asked (7 days by default,+ /// within the backend's 60 s – 7 day range), never past the uploaded file's+ /// own expiry — a link may not outlive its file — less a minute of margin.+ pub(crate) fn link_seconds(+ requested: Option<u64>,+ file_expires_at_millis: Option<u64>,+ now_millis: u64,+ ) -> u64 {+ let wanted = requested+ .unwrap_or(DEFAULT_LINK_SECONDS)+ .clamp(60, DEFAULT_LINK_SECONDS);+ match file_expires_at_millis {+ Some(expires) => {+ let left = expires.saturating_sub(now_millis) / 1000;+ wanted.min(left.saturating_sub(60)).max(60)+ }+ None => wanted,+ }+ }++ /// Whether `err` is the backend refusing the request's values (a 400 or 422),+ /// as opposed to a transport, authentication or server failure. The+ /// integration client reports a status as "Backend returned <code> <reason>".+ fn is_validation_rejection(err: &anyhow::Error) -> bool {+ let message = err.to_string();+ ["Backend returned 400 ", "Backend returned 422 "]+ .iter()+ .any(|prefix| message.contains(prefix))+ }++ impl StorageArtifactPublisher {+ /// A presigned link for `file_id` lasting `seconds`. If the backend+ /// rejects that lifetime (a 400/422), one retry asks for its default+ /// lifetime instead; any other failure is returned as it is.+ async fn private_link(&self, file_id: &str, seconds: u64) -> anyhow::Result<LinkResponse> {+ let route = file_path(file_id, "/link");+ let first = match self+ .client+ .post::<LinkResponse>(+ &self.approval,+ &route,+ &json!({ "expiresInSeconds": seconds }),+ )+ .await+ {+ Ok(link) => return Ok(link),+ Err(err) if is_validation_rejection(&err) => err,+ Err(err) => return Err(anyhow::anyhow!("link generation failed: {err}")),+ };+ tracing::warn!(+ file_id,+ seconds,+ err = %first,+ "[file_storage] link with a set lifetime refused; retrying with the default"+ );+ self.client+ .post::<LinkResponse>(&self.approval, &route, &json!({}))+ .await+ .map_err(|e| anyhow::anyhow!("link generation failed: {e}"))+ }++ /// Delete an upload nothing points at. Best-effort.+ async fn discard(&self, file_id: &str) {+ if let Err(err) = self+ .client+ .delete::<super::types::DeleteResponse>(&self.approval, &file_path(file_id, ""))+ .await+ {+ tracing::warn!(file_id, err = %err, "[file_storage] could not delete an unshared upload");+ }+ }+ }++ #[async_trait]+ impl ArtifactPublisher for StorageArtifactPublisher {+ async fn publish(+ &self,+ record: &ArtifactRecord,+ version: &ArtifactVersion,+ options: &PublishOptions,+ ) -> anyhow::Result<PublishedLink> {+ if !self.security.can_act() {+ anyhow::bail!("[policy-blocked] Action blocked: autonomy is read-only");+ }+ let (bytes, filename, mime) = upload_body(record, version).await?;+ tracing::debug!(+ artifact_id = %record.id,+ version = version.version,+ bytes = bytes.len(),+ public = options.public,+ "[file_storage] sharing artifact version"+ );+ let part = reqwest::multipart::Part::bytes(bytes)+ .file_name(filename)+ .mime_str(mime)?;+ let visibility = if options.public { "public" } else { "private" };+ let form = reqwest::multipart::Form::new()+ .part("file", part)+ .text("visibility", visibility);+ let uploaded = self+ .client+ .upload_multipart::<UploadResponse>(&self.approval, FILES_PATH, form)+ .await+ .map_err(|e| anyhow::anyhow!("upload failed: {e}"))?;++ let link = if options.public {+ uploaded+ .public_url+ .clone()+ .map(|url| (url, uploaded.expires_at.clone()))+ .ok_or_else(|| anyhow::anyhow!("the stored file has no public URL"))+ } else {+ let seconds = link_seconds(+ options.expires_in_seconds,+ millis(uploaded.expires_at.as_deref()),+ tiny_artifacts::now_millis(),+ );+ self.private_link(&uploaded.file_id, seconds)+ .await+ .map(|link| (link.url, link.expires_at))+ };+ let (url, expires_at) = match link {+ Ok(link) => link,+ Err(err) => {+ // Nothing will point at the upload: free it rather than leave+ // a billed orphan.+ self.discard(&uploaded.file_id).await;+ return Err(err);+ }+ };+ tracing::info!(+ artifact_id = %record.id,+ version = version.version,+ file_id = %uploaded.file_id,+ public = options.public,+ "[file_storage] shared artifact version"+ );+ Ok(PublishedLink {+ url,+ expires_at_millis: millis(expires_at.as_deref()),+ published_at_millis: tiny_artifacts::now_millis(),+ public: options.public,+ })+ }+ }++ #[cfg(test)]+ #[path = "artifact_publisher_tests.rs"]+ mod tests;diff --cc crates/openhuman-tinyhumans/src/integrations/file_storage/artifact_publisher_tests.rsindex 0000000000,b7d0afad23..bddcf2a572mode 000000,100644..100644--- a/crates/openhuman-tinyhumans/src/integrations/file_storage/artifact_publisher_tests.rs+++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/artifact_publisher_tests.rs@@@ -1,0 -1,370 +1,370 @@@+ use std::sync::Arc;++ use serde_json::json;+ use tiny_artifacts::{+ ArtifactKind, ArtifactPublisher, ArtifactRecord, ArtifactVersion, Artifacts, Author, Content,+ FileRef, PublishOptions,+ };+ use wiremock::matchers::{body_string_contains, method, path};+ use wiremock::{Mock, MockServer, ResponseTemplate};++ use super::*;-use crate::agent::artifacts::tiny_store::versioned_store;-use crate::security::AutonomyLevel;++use openhuman_embed::__host::artifact_publisher::versioned_store;++use openhuman_embed::__host::security::AutonomyLevel;++ fn publisher(server_uri: String, autonomy: AutonomyLevel) -> StorageArtifactPublisher {+ StorageArtifactPublisher::new(+ Arc::new(IntegrationClient::new(server_uri, "tok".to_string())),+ Arc::new(SecurityPolicy {+ autonomy,+ ..SecurityPolicy::default()+ }),+ )+ }++ fn uploaded(public_url: Option<&str>) -> ResponseTemplate {+ ResponseTemplate::new(200).set_body_json(json!({+ "success": true,+ "data": {+ "fileId": "file-1",+ "filename": "x",+ "size": 4,+ "contentType": "text/markdown",+ "visibility": if public_url.is_some() { "public" } else { "private" },+ "expiresAt": "2030-01-01T00:00:00.000Z",+ "publicUrl": public_url,+ "costUsd": 0.0001+ }+ }))+ }++ async fn mount_link(server: &MockServer, expect: u64) {+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files/file-1/link"))+ .and(body_string_contains("604800"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "success": true,+ "data": {+ "url": "https://s3.example/presigned?sig=abc",+ "expiresAt": "2030-01-08T00:00:00.000Z",+ "costUsd": 0.0001+ }+ })))+ .expect(expect)+ .mount(server)+ .await;+ }++ #[tokio::test]+ async fn a_text_version_uploads_its_own_content_behind_a_private_link() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files"))+ .and(body_string_contains("# version one"))+ .and(body_string_contains("filename=\"Release Notes.md\""))+ .and(body_string_contains("private"))+ .respond_with(uploaded(None))+ .expect(1)+ .mount(&server)+ .await;+ mount_link(&server, 1).await;++ let mut record = ArtifactRecord::new(+ "a-1",+ "Release Notes",+ ArtifactKind::Markdown,+ "# version one",+ "agent",+ 1,+ );+ record.push_version(ArtifactVersion::new(+ 0,+ "# version two",+ tiny_artifacts::ArtifactAuthor::Agent,+ "agent",+ 2,+ ));+ // Version 1, not the newest: its own text is what goes out.+ let link = publisher(server.uri(), AutonomyLevel::Full)+ .publish(+ &record,+ record.version(1).unwrap(),+ &PublishOptions::default(),+ )+ .await+ .unwrap();+ assert_eq!(link.url, "https://s3.example/presigned?sig=abc");+ assert!(!link.public);+ assert_eq!(link.expires_at_millis, Some(1_894_060_800_000));+ }++ #[tokio::test]+ async fn a_public_file_share_uses_the_public_url_and_makes_no_link() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files"))+ .and(body_string_contains("PNG-BYTES"))+ .and(body_string_contains("filename=\"Chart.png\""))+ .and(body_string_contains("public"))+ .respond_with(uploaded(Some("https://api.example/public/file-1")))+ .expect(1)+ .mount(&server)+ .await;+ mount_link(&server, 0).await;++ let dir = tempfile::tempdir().unwrap();+ let file = dir.path().join("chart.png");+ std::fs::write(&file, b"PNG-BYTES").unwrap();+ let mut version = ArtifactVersion::new(+ 1,+ file.display().to_string(),+ tiny_artifacts::ArtifactAuthor::Agent,+ "agent",+ 1,+ );+ version.file = Some(FileRef {+ path: file.display().to_string(),+ size_bytes: 9,+ media_type: Some("image/png".into()),+ });+ let mut record = ArtifactRecord::pending("img-1", "Chart", ArtifactKind::Image, 1);+ record.versions.push(version.clone());++ let options = PublishOptions {+ public: true,+ ..PublishOptions::default()+ };+ let link = publisher(server.uri(), AutonomyLevel::Full)+ .publish(&record, &version, &options)+ .await+ .unwrap();+ assert_eq!(link.url, "https://api.example/public/file-1");+ assert!(link.public);+ }++ #[tokio::test]+ async fn read_only_autonomy_blocks_sharing_before_any_network_call() {+ let record = ArtifactRecord::new("a-1", "T", ArtifactKind::Text, "x", "agent", 1);+ // An unreachable backend: a network attempt would fail differently.+ let err = publisher("http://127.0.0.1:9".into(), AutonomyLevel::ReadOnly)+ .publish(+ &record,+ record.latest().unwrap(),+ &PublishOptions::default(),+ )+ .await+ .unwrap_err();+ assert!(err.to_string().contains("[policy-blocked]"), "{err}");+ }++ #[tokio::test]+ async fn sharing_through_the_service_records_and_reuses_the_link() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files"))+ .respond_with(uploaded(None))+ .expect(1)+ .mount(&server)+ .await;+ mount_link(&server, 1).await;++ let workspace = tempfile::tempdir().unwrap();+ let artifacts = Artifacts::new(Arc::new(versioned_store(workspace.path())))+ .with_publisher(Arc::new(publisher(server.uri(), AutonomyLevel::Full)));+ let id = artifacts+ .create(+ ArtifactKind::Markdown,+ "Notes",+ Content::Text("# hi".into()),+ &Author::agent("agent"),+ None,+ )+ .await+ .unwrap()+ .record+ .id;++ let first = artifacts+ .publish(&id, None, &PublishOptions::default())+ .await+ .unwrap();+ assert!(!first.reused);+ let stored = artifacts.get(&id).await.unwrap().unwrap();+ assert_eq!(+ stored.latest().unwrap().published.as_ref(),+ Some(&first.link)+ );++ // The link is live (expires 2030): no second upload.+ let again = artifacts+ .publish(&id, None, &PublishOptions::default())+ .await+ .unwrap();+ assert!(again.reused);+ assert_eq!(again.link.url, first.link.url);+ }++ #[test]+ fn a_link_never_outlives_its_file() {+ let now = 1_000_000_000_000;+ let day = 86_400;+ // The free plan's file lives exactly 7 days from upload: a 7-day link+ // would end a moment after it, so it is cut to the file's life less a+ // minute.+ let file_expires = Some(now + 7 * day * 1000);+ assert_eq!(link_seconds(None, file_expires, now), 7 * day - 60);+ // A shorter request stands.+ assert_eq!(link_seconds(Some(3600), file_expires, now), 3600);+ // Requests are held to the backend's 60 s – 7 day range.+ assert_eq!(link_seconds(Some(10), None, now), 60);+ assert_eq!(link_seconds(Some(30 * day), None, now), 7 * day);+ // A file about to expire still gets the shortest valid link.+ assert_eq!(link_seconds(None, Some(now + 30_000), now), 60);+ }++ #[tokio::test]+ async fn a_refused_lifetime_falls_back_to_the_backend_default() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files"))+ .respond_with(uploaded(None))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files/file-1/link"))+ .and(body_string_contains("expiresInSeconds"))+ .respond_with(+ ResponseTemplate::new(400)+ .set_body_json(json!({ "success": false, "error": "Validation failed" })),+ )+ .expect(1)+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files/file-1/link"))+ .and(wiremock::matchers::body_json(json!({})))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "success": true,+ "data": { "url": "https://s3.example/default", "expiresAt": "2030-01-01T01:00:00.000Z", "costUsd": 0.0 }+ })))+ .expect(1)+ .mount(&server)+ .await;++ let record = ArtifactRecord::new("a-1", "T", ArtifactKind::Text, "x", "agent", 1);+ let link = publisher(server.uri(), AutonomyLevel::Full)+ .publish(+ &record,+ record.latest().unwrap(),+ &PublishOptions::default(),+ )+ .await+ .unwrap();+ assert_eq!(link.url, "https://s3.example/default");+ }++ #[tokio::test]+ async fn an_upload_that_cannot_be_linked_is_deleted() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files"))+ .respond_with(uploaded(None))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files/file-1/link"))+ .respond_with(+ ResponseTemplate::new(400)+ .set_body_json(json!({ "success": false, "error": "Validation failed" })),+ )+ .expect(2)+ .mount(&server)+ .await;+ Mock::given(method("DELETE"))+ .and(path("/agent-integrations/file-storage/files/file-1"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "success": true, "data": { "deleted": true }+ })))+ .expect(1)+ .mount(&server)+ .await;++ let record = ArtifactRecord::new("a-1", "T", ArtifactKind::Text, "x", "agent", 1);+ let err = publisher(server.uri(), AutonomyLevel::Full)+ .publish(+ &record,+ record.latest().unwrap(),+ &PublishOptions::default(),+ )+ .await+ .unwrap_err();+ assert!(err.to_string().contains("link generation failed"), "{err}");+ }++ #[tokio::test]+ async fn a_server_failure_on_the_link_is_not_retried() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files"))+ .respond_with(uploaded(None))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files/file-1/link"))+ .respond_with(+ ResponseTemplate::new(503)+ .set_body_json(json!({ "success": false, "error": "unavailable" })),+ )+ .expect(1)+ .mount(&server)+ .await;+ Mock::given(method("DELETE"))+ .and(path("/agent-integrations/file-storage/files/file-1"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "success": true, "data": { "deleted": true }+ })))+ .expect(1)+ .mount(&server)+ .await;++ let record = ArtifactRecord::new("a-1", "T", ArtifactKind::Text, "x", "agent", 1);+ let err = publisher(server.uri(), AutonomyLevel::Full)+ .publish(+ &record,+ record.latest().unwrap(),+ &PublishOptions::default(),+ )+ .await+ .unwrap_err();+ assert!(err.to_string().contains("link generation failed"), "{err}");+ }++ #[tokio::test]+ async fn a_file_in_a_protected_location_is_never_uploaded() {+ let dir = tempfile::tempdir().unwrap();+ let ssh = dir.path().join(".ssh");+ std::fs::create_dir_all(&ssh).unwrap();+ let key = ssh.join("id_ed25519");+ std::fs::write(&key, b"PRIVATE").unwrap();+ let mut version = ArtifactVersion::new(+ 1,+ key.display().to_string(),+ tiny_artifacts::ArtifactAuthor::Agent,+ "agent",+ 1,+ );+ version.file = Some(FileRef {+ path: key.display().to_string(),+ size_bytes: 7,+ media_type: None,+ });+ let mut record = ArtifactRecord::pending("k-1", "Key", ArtifactKind::File, 1);+ record.versions.push(version.clone());++ // An unreachable backend: an upload attempt would fail differently.+ let err = publisher("http://127.0.0.1:9".into(), AutonomyLevel::Full)+ .publish(&record, &version, &PublishOptions::default())+ .await+ .unwrap_err();+ assert!(err.to_string().contains("protected location"), "{err}");+ }diff --cc crates/openhuman-tinyhumans/src/integrations/file_storage/tools/helpers.rsindex 955006ceb9,01c5ccead7..295280e007--- a/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/helpers.rs+++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/helpers.rs@@@ -5,10 -5,10 +5,10 @@@ use std::path::{Path, PathBuf}use serde_json::Value;use tinytools::ToolRunContext;-use crate::security::SecurityPolicy;+use openhuman_embed::__host::security::SecurityPolicy;use tinytools::ToolResult;- pub(super) const FILES_PATH: &str = "/agent-integrations/file-storage/files";+ pub(crate) const FILES_PATH: &str = "/agent-integrations/file-storage/files";/// Subdirectory (under `action_dir`) where downloaded files are stored./// Mirrors `media_generation`'s `generated-media/` root — the action dir isdiff --cc crates/openhuman-tinyhumans/src/integrations/mod.rsindex bd035b837b,0000000000..673073291dmode 100644,000000..100644--- a/crates/openhuman-tinyhumans/src/integrations/mod.rs+++ b/crates/openhuman-tinyhumans/src/integrations/mod.rs@@@ -1,73 -1,0 +1,81 @@@+//! Hosted integrations: the integrations client, budget gate, file storage,+//! media generation, web3 crypto client and the Composio backend route.+//!+//! This code used to live in `openhuman-core` (`integrations/client`,+//! `integrations/tools`, `integrations/file_storage`, `media/generation/provider`,+//! `web3/client`) next to the hosted routes it calls. It plugs back into the+//! core only through the generic registries on `openhuman_embed::__host`:+//! [`tool_sources`](openhuman_embed::__host::tool_sources) for the agent tools,+//! [`composio`](openhuman_embed::__host::composio) for the backend route, and- //! the module wallet-backend hook for the web3 crypto client. [`register`] is++//! the module wallet-backend hook for the web3 crypto client, and++//! [`artifact_publisher`](openhuman_embed::__host::artifact_publisher) for sharing++//! artifacts through file storage. [`register`] is+//! the one place it does so; `crate::register::register_all` calls it from+//! `install()`.++pub mod client;+pub mod composio;+pub mod file_storage;+#[cfg(feature = "media")]+pub mod media;+pub mod tools;+pub mod types;+#[cfg(feature = "web3")]+pub mod web3;++pub use client::{build_client, pricing_for_config, IntegrationClient};+pub use types::{+ BackendResponse, IntegrationPricing, IntegrationPricingEntry, PricingIntegrations,+};++use openhuman_embed::__host::tool_sources::{+ register_tool_source_at, ToolSourcePlacement, ANCHOR_AFTER_DELEGATE, ANCHOR_AFTER_SEARCH,+};++use crate::install::InstallOptions;++/// Registers this area's hooks with the core. Idempotent.+///+/// The tool sources register in the order the core used to build them inline+/// (media, file storage, then the Google Places / stock tools) and at the+/// anchors it built them at: media and file storage right after the search+/// tools, the Google Places / stock tools right after the delegation tool, so+/// the catalogue order (a prompt-cache layout input) is unchanged.+pub(crate) fn register(_options: &InstallOptions) {+ #[cfg(feature = "media")]+ media::register();+ register_tool_source_at(+ FILE_STORAGE_SOURCE_ID,+ ToolSourcePlacement::After(ANCHOR_AFTER_SEARCH),+ |ctx| file_storage::build_file_storage_tools(ctx.root_config, ctx.action_dir),+ );+ register_tool_source_at(+ INTEGRATION_TOOLS_SOURCE_ID,+ ToolSourcePlacement::After(ANCHOR_AFTER_DELEGATE),+ |ctx| tools::build_integration_tools(ctx.root_config),+ );+ #[cfg(feature = "web3")]+ web3::register();+ composio::register();++ openhuman_embed::__host::artifact_publisher::register_artifact_publisher(++ ARTIFACT_PUBLISHER_ID,++ file_storage::artifact_publisher,++ );+ log::debug!(- "[tinyhumans] integrations: tool sources, wallet backend and composio route registered"++ "[tinyhumans] integrations: tool sources, wallet backend, composio route and artifact publisher registered"+ );+}++/// The id the file-storage tool source registers under.+pub const FILE_STORAGE_SOURCE_ID: &str = "tinyhumans-file-storage";++/// The id the artifact publisher (sharing through file storage) registers under.++pub const ARTIFACT_PUBLISHER_ID: &str = "tinyhumans-file-storage";+/// The id the Google Places / stock tool source registers under.+pub const INTEGRATION_TOOLS_SOURCE_ID: &str = "tinyhumans-integrations";++#[cfg(test)]+mod test_support;++#[cfg(test)]+#[path = "mod_tests.rs"]+mod tests;diff --cc crates/openhuman-tinyhumans/src/integrations/mod_tests.rsindex f49fa1c6ee,0000000000..a61ba7bb26mode 100644,000000..100644--- a/crates/openhuman-tinyhumans/src/integrations/mod_tests.rs+++ b/crates/openhuman-tinyhumans/src/integrations/mod_tests.rs@@@ -1,120 -1,0 +1,125 @@@+//! Tests for the integrations module root (types + client construction).++use super::*;+#[test]+fn backend_response_deserializes() {+ let json = r#"{"success": true, "data": {"foo": 42}}"#;+ let resp: BackendResponse<serde_json::Value> = serde_json::from_str(json).unwrap();+ assert!(resp.success);+ assert_eq!(resp.data.unwrap()["foo"], 42);+}++#[test]+fn backend_response_without_data() {+ let json = r#"{"success": true}"#;+ let resp: BackendResponse<serde_json::Value> = serde_json::from_str(json).unwrap();+ assert!(resp.success);+ assert!(resp.data.is_none());+}++#[test]+fn integration_pricing_defaults_on_missing_fields() {+ let json = r#"{"integrations": {}}"#;+ let pricing: IntegrationPricing = serde_json::from_str(json).unwrap();+ assert!(pricing.integrations.google_places.is_none());+ assert!(pricing.integrations.parallel.is_none());+ assert!(pricing.integrations.tinyfish.is_none());+}++#[test]+fn integration_pricing_ignores_retired_apify_and_twilio_entries() {+ // An older backend still reporting the retired integrations must not+ // break pricing deserialization.+ let json = r#"{"integrations": {+ "apify": {"available": true, "pricing": {}},+ "twilio": {"available": true, "pricing": {}},+ "parallel": {"available": true, "pricing": {}}+ }}"#;+ let pricing: IntegrationPricing = serde_json::from_str(json).unwrap();+ assert!(pricing.integrations.parallel.unwrap().available);+}++#[test]+fn build_client_returns_none_when_no_auth_token() {+ let tmp = tempfile::tempdir().expect("tempdir");+ let config = openhuman_embed::__host::config::Config {+ workspace_dir: tmp.path().join("workspace"),+ action_dir: tmp.path().join("workspace"),+ config_path: tmp.path().join("config.toml"),+ ..openhuman_embed::__host::config::Config::default()+ };+ assert!(build_client(&config).is_none());+}++#[test]+fn register_plugs_every_hosted_integration_into_the_core_registries() {+ use openhuman_embed::__host::composio::unregister_composio_route_builder;+ use openhuman_embed::__host::config::schema::COMPOSIO_MODE_BACKEND;+ use openhuman_embed::__host::tool_sources::unregister_tool_source;++ register(&InstallOptions::default());++ assert!(unregister_tool_source(FILE_STORAGE_SOURCE_ID));+ assert!(unregister_tool_source(INTEGRATION_TOOLS_SOURCE_ID));+ #[cfg(feature = "media")]+ assert!(unregister_tool_source(media::TOOL_SOURCE_ID));+ #[cfg(feature = "web3")]+ assert!(openhuman_embed::__host::wallet_backend::unregister_wallet_backend(web3::HANDLER_ID));+ assert!(unregister_composio_route_builder(COMPOSIO_MODE_BACKEND));++ assert!(++ openhuman_embed::__host::artifact_publisher::unregister_artifact_publisher(++ ARTIFACT_PUBLISHER_ID++ )++ );+ #[cfg(feature = "modules")]+ assert!(openhuman_embed::__host::composio::unregister_proxy_target(+ COMPOSIO_MODE_BACKEND+ ));++ // Registration is idempotent and restores everything it removed above.+ register(&InstallOptions::default());+ register(&InstallOptions::default());+ assert!(unregister_tool_source(FILE_STORAGE_SOURCE_ID));+ register(&InstallOptions::default());+}++/// The catalogue order is a prompt-cache input. Before the move the core built+/// the media and file-storage tools right after the search tools, and the+/// Google Places / stock tools right after the delegation tool (ahead of+/// Composio); the sources must register at those same anchors and in that order.+#[test]+fn tool_sources_register_at_the_pre_refactor_catalogue_positions() {+ use openhuman_embed::__host::tool_sources::{+ registered_tool_source_placements, unregister_tool_source, ToolSourcePlacement,+ ANCHOR_AFTER_DELEGATE, ANCHOR_AFTER_SEARCH,+ };++ register(&InstallOptions::default());+ let ours: Vec<_> = registered_tool_source_placements()+ .into_iter()+ .filter(|(id, _)| id.starts_with("tinyhumans-"))+ .collect();+ let placement = |id: &str| ours.iter().find(|(i, _)| i == id).map(|(_, p)| *p);+ let position = |id: &str| ours.iter().position(|(i, _)| i == id);++ assert_eq!(+ placement(FILE_STORAGE_SOURCE_ID),+ Some(ToolSourcePlacement::After(ANCHOR_AFTER_SEARCH))+ );+ assert_eq!(+ placement(INTEGRATION_TOOLS_SOURCE_ID),+ Some(ToolSourcePlacement::After(ANCHOR_AFTER_DELEGATE))+ );+ #[cfg(feature = "media")]+ {+ assert_eq!(+ placement(media::TOOL_SOURCE_ID),+ Some(ToolSourcePlacement::After(ANCHOR_AFTER_SEARCH))+ );+ // media before file storage, as the core built them.+ assert!(position(media::TOOL_SOURCE_ID) < position(FILE_STORAGE_SOURCE_ID));+ assert!(unregister_tool_source(media::TOOL_SOURCE_ID));+ }+ assert!(unregister_tool_source(FILE_STORAGE_SOURCE_ID));+ assert!(unregister_tool_source(INTEGRATION_TOOLS_SOURCE_ID));+}diff --cc scripts/ci/process-statics.jsonindex 31129a13a7,1765d5b551..0ee65285ae--- a/scripts/ci/process-statics.json+++ b/scripts/ci/process-statics.json@@@ -139,134 -129,14 +139,154 @@@"reason": "The process's registry of weak handles to the rebindable session-store providers a host installed, so a workspace switch (storage::rebind) can point each at the new backend. It holds no records and no tenant state, only Weak references; the stores' data lives in the storage backend. A test builds its own StoreRegistry, so rebinding one never moves another's stores.","verification": "agent/session_store/rebound_tests.rs: a_registry_rebind_leaves_other_registries_alone"},++ {++ "file": "crates/openhuman-core/src/agent/artifacts/publisher_slot.rs",++ "scope": "",++ "name": "PUBLISHERS",++ "type": "HookSlot<ArtifactPublisherFactory>",++ "count": 1,++ "category": "A",++ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",++ "verification": "agent/artifacts/publisher_slot_tests.rs: the_first_factory_that_answers_serves_sharing"++ },+ {+ "file": "crates/openhuman-core/src/channels/callback_slot.rs",+ "scope": "",+ "name": "CALLBACKS",+ "type": "HookSlot<ChannelCallback>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "channels/callback_slot_tests.rs: the_first_registered_callback_serves_requests"+ },+ {+ "file": "crates/openhuman-core/src/config/enrichers.rs",+ "scope": "",+ "name": "ENRICHERS",+ "type": "HookSlot<ConfigEnricher>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "config/enrichers_tests.rs: enrichers_run_in_registration_order"+ },+ {+ "file": "crates/openhuman-core/src/inference/registry.rs",+ "scope": "",+ "name": "CHAT_MODELS",+ "type": "HookSlot<ChatModelEntry>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "inference/registry_tests.rs: a_registered_chat_model_serves_the_managed_provider_for_a_thread"+ },+ {+ "file": "crates/openhuman-core/src/inference/registry.rs",+ "scope": "",+ "name": "EMBEDDINGS",+ "type": "HookSlot<EmbeddingFactory>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "inference/registry_tests.rs: a_registered_embedding_factory_builds_the_managed_embedding_model"+ },+ {+ "file": "crates/openhuman-core/src/inference/registry.rs",+ "scope": "",+ "name": "CATALOGS",+ "type": "HookSlot<CatalogEntry>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "inference/registry_tests.rs: a_registered_catalog_answers_the_model_listing_for_its_provider"+ },+ {+ "file": "crates/openhuman-core/src/integrations/composio/client/factory.rs",+ "scope": "",+ "name": "ROUTE_BUILDERS",+ "type": "HookSlot<ComposioRouteBuilder>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "integrations/composio/client/factory_tests.rs: a_registered_route_builder_resolves_the_backend_mode"+ },+ {+ "file": "crates/openhuman-core/src/modules/connectors.rs",+ "scope": "",+ "name": "MODULE_PROXY_TARGETS",+ "type": "HookSlot<ProxyTargetResolver>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of handlers the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "modules/connectors_tests.rs: the_backend_route_is_unavailable_without_a_registered_target"+ },+ {+ "file": "crates/openhuman-core/src/memory/engine_registry.rs",+ "scope": "",+ "name": "ENGINES",+ "type": "HookSlot<EngineEntry>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "memory/engine_registry_tests.rs: the_layout_root_reaches_the_registered_builder"+ },+ {+ "file": "crates/openhuman-core/src/tools/sources.rs",+ "scope": "",+ "name": "TOOL_SOURCES",+ "type": "HookSlot<ToolSourceEntry>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "tools/sources_tests.rs: registered_sources_append_in_registration_order_after_built_ins"+ },+ {+ "file": "crates/openhuman-core/src/voice/factory/registry.rs",+ "scope": "",+ "name": "STT_PROVIDERS",+ "type": "HookSlot<SttProviderFactory>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "voice/factory/registry_tests.rs: a_registered_stt_slug_is_built_with_the_effective_model"+ },+ {+ "file": "crates/openhuman-core/src/voice/factory/registry.rs",+ "scope": "",+ "name": "TTS_PROVIDERS",+ "type": "HookSlot<TtsProviderFactory>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "voice/factory/registry_tests.rs: a_registered_tts_provider_gets_the_resolved_voice_and_returns_reply_speech"+ },+ {+ "file": "crates/openhuman-core/src/voice/live/registry.rs",+ "scope": "",+ "name": "LIVE_PROVIDERS",+ "type": "HookSlot<LiveProviderEntry>",+ "count": 1,+ "category": "A",+ "reason": "Host wiring: an id-keyed table of factories the embedding host registers at startup (core::slots::HookSlot). It holds code, never tenant data; a per-context override table lives on the CoreContext, not here.",+ "verification": "voice/live/registry_tests.rs: a_registered_provider_is_listed_after_the_built_in_ones"+ },+ {+ "file": "crates/openhuman-core/src/core/slots.rs",+ "scope": "",+ "name": "TEST_GLOBALS",+ "type": "std::cell::RefCell<HashMap<&'static str,Box<dyn Any>>>",+ "count": 1,+ "category": "A",+ "reason": "cfg(test) only: replaces a slot's process table with a per-thread one so a test's fake registration cannot reach a test on another thread. Not compiled into any shipped build.",+ "verification": "core/slots_tests.rs: entries_keep_registration_order_and_re_registering_keeps_position"++ },+ {+ "file": "crates/openhuman-core/src/threads/artifact_rows.rs",+ "scope": "",+ "name": "ARTIFACT_ROW_HANDLE",+ "type": "OnceLock<SubscriptionHandle>",+ "count": 1,+ "category": "A",+ "reason": "Keeps the one process-wide event-bus subscription that writes artifact rows alive and makes registration idempotent; it holds no data, and each event names the workspace and thread its row is written to.",+ "verification": "threads/artifact_rows_tests.rs: recording_an_artifact_twice_writes_one_row"}]