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
feat(hosting): route deployment tools through TinyHosts module
Steven Enamakel97a1537aac12
diff --git a/Cargo.lock b/Cargo.lockindex 10ccd480e1..7279f79374 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4679,7 +4679,7 @@ dependencies = ["tinyflows-drivers","tinyflows-schedule","tinyflows-sqlite",- "tinyhosts",+ "tinyhosts-bus","tinyinference-core","tinyinference-embeddings","tinyinference-llm",@@ -7637,21 +7637,12 @@ dependencies = [][[package]]-name = "tinyhosts"-version = "0.2.3"+name = "tinyhosts-bus"+version = "0.3.0"dependencies = [- "anyhow",- "async-trait",- "base64 0.23.1",- "hex",- "percent-encoding",- "reqwest 0.12.28","serde","serde_json",- "sha1 0.11.0","thiserror 2.0.20",- "tinytools",- "tracing",][[package]]diff --git a/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lockindex b8fc81cf18..eca5367a94 100644--- a/crates/openhuman-app/Cargo.lock+++ b/crates/openhuman-app/Cargo.lock@@ -4632,7 +4632,7 @@ dependencies = ["tinyflows-drivers","tinyflows-schedule","tinyflows-sqlite",- "tinyhosts",+ "tinyhosts-bus","tinyinference-core","tinyinference-embeddings","tinyinference-llm",@@ -7938,21 +7938,12 @@ dependencies = [][[package]]-name = "tinyhosts"-version = "0.2.3"+name = "tinyhosts-bus"+version = "0.3.0"dependencies = [- "anyhow",- "async-trait",- "base64 0.23.1",- "hex",- "percent-encoding",- "reqwest 0.12.28","serde","serde_json",- "sha1 0.11.0","thiserror 2.0.20",- "tinytools",- "tracing",][[package]]diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.tomlindex dc6b4bedc4..d5c934f65b 100644--- a/crates/openhuman-core/Cargo.toml+++ b/crates/openhuman-core/Cargo.toml@@ -545,22 +545,11 @@ tinyjuice-bus = { path = "../../vendor/tinyjuice/crates/tinyjuice-bus" }# feeds them each original over the bus: see `inference/tokenjuice/repl_tools.rs`.tinyjuice = { path = "../../vendor/tinyjuice", default-features = false, features = ["tinytools", "host"] }-# TinyHosts — the unified hosting API: one `Host` trait over a hosting provider,-# and the `launch` flow that puts a Next.js application, its database, its-# environment and its domains on it in the one order that works.-#-# The provider vocabulary stops inside the crate. What OpenHuman gets is the-# model — sites, deployments, databases, domains, analytics — so which provider-# a user pastes a key for is a config value here rather than a code path.-#-# Taken with the `vercel` provider only, which is the one that exists.-#-# Vendored as a path dependency like `tinyhumans-sdk`: the crate is not-# published to crates.io, so there is no `[patch.crates-io]` entry for it.-# After cloning: `git submodule update --init vendor/tinyhosts`.-#+# Transport-free host contract for the compiled TinyHosts provider module.+# Provider operations, deployment sequencing, and bounded source preparation+# stay in the owner repository; OpenHuman adds only the configured adapter.# Optional: exclusive to the default-OFF `hosting` feature.-tinyhosts = { path = "../../vendor/tinyhosts", default-features = false, features = ["vercel", "tools"], optional = true }+tinyhosts-bus = { path = "../../vendor/tinyhosts/crates/tinyhosts-bus", optional = true }# TinyWallet — host-agnostic multi-chain wallet primitives. Owns the address# formats themselves: parsing, validation, and the conversions between their@@ -804,7 +793,7 @@ documents = ["modules", "dep:tinydocs-bus", "tinymemory-integrations/documents-o# still only registered once a credential actually resolves — from# `[hosting].api_key` or the provider's environment variable — because a tool# that cannot work is worse than a tool that is not there.-hosting = ["dep:tinyhosts"]+hosting = ["modules", "dep:tinyhosts-bus"]# TinyMemes: remixes the final reply with the user's register, regional slang# and, sometimes, a reaction meme. Compiled into product builds; at runtime it# is still off until `OPENHUMAN_TINYMEMES` (or a build-timediff --git a/crates/openhuman-core/src/config/schema/hosting.rs b/crates/openhuman-core/src/config/schema/hosting.rsindex abdfc38a9a..4c6607c810 100644--- a/crates/openhuman-core/src/config/schema/hosting.rs+++ b/crates/openhuman-core/src/config/schema/hosting.rs@@ -2,7 +2,7 @@//!//! Where the credential for a hosting provider comes from, and whether the//! `hosting_*` agent tools are offered at all. Read by-//! [`crate::hosting::credentials`] when it resolves an account, and+//! [`crate::hosting::Account`] when it resolves an account, and//! by the tool registry when it decides whether to register the tools.//!//! The key may be left empty here: an empty key falls back to the provider's own@@ -26,7 +26,7 @@ pub struct HostingConfig {pub provider: String,/// The provider API key. Empty means "read it from the environment", which- /// is [`tinyhosts::ProviderKind::credentials_from_env`]'s search order.+ /// is the `TINYHOSTS_VERCEL_TOKEN`, then `VERCEL_TOKEN` environment search.#[serde(default)]pub api_key: String,diff --git a/crates/openhuman-core/src/hosting/README.md b/crates/openhuman-core/src/hosting/README.mdindex 53327fe813..2b42da5653 100644--- a/crates/openhuman-core/src/hosting/README.md+++ b/crates/openhuman-core/src/hosting/README.md@@ -1,163 +1,32 @@-# hosting--Puts a workspace on the internet. This domain is the thin seam between-OpenHuman and [`tinyhosts`](../../../../vendor/tinyhosts), the unified hosting-API. TinyHosts owns everything about a provider (today, Vercel): its REST-endpoints, the upload-then-build deployment protocol, how a marketplace-database is provisioned and connected, and the order a launch runs in. This-module owns the OpenHuman side: where the credential comes from, which-workspace the agent deploys from, and whether the tools are offered at all.--The whole domain is one file, [`mod.rs`](./mod.rs), around a single type, `Account`.--## How it works--At tool-registry build time, `tools::ops` (in [`src/tools/ops.rs`](../tools/ops.rs)) asks this-module for an account. If one resolves, the account's ten tools are appended-to the agent's tool list. If none resolves, nothing is registered.--```text- tools::ops (registry build, #[cfg(feature = "hosting")])- |- v- Account::from_config(&Config)- |- |-- [hosting].enabled == false ----------------> Ok(None) (no tools)- |- |-- ProviderKind::from_str(provider) (bad slug -> Err, logged at warn)- |- |-- [hosting].api_key set?- | yes -> Credentials::new(key) [+ with_team(team)]- | no -> provider.credentials_from_env()- | not found ---------------------> Ok(None) (no tools)- |- v- tinyhosts::connect(provider, credentials) -> Arc<dyn Host>- |- v- Account { host, workspace_dir }- |- v- account.tools() = tinyhosts::tools::hosting_tools(&host, &workspace_dir)-```--`from_config` separates "absent" from "wrong". Hosting switched off, or-switched on with no key anywhere, is the ordinary state of a host nobody has-connected a provider to, so it returns `Ok(None)` and logs at `debug`. An-unknown provider slug, a blank configured key, or a client that fails to build-is a misconfiguration: it returns an error, which `tools::ops` logs at `warn`-and then skips. Startup does not fail, since nothing else in the process-depends on hosting.--The reason absent credentials mean absent tools: a tool that is present and-cannot work is worse than one that is missing, because a model will retry it.--Embedders that hold their own credential use `Account::connect(provider,-api_key, team, workspace_dir)` instead. It takes the provider slug and key as-plain strings, so a host (OpenCompany keeps one hosting key per company in that-company's secret store) can reach the tools without naming `tinyhosts` in its-own dependency graph.--Configuration lives in `HostingConfig` ([`src/config/schema/hosting.rs`](../config/schema/hosting.rs)):-`enabled`, `provider` (default `vercel`), `api_key` (empty means "read the-provider's environment variable"), and `team` (empty means the personal-account). Its `Debug` impl redacts the key.--## Layout--| Path | What it does |-| --- | --- |-| `mod.rs` | `Account`: `from_config` credential resolution, `connect` for embedders, the shared `Arc<dyn Host>`, `tools()`, and the `resolve_in_workspace` re-export. |--## Key types and entry points--- `Account` (`mod.rs`) is one hosting account plus the workspace it deploys- from. Its `Debug` prints the provider slug and workspace, never the client.-- `Account::from_config` resolves an account from `[hosting]` and the- environment, as described above.-- `Account::connect` builds an account from credentials an embedder resolved.-- `Account::tools` returns the ten `hosting_*` tools as- `Vec<Box<dyn tinytools::Tool>>`.-- `resolve_in_workspace` is re-exported from `tinyhosts::tools`. It decides- which directory an agent may deploy.--## Agent tools--All ten are implemented in [`vendor/tinyhosts/src/tools/`](../../../../vendor/tinyhosts/src/tools/). Tools with an-external effect return `true` from `Tool::external_effect`, which the agent-harness reads to route the call through approval.--| Tool | Effect |-| --- | --- |-| `hosting_launch_site` | Deploys a workspace directory as a live site, optionally provisioning a database and wiring it in, setting environment variables, and attaching domains. External effect. |-| `hosting_deployment_status` | Whether a build has finished. Read-only. |-| `hosting_list_deployments` | A site's recent deployments, newest first, with status and target. Read-only. |-| `hosting_deployment_logs` | A deployment's build and runtime log events, oldest first, trimmed to the most recent. Read-only. |-| `hosting_rollback` | Points production back at an earlier deployment that already built. External effect. |-| `hosting_list_sites` | The sites on the account. Read-only. |-| `hosting_set_env` | Sets environment variables on an existing site. External effect. |-| `hosting_add_domain` | Attaches a custom domain. External effect. |-| `hosting_domain_status` | Whether a site's domains are verified and serving. Read-only. |-| `hosting_analytics` | Traffic over the last N days. Read-only. |--### Rollback, and why there is no separate promote--`Host::promote` covers both: a rollback is a promote of an older deployment,-and the crate models it once. The tool is named for the reason an agent-reaches for it, which is recovering a site a deploy broke.--`hosting_rollback` reads the deployment before promoting it and refuses one-that did not finish building. `hosting_list_deployments` returns failed and-still-building deployments too, because they are the history an agent is-reading, so the id an agent picks is not necessarily one that can serve-traffic. Promoting a failed build would take the site down during an attempt-to bring it back up.--The tool does not check that the deployment belongs to the named site. A-deployment is looked up by id alone and the provider's response may omit the-project name, so that check would refuse legitimate rollbacks. The provider-enforces it.--## Boundaries--- Provider behavior (endpoints, deployment states, database provisioning,- launch ordering, the tool implementations and their argument validation)- belongs to `tinyhosts` ([`vendor/tinyhosts`](../../../../vendor/tinyhosts/), upstream- `tinyhumansai/tinyhosts`). Nothing in this module knows the word- `readyState`, and nothing in `tinyhosts` knows what a workspace is.-- Approval routing belongs to the agent harness, via `external_effect`.-- There are no RPC controllers and no events: no `schemas.rs`, no `bus.rs`.--## Gotchas--- Two gates both have to pass. The `hosting` Cargo feature (default-off in the- contributor build, on in `scripts/ci/product-features.txt`) decides whether- `openhuman::hosting` compiles at all. A resolving credential decides whether- the tools register at runtime.-- This process never reads a managed database's secret. The provider injects- the connection string into the site's environment; OpenHuman learns only the- variable names. That is why `hosting_launch_site` reports `DATABASE_URL`- rather than a URL.-- `resolve_in_workspace` refuses absolute paths, `..` escapes, and- non-directories. It is the only place that decides what may leave the- machine, and a deployment uploads every byte under the directory it is given.-- The doc comment in `src/config/schema/hosting.rs` mentions- `crate::hosting::credentials`, which does not exist. Credential resolution is- `Account::from_config`.--## Tests--[`hosting_tests.rs`](./hosting_tests.rs) covers the seam only: account resolution from config and-the tool set handed back. The tools themselves, workspace containment, and the-rollback guard are tested in `tinyhosts` against a mock of the provider API.--```bash-cargo test -p openhuman --features hosting hosting::-```--## Further reading--- [Parent module README](../../README.md)-- [Hosting](../../../../gitbooks/features/hosting.md)-- [Cloud deploy](../../../../gitbooks/features/cloud-deploy.md)-- [tinyhosts](../../../../vendor/tinyhosts/README.md)+# Hosting adapter++OpenHuman exposes TinyHosts provider operations through the compiled TinyHosts+TinyBus module. This domain owns the host-specific policy: resolving the+Vercel credential from `[hosting]` or the documented environment variables,+scoping a deployable path to the configured workspace, and presenting the+model-facing tool declarations. It does not link the provider implementation.++The lazy module loader is first used when a hosting tool runs. The adapter+queries `Providers`, then sends the existing `Execute` envelope. Credential+bearing requests use confidential TinyBus delivery. The portable request and+tool vocabulary is defined in `vendor/tinyhosts/crates/tinyhosts-bus`; provider+API calls, source preparation, and deployment sequencing live in the released+TinyHosts module.++All ten names, descriptions, schemas, and approval classifications are read+from the release contract's `TOOL_DECLARATIONS_JSON`. OpenHuman keeps the+workspace containment check and checks that a rollback target is ready before+it asks the module to promote it. The module itself enforces preparation limits+and validates the uploaded snapshot.++`hosting::Account::from_config` returns no account when hosting is disabled or+no credential resolves. Invalid providers and blank explicit credentials are+configuration errors. `Account::connect` is the embedding seam for hosts that+resolve credentials in their own secret store; it uses the supplied workspace+for module artifact discovery as well as deployable paths. Embedders with a+custom module policy or artifact root can use `Account::connect_with_config`.++`Account::host()` was removed with the provider implementation dependency. Its+return type exposed TinyHosts' concrete implementation trait, which cannot be+kept in the host crate without restoring that dependency. Callers should use+the stable `Account::tools()` surface or the TinyHosts bus contract directly.diff --git a/crates/openhuman-core/src/hosting/hosting_tests.rs b/crates/openhuman-core/src/hosting/hosting_tests.rsindex a40170f4ff..c54a645050 100644--- a/crates/openhuman-core/src/hosting/hosting_tests.rs+++ b/crates/openhuman-core/src/hosting/hosting_tests.rs@@ -1,12 +1,8 @@-//! Tests for hosting account resolution and the tool set it exposes.-//!-//! The provider and the tools themselves (workspace containment, argument-//! validation, the rollback guard, the declarations a model sees) are TinyHosts'-//! and are tested there. What is tested here is the seam: whether an account-//! resolves from configuration and hands the crate's tools its host and workspace.+//! Tests for OpenHuman's hosting module adapter and its tool contract.use super::*;use crate::config::Config;+use std::sync::{Arc, Mutex};fn config_with(workspace: &std::path::Path, enabled: bool, api_key: &str) -> Config {let mut config = Config::default();@@ -16,14 +12,69 @@ fn config_with(workspace: &std::path::Path, enabled: bool, api_key: &str) -> Conconfig}+/// A recording adapter fixture for OpenHuman's exact member, tuple, and+/// confidentiality intent. The TinyBus transport is covered separately by+/// the generic client fixtures and the released-module verifier.+fn account_fixture(+ workspace_dir: PathBuf,+ calls: Arc<Mutex<Vec<(String, serde_json::Value, bool)>>>,+) -> Account {+ let mut config = Config::default();+ config.workspace_dir = workspace_dir;+ config.hosting.enabled = true;+ config.hosting.api_key = "fixture-secret".to_owned();+ let account = Account::from_config(&config)+ .expect("configuration")+ .expect("account");+ let calls_out = Arc::clone(&calls);+ let fixture = Arc::new(+ move |member: &str, args: serde_json::Value, confidential: bool| {+ calls_out+ .lock()+ .unwrap()+ .push((member.to_owned(), args.clone(), confidential));+ if member == tinyhosts_bus::METHODS[1] {+ return Ok(serde_json::json!(["vercel"]).to_string());+ }+ let request = args+ .as_array()+ .and_then(|args| args.first())+ .and_then(serde_json::Value::as_str)+ .ok_or_else(|| anyhow::anyhow!("fixture expected one JSON argument"))?;+ let request: serde_json::Value = serde_json::from_str(request)?;+ let response = match request.get("operation").and_then(serde_json::Value::as_str) {+ Some("prepare_bundle") => serde_json::json!({"result":"prepared_bundle","value":{+ "contract_version":[1,1],+ "bundle":[{"path":"index.html","contents":"aGVsbG8="}],+ "file_count":1,"total_bytes":5,"skipped_entries":0,"scanned_entries":1+ }}),+ Some("launch") => serde_json::json!({"result":"launch","value":{+ "site":{"id":"site-1","name":"demo"},"created_site":true,+ "database":null,"database_env_keys":[],"domains":[],+ "deployment":{"id":"deploy-1","site":"demo","status":"building","url":"https://demo.example"}+ }}),+ Some("list_sites") => serde_json::json!({"result":"sites","value":[]}),+ _ => return Err(anyhow::anyhow!("unexpected fixture operation")),+ };+ Ok(response.to_string())+ },+ );+ Account {+ call_fixture: Some(fixture),+ ..account+ }+}+#[test]fn hosting_off_yields_no_account() {let workspace = tempfile::tempdir().expect("tempdir");let config = config_with(workspace.path(), false, "token");- assert!(Account::from_config(&config)- .expect("resolution does not fail")- .is_none());+ assert!(+ Account::from_config(&config)+ .expect("resolution does not fail")+ .is_none()+ );}#[test]@@ -35,7 +86,7 @@ fn a_configured_key_yields_an_account() {.expect("resolution does not fail").expect("an account, since a key is configured");- assert_eq!(account.host().kind().as_str(), "vercel");+ assert_eq!(account.provider, "vercel");assert_eq!(account.workspace_dir(), workspace.path());}@@ -97,6 +148,298 @@ fn an_account_exposes_every_hosting_tool() {"hosting_analytics",]);+ for tool in account.tools() {+ assert!(!tool.description().is_empty());+ assert_eq!(tool.parameters_schema()["type"], "object");+ }+}++#[test]+fn tool_declarations_match_the_released_module_contract() {+ let workspace = tempfile::tempdir().expect("tempdir");+ let account = Account::from_config(&config_with(workspace.path(), true, "token"))+ .expect("resolution")+ .expect("account");+ let tools = account.tools();+ let declarations: Vec<tinyhosts_bus::ToolDeclaration> =+ serde_json::from_str(tinyhosts_bus::TOOL_DECLARATIONS_JSON).expect("contract json");+ assert_eq!(tools.len(), declarations.len());+ for (tool, declaration) in tools.iter().zip(declarations) {+ assert_eq!(tool.name(), declaration.name);+ assert_eq!(tool.description(), declaration.description);+ assert_eq!(tool.parameters_schema(), declaration.parameters_schema);+ assert_eq!(tool.external_effect(), declaration.external_effect);+ assert_eq!(+ tool.permission_level(),+ match declaration.permission_level {+ tinyhosts_bus::PermissionLevel::ReadOnly => tinytools::PermissionLevel::ReadOnly,+ tinyhosts_bus::PermissionLevel::Write => tinytools::PermissionLevel::Write,+ }+ );+ }+}++#[test]+fn the_module_registry_pins_the_released_hosts_artifact_set() {+ let record = crate::modules::registry::find("tinyhosts").expect("registered module");+ assert_eq!(record.version, "0.3.0");+ assert_eq!(record.assets.len(), 11);+ assert!(record.assets.iter().all(|asset| {+ asset.archive.starts_with("tinyhosts-0.3.0-") && asset.sha256.len() == 64+ }));+ assert_eq!(+ record.asset_for("ubuntu-24.04-x86_64").unwrap().sha256,+ "368f00ee397649481ff8f61d33eeb8b908cc416d6b2f9d4ef3c81263d6b0460e"+ );+}++#[tokio::test]+async fn providers_and_launch_use_the_declared_bus_members_and_confidential_execute() {+ let workspace = tempfile::tempdir().expect("workspace");+ std::fs::create_dir(workspace.path().join("app")).unwrap();+ std::fs::write(workspace.path().join("app/index.html"), "hello").unwrap();+ let calls = Arc::new(Mutex::new(Vec::new()));+ let account = account_fixture(workspace.path().to_path_buf(), Arc::clone(&calls));+ let tools = account.tools();+ let launch = tools+ .iter()+ .find(|tool| tool.name() == "hosting_launch_site")+ .unwrap();+ let result = launch+ .execute(serde_json::json!({"site":"demo","path":"app"}))+ .await+ .unwrap();+ assert!(!result.is_error);+ assert!(+ result+ .markdown_formatted+ .as_deref()+ .unwrap()+ .contains("deploy-1")+ );++ let calls = calls.lock().unwrap();+ assert_eq!(+ calls.len(),+ 3,+ "Providers and two Execute operations are expected"+ );+ assert_eq!(+ calls[0],+ ("Providers".to_owned(), serde_json::Value::Null, false)+ );+ assert_eq!(calls[1].0, "Execute");+ assert!(calls[1].2, "PrepareBundle uses confidential Execute");+ assert_eq!(calls[2].0, "Execute");+ assert!(+ calls[2].2,+ "Launch carries credentials and must be confidential"+ );+ let prepared: serde_json::Value =+ serde_json::from_str(calls[1].1[0].as_str().unwrap()).unwrap();+ assert_eq!(prepared["operation"], "prepare_bundle");+ assert_eq!(prepared["directory"]["path"], "app");+ assert!(prepared["credentials"]["api_key"].as_str().unwrap() == "fixture-secret");+ let launched: serde_json::Value =+ serde_json::from_str(calls[2].1[0].as_str().unwrap()).unwrap();+ assert_eq!(launched["operation"], "launch");+ assert_eq!(launched["plan"]["bundle"][0]["path"], "index.html");+}++#[tokio::test]+async fn disabled_module_loader_does_not_fall_back_to_a_linked_provider() {+ let workspace = tempfile::tempdir().expect("workspace");+ let mut config = config_with(workspace.path(), true, "fixture-secret");+ config.modules.enabled = false;+ let account = Account::from_config(&config).unwrap().unwrap();+ let tools = account.tools();+ let list = tools+ .iter()+ .find(|tool| tool.name() == "hosting_list_sites")+ .unwrap();+ let result = list.execute(serde_json::json!({})).await.unwrap();+ assert!(result.is_error);+ assert!(+ result.content[0]+ .render()+ .starts_with("MODULE_CALL_REPORTED:")+ );+}++#[tokio::test]+async fn connect_with_config_preserves_embedding_module_policy() {+ let workspace = tempfile::tempdir().expect("workspace");+ let mut config = Config::default();+ config.workspace_dir = workspace.path().to_path_buf();+ config.modules.enabled = false;+ let account = Account::connect_with_config("vercel", "fixture-secret", None, config)+ .expect("account uses the supplied host configuration");+ assert_eq!(account.workspace_dir(), workspace.path());+ let list = account+ .tools()+ .into_iter()+ .find(|tool| tool.name() == "hosting_list_sites")+ .unwrap();+ let result = list.execute(serde_json::json!({})).await.unwrap();+ assert!(result.is_error);+ assert!(+ result.content[0]+ .render()+ .starts_with("MODULE_CALL_REPORTED:")+ );+}++#[tokio::test]+async fn launch_rejects_a_forbidden_workspace_path_before_any_module_call() {+ let workspace = tempfile::tempdir().expect("workspace");+ std::fs::create_dir(workspace.path().join(".ssh")).unwrap();+ let calls = Arc::new(Mutex::new(Vec::new()));+ let account = account_fixture(workspace.path().to_path_buf(), Arc::clone(&calls));+ let launch = account+ .tools()+ .into_iter()+ .find(|tool| tool.name() == "hosting_launch_site")+ .unwrap();++ let result = launch+ .execute(serde_json::json!({"site":"demo", "path":".ssh"}))+ .await+ .unwrap();+ assert!(result.is_error);+ assert!(calls.lock().unwrap().is_empty());+}++#[tokio::test]+async fn confidential_execute_failure_is_not_retried_as_an_ordinary_call() {+ let workspace = tempfile::tempdir().expect("workspace");+ let config = config_with(workspace.path(), true, "never-render-this-secret");+ let account = Account::from_config(&config).unwrap().unwrap();+ let calls = Arc::new(Mutex::new(Vec::new()));+ let calls_out = Arc::clone(&calls);+ let fixture = Arc::new(+ move |member: &str, args: serde_json::Value, confidential: bool| {+ calls_out+ .lock()+ .unwrap()+ .push((member.to_owned(), args, confidential));+ if member == tinyhosts_bus::METHODS[1] {+ Ok(serde_json::json!(["vercel"]).to_string())+ } else {+ Err(anyhow::anyhow!(+ "MODULE_CALL_REPORTED: module transport failed"+ ))+ }+ },+ );+ let account = Account {+ call_fixture: Some(fixture),+ ..account+ };+ let list = account+ .tools()+ .into_iter()+ .find(|tool| tool.name() == "hosting_list_sites")+ .unwrap();++ let result = list.execute(serde_json::json!({})).await.unwrap();+ assert!(result.is_error);+ assert!(+ result.content[0]+ .render()+ .contains("MODULE_CALL_REPORTED: module execution failed")+ );+ assert!(+ !result.content[0]+ .render()+ .contains("never-render-this-secret")+ );+ let calls = calls.lock().unwrap();+ assert_eq!(calls.len(), 2, "one Providers call and one failed Execute");+ assert_eq!(calls[0].0, "Providers");+ assert_eq!(calls[1].0, "Execute");+ assert!(+ calls[1].2,+ "the failed credential-bearing call remains confidential"+ );+}++#[cfg(feature = "crash-reporting")]+#[test]+fn an_operation_with_the_wrong_typed_outcome_is_reported_once_without_reply_data() {+ let workspace = tempfile::tempdir().expect("workspace");+ let config = config_with(workspace.path(), true, "never-render-this-secret");+ let account = Account::from_config(&config).unwrap().unwrap();+ let calls = Arc::new(Mutex::new(Vec::new()));+ let calls_out = Arc::clone(&calls);+ let fixture = Arc::new(+ move |member: &str, args: serde_json::Value, confidential: bool| {+ calls_out+ .lock()+ .unwrap()+ .push((member.to_owned(), args.clone(), confidential));+ if member == tinyhosts_bus::METHODS[1] {+ return Ok(serde_json::json!(["vercel"]).to_string());+ }+ Ok(serde_json::json!({"result":"launch","value":{+ "site":{"id":"private-id","name":"private-site"},+ "created_site":true,+ "database":null,+ "database_env_keys":[],+ "domains":[],+ "deployment":{"id":"private-deployment","site":"private-site","status":"building"}+ }})+ .to_string())+ },+ );+ let account = Account {+ call_fixture: Some(fixture),+ ..account+ };+ let list = account+ .tools()+ .into_iter()+ .find(|tool| tool.name() == "hosting_list_sites")+ .unwrap();+ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap();+ let events = sentry::test::with_captured_events(|| {+ runtime.block_on(async {+ let result = list.execute(serde_json::json!({})).await.unwrap();+ assert!(result.is_error);+ assert!(+ result.content[0]+ .render()+ .contains("MODULE_CALL_REPORTED: module execution failed")+ );+ assert!(!result.content[0].render().contains("private-site"));+ });+ });+ assert_eq!(events.len(), 1, "{events:?}");+ assert_eq!(+ events[0].tags.get("reason_code").map(String::as_str),+ Some("module_fault")+ );+ let calls = calls.lock().unwrap();+ assert_eq!(calls.len(), 2);+ assert!(calls[1].2);+}++#[test]+fn workspace_resolution_refuses_absolute_traversal_and_symlink_escape() {+ let workspace = tempfile::tempdir().expect("workspace");+ let outside = tempfile::tempdir().expect("outside");+ std::fs::create_dir(workspace.path().join("app")).unwrap();+ std::fs::create_dir(workspace.path().join(".ssh")).unwrap();+ #[cfg(unix)]+ std::os::unix::fs::symlink(outside.path(), workspace.path().join("escape")).unwrap();+ assert!(resolve_in_workspace(workspace.path(), "app").is_ok());+ assert!(resolve_in_workspace(workspace.path(), "../outside").is_err());+ assert!(resolve_in_workspace(workspace.path(), ".ssh").is_err());+ assert!(resolve_in_workspace(workspace.path(), outside.path().to_str().unwrap()).is_err());+ #[cfg(unix)]+ assert!(resolve_in_workspace(workspace.path(), "escape").is_err());}#[test]diff --git a/crates/openhuman-core/src/hosting/mod.rs b/crates/openhuman-core/src/hosting/mod.rsindex a4af9235ea..78e73f2693 100644--- a/crates/openhuman-core/src/hosting/mod.rs+++ b/crates/openhuman-core/src/hosting/mod.rs@@ -1,156 +1,264 @@-//! Hosting: putting a workspace on the internet.+//! Hosting tools backed by the compiled TinyHosts module.//!-//! This domain is the seam between OpenHuman and [`tinyhosts`], the unified-//! hosting API. TinyHosts owns everything about a provider — Vercel's endpoints,-//! its deployment protocol, how a marketplace database is provisioned and-//! connected. This module owns everything about *OpenHuman*: where the-//! credential comes from, which directory an agent is allowed to deploy, and how-//! the result is described back to a model.-//!-//! The split is the point. Nothing here knows the word "project" or-//! "readyState", and nothing in `tinyhosts` knows what a workspace is.-//!-//! # What the agent gets-//!-//! Ten tools, in [`tinyhosts::tools`]. `hosting_launch_site` is the one that matters: it-//! turns a directory in the workspace into a live site with a database behind-//! it. `hosting_rollback` is its counterweight — it points production back at-//! an earlier deployment, so an agent that ships a broken site has a way back-//! rather than only a way forward. The rest read or adjust what they produced.-//!-//! # The credential-//!-//! [`Account::from_config`] resolves one from `[hosting].api_key`, falling back-//! to the provider's own environment variables. It returns `Ok(None)` — not an-//! error — when hosting is switched off or no credential resolves, and the-//! registry then does not register the tools at all. A tool that is present and-//! cannot work is worse than one that is absent: a model will retry it.+//! OpenHuman owns credentials, workspace authorization, and tool policy. The+//! provider operations and deployment lifecycle run in the pinned `tinyhosts`+//! TinyBus module through its transport-free `tinyhosts-bus` contract.use std::path::PathBuf;-use std::str::FromStr;use std::sync::Arc;-use tinyhosts::{Credentials, Host, ProviderKind};-use crate::config::Config;-pub use tinyhosts::tools::resolve_in_workspace;-#[cfg(test)]#[path = "hosting_tests.rs"]mod test;-/// One hosting account the agent may act on, and the workspace it deploys from.+mod tools;++/// Resolve a path beneath the workspace root, rejecting absolute paths,+/// traversal, escapes through symlinks, and non-directories.+pub use tools::resolve_in_workspace;++/// One configured hosting account and its authorized workspace.#[derive(Clone)]pub struct Account {- host: Arc<dyn Host>,+ client: crate::modules::client::ModuleClient,+ provider: String,+ api_key: String,+ team: Option<String>,workspace_dir: PathBuf,+ providers_loaded: Arc<tokio::sync::OnceCell<()>>,+ #[cfg(test)]+ call_fixture:+ Option<Arc<dyn Fn(&str, serde_json::Value, bool) -> anyhow::Result<String> + Send + Sync>>,}impl std::fmt::Debug for Account {fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {formatter.debug_struct("Account")- .field("provider", &self.host.kind().as_str())+ .field("provider", &self.provider)+ .field("api_key", &"<redacted>").field("workspace_dir", &self.workspace_dir).finish()}}impl Account {- /// Resolves the configured hosting account, if there is one.- ///- /// Returns `Ok(None)` when `[hosting].enabled` is false, or when no- /// credential can be found — neither is a failure, it is the ordinary state- /// of a host nobody has connected a hosting provider to.- ///- /// # Errors- ///- /// Returns an error only when the configuration is *wrong* rather than- /// absent: an unknown provider slug, a blank configured key, or a client- /// that cannot be built.+ /// Resolve the enabled provider and credential without loading its module.pub fn from_config(config: &Config) -> anyhow::Result<Option<Self>> {if !config.hosting.enabled {return Ok(None);}-- let provider = ProviderKind::from_str(&config.hosting.provider)?;- let credentials = if config.hosting.has_api_key() {- let credentials = Credentials::new(config.hosting.api_key.clone())?;- match config.hosting.team() {- Some(team) => credentials.with_team(team),- None => credentials,- }+ let provider = config.hosting.provider.trim().to_ascii_lowercase();+ if provider != "vercel" {+ anyhow::bail!("unknown hosting provider `{}`", config.hosting.provider);+ }+ let (api_key, uses_environment_credential) = if config.hosting.has_api_key() {+ (config.hosting.api_key.trim().to_owned(), false)} else {- match provider.credentials_from_env() {- Ok(credentials) => credentials,- // No key anywhere. The tools are simply not offered.- Err(error) => {- tracing::debug!(- provider = provider.as_str(),- %error,- "[hosting] enabled but no credential resolved; tools not registered"- );- return Ok(None);- }- }+ (+ ["TINYHOSTS_VERCEL_TOKEN", "VERCEL_TOKEN"]+ .into_iter()+ .find_map(|name| {+ std::env::var(name)+ .ok()+ .filter(|value| !value.trim().is_empty())+ })+ .unwrap_or_default(),+ true,+ )};-- let host = tinyhosts::connect(provider, credentials)?;- tracing::info!(- provider = provider.as_str(),- "[hosting] hosting tools enabled"- );-+ if api_key.is_empty() {+ tracing::debug!(+ provider,+ "[hosting] no credential resolved; tools not registered"+ );+ return Ok(None);+ }Ok(Some(Self {- host: Arc::from(host),+ client: crate::modules::client::ModuleClient::new(config.clone()),+ provider,+ api_key,+ team: config+ .hosting+ .team()+ .map(str::to_owned)+ .or_else(|| uses_environment_credential.then(env_team).flatten()),workspace_dir: config.workspace_dir.clone(),+ providers_loaded: Arc::new(tokio::sync::OnceCell::new()),+ #[cfg(test)]+ call_fixture: None,}))}- /// Builds an account from credentials an embedder resolved itself.- ///- /// OpenCompany holds one hosting credential per company, in that company's- /// secret store rather than in this process's configuration, and deploys- /// into that company's workspace. This is the seam it uses: the provider- /// slug and key as strings, so an embedder does not have to name- /// `tinyhosts` in its own dependency graph to reach the tools.- ///- /// # Errors- ///- /// Returns an error for an unknown provider slug, a blank key, or a client- /// that cannot be built.+ /// Build an account from a credential supplied by an embedding host.pub fn connect(provider: &str,api_key: &str,team: Option<&str>,workspace_dir: PathBuf,) -> anyhow::Result<Self> {- let provider = ProviderKind::from_str(provider)?;- let credentials = Credentials::new(api_key)?;- let credentials = match team {- Some(team) => credentials.with_team(team),- None => credentials,- };+ let mut config = Config::default();+ config.workspace_dir = workspace_dir;+ Self::connect_with_config(provider, api_key, team, config)+ }+ /// Connect using embedding-host configuration, including its module+ /// artifact roots and loader policy.+ pub fn connect_with_config(+ provider: &str,+ api_key: &str,+ team: Option<&str>,+ config: Config,+ ) -> anyhow::Result<Self> {+ if provider.trim().to_ascii_lowercase() != "vercel" {+ anyhow::bail!("unknown hosting provider `{provider}`");+ }+ if api_key.trim().is_empty() {+ anyhow::bail!("hosting API key must not be blank");+ }+ let workspace_dir = config.workspace_dir.clone();Ok(Self {- host: Arc::from(tinyhosts::connect(provider, credentials)?),+ client: crate::modules::client::ModuleClient::new(config),+ provider: "vercel".to_owned(),+ api_key: api_key.trim().to_owned(),+ team: team+ .map(str::trim)+ .filter(|team| !team.is_empty())+ .map(str::to_owned),workspace_dir,+ providers_loaded: Arc::new(tokio::sync::OnceCell::new()),+ #[cfg(test)]+ call_fixture: None,})}- /// The provider client, shared by every tool.- pub fn host(&self) -> Arc<dyn Host> {- Arc::clone(&self.host)- }-- /// The workspace the deployable directories live under.+ /// The workspace whose directories can be deployed.pub fn workspace_dir(&self) -> &PathBuf {&self.workspace_dir}- /// The agent tools this account exposes.+ /// The model-facing tools from the released TinyHosts declaration bundle.pub fn tools(&self) -> Vec<Box<dyn tinytools::Tool>> {- tinyhosts::tools::hosting_tools(&self.host, &self.workspace_dir)+ tools::hosting_tools(self.clone())+ }++ async fn execute(&self, operation: serde_json::Value) -> anyhow::Result<serde_json::Value> {+ use serde_json::json;+ self.providers_loaded+ .get_or_try_init(|| async {+ let response = self.call_providers().await?;+ let providers: Vec<String> = serde_json::from_str(&response).map_err(|_| {+ crate::modules::client::ModuleClient::report_malformed_reply("tinyhosts");+ anyhow::anyhow!(+ crate::modules::client::ModuleCallError::ModuleFault.to_string()+ )+ })?;+ if !providers.iter().any(|provider| provider == &self.provider) {+ crate::modules::client::ModuleClient::report_unavailable("tinyhosts");+ anyhow::bail!(crate::modules::client::ModuleCallError::Unavailable.to_string());+ }+ Ok::<(), anyhow::Error>(())+ })+ .await?;+ let mut request = operation;+ let object = request+ .as_object_mut()+ .ok_or_else(|| anyhow::anyhow!("hosting operation must be an object"))?;+ object.insert("provider".into(), json!(self.provider));+ object.insert(+ "credentials".into(),+ json!({"api_key": self.api_key, "team": self.team}),+ );+ let operation_name = request+ .get("operation")+ .and_then(serde_json::Value::as_str)+ .unwrap_or_default()+ .to_owned();+ let request = serde_json::to_string(&request)?;+ let outcome: tinyhosts_bus::rpc::Outcome = self+ .call_execute_json(&request)+ .await+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;+ if !outcome_matches(&operation_name, &outcome) {+ crate::modules::client::ModuleClient::report_malformed_reply("tinyhosts");+ return Err(anyhow::anyhow!(+ crate::modules::client::ModuleCallError::ModuleFault.to_string()+ ));+ }+ let value = serde_json::to_value(outcome)?;+ Ok(value+ .get("value")+ .cloned()+ .unwrap_or(serde_json::Value::Null))+ }++ async fn call_providers(&self) -> anyhow::Result<String> {+ #[cfg(test)]+ if let Some(fixture) = &self.call_fixture {+ return fixture(tinyhosts_bus::METHODS[1], serde_json::Value::Null, false);+ }+ self.client+ .call::<String>("tinyhosts", tinyhosts_bus::METHODS[1], ())+ .await+ .map_err(|error| anyhow::anyhow!(error.to_string()))+ }++ async fn call_execute_json(+ &self,+ request: &str,+ ) -> Result<tinyhosts_bus::rpc::Outcome, crate::modules::client::ModuleCallError> {+ #[cfg(test)]+ if let Some(fixture) = &self.call_fixture {+ let response = fixture(+ tinyhosts_bus::METHODS[0],+ serde_json::json!([request]),+ true,+ )+ .map_err(|_| crate::modules::client::ModuleCallError::ModuleFault)?;+ return serde_json::from_str(&response).map_err(|_| {+ crate::modules::client::ModuleClient::report_malformed_reply("tinyhosts");+ crate::modules::client::ModuleCallError::ModuleFault+ });+ }+ self.client+ .call_confidential_json::<tinyhosts_bus::rpc::Outcome>(+ "tinyhosts",+ tinyhosts_bus::METHODS[0],+ (request,),+ )+ .await}}++fn outcome_matches(operation: &str, outcome: &tinyhosts_bus::rpc::Outcome) -> bool {+ use tinyhosts_bus::rpc::Outcome;+ match operation {+ "prepare_bundle" => matches!(outcome, Outcome::PreparedBundle(_)),+ "launch" => matches!(outcome, Outcome::Launch(_)),+ "create_site" => matches!(outcome, Outcome::Site(_)),+ "find_site" => matches!(outcome, Outcome::Site(_) | Outcome::NoSite),+ "list_sites" => matches!(outcome, Outcome::Sites(_)),+ "set_env" | "attach_database" | "promote" => matches!(outcome, Outcome::Done),+ "list_env" => matches!(outcome, Outcome::Env(_)),+ "provision_database" => matches!(outcome, Outcome::Database(_)),+ "deploy" | "deployment" => matches!(outcome, Outcome::Deployment(_)),+ "list_deployments" => matches!(outcome, Outcome::Deployments(_)),+ "deployment_logs" => matches!(outcome, Outcome::DeploymentLogs(_)),+ "add_domain" => matches!(outcome, Outcome::Domain(_)),+ "list_domains" => matches!(outcome, Outcome::Domains(_)),+ "analytics" => matches!(outcome, Outcome::Analytics(_)),+ _ => false,+ }+}++fn env_team() -> Option<String> {+ ["TINYHOSTS_VERCEL_TEAM_ID", "VERCEL_TEAM_ID"]+ .into_iter()+ .find_map(|name| {+ std::env::var(name)+ .ok()+ .filter(|value| !value.trim().is_empty())+ })+}diff --git a/crates/openhuman-core/src/hosting/tools.rs b/crates/openhuman-core/src/hosting/tools.rsnew file mode 100644index 0000000000..38a3f2e0fe--- /dev/null+++ b/crates/openhuman-core/src/hosting/tools.rs@@ -0,0 +1,484 @@+//! OpenHuman tool adapters over the released TinyHosts bus vocabulary.++use std::path::{Component, Path, PathBuf};++use async_trait::async_trait;+use serde_json::{Value, json};+use tinyhosts_bus::{PermissionLevel as ContractPermission, ToolDeclaration};+use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult};++use super::Account;++pub(super) fn hosting_tools(account: Account) -> Vec<Box<dyn Tool>> {+ let declarations: Vec<ToolDeclaration> =+ serde_json::from_str(tinyhosts_bus::TOOL_DECLARATIONS_JSON)+ .expect("released TinyHosts tool declarations are valid");+ declarations+ .into_iter()+ .map(|declaration| {+ Box::new(HostingTool {+ account: account.clone(),+ declaration,+ }) as Box<dyn Tool>+ })+ .collect()+}++pub fn resolve_in_workspace(workspace_dir: &Path, relative: &str) -> anyhow::Result<PathBuf> {+ let relative = relative.trim();+ let candidate = Path::new(if relative.is_empty() { "." } else { relative });+ if candidate.is_absolute()+ || candidate.components().any(|part| {+ matches!(+ part,+ Component::ParentDir | Component::RootDir | Component::Prefix(_)+ )+ })+ {+ anyhow::bail!("path must stay inside the workspace");+ }+ let root = workspace_dir+ .canonicalize()+ .map_err(|_| anyhow::anyhow!("cannot access the workspace directory"))?;+ if crate::security::SecurityPolicy::is_always_forbidden(&root) {+ anyhow::bail!("workspace path is always forbidden");+ }+ let canonical = root+ .join(candidate)+ .canonicalize()+ .map_err(|_| anyhow::anyhow!("cannot access the requested workspace directory"))?;+ if !canonical.starts_with(&root) {+ anyhow::bail!("path escapes the workspace");+ }+ if crate::security::SecurityPolicy::is_always_forbidden(&canonical) {+ anyhow::bail!("workspace path is always forbidden");+ }+ if !canonical.is_dir() {+ anyhow::bail!("requested workspace path is not a directory");+ }+ Ok(canonical)+}++#[derive(Debug)]+struct HostingTool {+ account: Account,+ declaration: ToolDeclaration,+}++impl HostingTool {+ async fn run(&self, args: Value) -> anyhow::Result<ToolResult> {+ match self.declaration.name.as_str() {+ "hosting_launch_site" => self.launch(args).await,+ "hosting_deployment_status" => {+ let id = required_str(&args, "deployment_id")?;+ self.pretty(operation("deployment", json!({"id": id})))+ .await+ }+ "hosting_list_deployments" => {+ let site = required_str(&args, "site")?;+ let limit = bounded(&args, "limit", 20, 1, 100);+ self.pretty(operation(+ "list_deployments",+ json!({"site": site, "limit": limit}),+ ))+ .await+ }+ "hosting_deployment_logs" => {+ let id = required_str(&args, "deployment_id")?;+ let limit = bounded(&args, "limit", 100, 1, 1000) as usize;+ let outcome = self+ .account+ .execute(operation("deployment_logs", json!({"id": id})))+ .await?;+ let mut logs = outcome;+ if let Some(items) = logs.as_array_mut() {+ if items.len() > limit {+ *items = items.split_off(items.len() - limit);+ }+ }+ Ok(ToolResult::success(serde_json::to_string_pretty(&logs)?))+ }+ "hosting_rollback" => self.rollback(args).await,+ "hosting_list_sites" => {+ let limit = bounded(&args, "limit", 20, 1, 100);+ self.pretty(operation("list_sites", json!({"limit": limit})))+ .await+ }+ "hosting_set_env" => self.set_env(args).await,+ "hosting_add_domain" => self.add_domain(args).await,+ "hosting_domain_status" => {+ let site = required_str(&args, "site")?;+ self.pretty(operation("list_domains", json!({"site": site})))+ .await+ }+ "hosting_analytics" => self.analytics(args).await,+ _ => Ok(ToolResult::error("hosting tool declaration is unsupported")),+ }+ }++ async fn pretty(&self, request: Value) -> anyhow::Result<ToolResult> {+ let value = self.account.execute(request).await?;+ Ok(ToolResult::success(serde_json::to_string_pretty(&value)?))+ }++ async fn launch(&self, args: Value) -> anyhow::Result<ToolResult> {+ let site = required_str(&args, "site")?;+ let relative = args.get("path").and_then(Value::as_str).unwrap_or(".");+ let workspace = self+ .account+ .workspace_dir()+ .canonicalize()+ .map_err(|_| anyhow::anyhow!("cannot access the workspace directory"))?;+ let source = resolve_in_workspace(&workspace, relative)?;+ let relative_source = source+ .strip_prefix(&workspace)+ .map_err(|_| anyhow::anyhow!("path escapes the workspace"))?;+ let prepared = self+ .account+ .execute(operation(+ "prepare_bundle",+ json!({+ "directory": {"workspace": workspace, "path": relative_source}+ }),+ ))+ .await?;+ let bundle = prepared+ .get("bundle")+ .cloned()+ .ok_or_else(|| anyhow::anyhow!("hosting module returned an invalid prepared bundle"))?;+ let mut env = Vec::new();+ if let Some(values) = args.get("env").and_then(Value::as_object) {+ for (key, value) in values {+ env.push(json!({"key": key, "value": env_string(key, value)?, "targets": [], "secret": false}));+ }+ }+ let database = args.get("database").and_then(Value::as_str).map(str::trim).filter(|name| !name.is_empty()).map(|name| {+ json!({"name": name, "kind": args.get("database_kind").and_then(Value::as_str).unwrap_or("postgres")})+ });+ let domains: Vec<String> = args+ .get("domains")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ .map(str::trim)+ .filter(|value| !value.is_empty())+ .map(str::to_owned)+ .collect();+ let target = if args+ .get("production")+ .and_then(Value::as_bool)+ .unwrap_or(false)+ {+ "production"+ } else {+ "preview"+ };+ let plan = json!({+ "site": {"name": site}, "bundle": bundle, "database": database,+ "env": env, "domains": domains, "target": target+ });+ let result = self+ .account+ .execute(operation("launch", json!({"plan": plan})))+ .await?;+ let text = launch_summary(&result);+ Ok(ToolResult::success_with_markdown(result, text))+ }++ async fn set_env(&self, args: Value) -> anyhow::Result<ToolResult> {+ let site = required_str(&args, "site")?;+ let Some(env) = args.get("env").and_then(Value::as_object) else {+ return Ok(ToolResult::error("`env` must be an object of variables"));+ };+ let targets = if args+ .get("production_only")+ .and_then(Value::as_bool)+ .unwrap_or(false)+ {+ vec!["production"]+ } else {+ Vec::new()+ };+ let secret = args.get("secret").and_then(Value::as_bool).unwrap_or(false);+ let mut vars = Vec::with_capacity(env.len());+ for (key, value) in env {+ vars.push(json!({"key": key, "value": env_string(key, value)?, "targets": targets, "secret": secret}));+ }+ self.account+ .execute(operation("set_env", json!({"site": site, "vars": vars})))+ .await?;+ Ok(ToolResult::success(format!(+ "Set {} on {site}. Redeploy the site for a build-time variable to take effect.",+ env.keys().cloned().collect::<Vec<_>>().join(", ")+ )))+ }++ async fn add_domain(&self, args: Value) -> anyhow::Result<ToolResult> {+ let site = required_str(&args, "site")?;+ let domain = required_str(&args, "domain")?;+ let outcome = self+ .account+ .execute(operation(+ "add_domain",+ json!({"site": site, "domain": domain}),+ ))+ .await?;+ let name = outcome+ .get("name")+ .and_then(Value::as_str)+ .unwrap_or(&domain);+ if outcome+ .get("verified")+ .and_then(Value::as_bool)+ .unwrap_or(false)+ {+ Ok(ToolResult::success(format!(+ "{name} is attached to {site} and verified."+ )))+ } else {+ Ok(ToolResult::success(format!(+ "{name} is attached to {site} but not verified yet: its DNS records still have to point at the provider."+ )))+ }+ }++ async fn rollback(&self, args: Value) -> anyhow::Result<ToolResult> {+ let site = required_str(&args, "site")?;+ let id = required_str(&args, "deployment_id")?;+ let deployment = self+ .account+ .execute(operation("deployment", json!({"id": id})))+ .await?;+ if !rollback_target_is_ready(&deployment) {+ let status = rollback_status(&deployment);+ return Ok(ToolResult::error(format!(+ "Deployment `{id}` is {status}, so it cannot be promoted — only a deployment that finished building can serve traffic. Use hosting_list_deployments to find one that is ready."+ )));+ }+ self.account+ .execute(operation(+ "promote",+ json!({"site": site, "deployment": id}),+ ))+ .await?;+ Ok(ToolResult::success(+ match deployment.get("url").and_then(Value::as_str) {+ Some(url) => format!(+ "{site} is now serving deployment `{id}` in production ({url}). The change is at the provider's edge; nothing was rebuilt."+ ),+ None => format!(+ "{site} is now serving deployment `{id}` in production. The change is at the provider's edge; nothing was rebuilt."+ ),+ },+ ))+ }++ async fn analytics(&self, args: Value) -> anyhow::Result<ToolResult> {+ let site = required_str(&args, "site")?;+ let days = bounded(&args, "days", 7, 1, 365) as u64;+ let until = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |duration| {+ u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)+ });+ let breakdown = match args.get("breakdown").and_then(Value::as_str) {+ None => None,+ Some("country") => Some("country"),+ Some("request_path") => Some("request_path"),+ Some("device_type") => Some("device_type"),+ Some("browser_name") => Some("browser_name"),+ Some("os_name") => Some("os_name"),+ Some("referrer_hostname") => Some("referrer_hostname"),+ Some("route") => Some("route"),+ Some(other) => {+ return Ok(ToolResult::error(format!(+ "`breakdown` must be one of country, request_path, device_type, \+ browser_name, os_name, referrer_hostname, route — not `{other}`"+ )));+ }+ };+ self.pretty(operation(+ "analytics",+ json!({"query": {+ "site": site, "since_ms": until.saturating_sub(days * 24 * 60 * 60 * 1000),+ "until_ms": until, "breakdown": breakdown, "limit": 10+ }}),+ ))+ .await+ }+}++#[async_trait]+impl Tool for HostingTool {+ fn name(&self) -> &str {+ &self.declaration.name+ }+ fn description(&self) -> &str {+ &self.declaration.description+ }+ fn parameters_schema(&self) -> Value {+ self.declaration.parameters_schema.clone()+ }+ fn permission_level(&self) -> PermissionLevel {+ match self.declaration.permission_level {+ ContractPermission::ReadOnly => PermissionLevel::ReadOnly,+ ContractPermission::Write => PermissionLevel::Write,+ }+ }+ fn external_effect(&self) -> bool {+ self.declaration.external_effect+ }+ fn supports_markdown(&self) -> bool {+ self.name() == "hosting_launch_site"+ }+ async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {+ match self.run(args).await {+ Ok(result) => Ok(result),+ Err(error) => Ok(ToolResult::error(error.to_string())),+ }+ }+ async fn execute_with_options(+ &self,+ args: Value,+ _options: ToolCallOptions,+ ) -> anyhow::Result<ToolResult> {+ self.execute(args).await+ }+}++fn operation(name: &str, mut fields: Value) -> Value {+ if let Some(object) = fields.as_object_mut() {+ object.insert("operation".into(), json!(name));+ }+ fields+}++fn required_str(args: &Value, key: &str) -> anyhow::Result<String> {+ args.get(key)+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|value| !value.is_empty())+ .map(str::to_owned)+ .ok_or_else(|| anyhow::anyhow!("`{key}` is required"))+}++fn env_string(key: &str, value: &Value) -> anyhow::Result<String> {+ match value {+ Value::String(value) => Ok(value.clone()),+ Value::Number(_) | Value::Bool(_) => Ok(value.to_string()),+ _ => anyhow::bail!("`env.{key}` must be a string, number, or boolean"),+ }+}++fn bounded(args: &Value, key: &str, default: u64, min: u64, max: u64) -> u32 {+ args.get(key)+ .and_then(Value::as_i64)+ .map(|value| value.clamp(min as i64, max as i64) as u64)+ .or_else(|| args.get(key).and_then(Value::as_u64))+ .unwrap_or(default)+ .clamp(min, max) as u32+}++fn launch_summary(launch: &Value) -> String {+ let site = launch+ .pointer("/site/name")+ .and_then(Value::as_str)+ .unwrap_or("site");+ let created = launch+ .get("created_site")+ .and_then(Value::as_bool)+ .unwrap_or(false);+ let deployment = launch+ .pointer("/deployment/id")+ .and_then(Value::as_str)+ .unwrap_or("unknown");+ let status = launch+ .pointer("/deployment/status")+ .and_then(Value::as_str)+ .map(status_debug)+ .unwrap_or("unknown");+ let mut lines = vec![format!(+ "Site **{site}** ({}), deployment `{deployment}` is {status}.",+ if created {+ "created"+ } else {+ "already existed"+ }+ )];+ match launch.pointer("/deployment/url").and_then(Value::as_str) {+ Some(url) => lines.push(format!("It will serve from {url} once the build finishes — poll `hosting_deployment_status` with the deployment id.")),+ None => lines.push("The provider has not assigned a URL yet; poll `hosting_deployment_status` with the deployment id.".to_owned()),+ }+ if let Some(database) = launch.get("database").filter(|value| !value.is_null()) {+ let name = database+ .get("name")+ .and_then(Value::as_str)+ .unwrap_or("database");+ let kind = database+ .pointer("/kind")+ .and_then(Value::as_str)+ .unwrap_or("database");+ let status = database+ .get("status")+ .and_then(Value::as_str)+ .unwrap_or("unknown");+ let keys = launch+ .get("database_env_keys")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ .collect::<Vec<_>>();+ lines.push(format!("Database **{name}** ({kind}) is {status}; it injected {} into the site's environment. The values are the provider's — nothing here can read them.", if keys.is_empty() { "no variables".to_owned() } else { keys.join(", ") }));+ }+ if let Some(domains) = launch+ .get("domains")+ .and_then(Value::as_array)+ .filter(|domains| !domains.is_empty())+ {+ let unverified = domains+ .iter()+ .filter(|domain| {+ !domain+ .get("verified")+ .and_then(Value::as_bool)+ .unwrap_or(false)+ })+ .filter_map(|domain| domain.get("name").and_then(Value::as_str))+ .collect::<Vec<_>>();+ if unverified.is_empty() {+ lines.push("Every domain is verified.".to_owned());+ } else {+ lines.push(format!("These domains still need their DNS records pointed at the provider before they serve traffic: {}.", unverified.join(", ")));+ }+ }+ lines.join("\n\n")+}++fn status_debug(status: &str) -> &'static str {+ match status {+ "queued" => "Queued",+ "building" => "Building",+ "ready" => "Ready",+ "failed" => "Failed",+ "canceled" => "Canceled",+ _ => "Other",+ }+}++fn rollback_target_is_ready(deployment: &Value) -> bool {+ deployment.get("status").and_then(Value::as_str) == Some("ready")+}++fn rollback_status(deployment: &Value) -> &str {+ deployment+ .get("status")+ .and_then(Value::as_str)+ .map(status_debug)+ .unwrap_or("unknown status")+}++#[cfg(test)]+#[path = "tools_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/hosting/tools_tests.rs b/crates/openhuman-core/src/hosting/tools_tests.rsnew file mode 100644index 0000000000..bcfe306f07--- /dev/null+++ b/crates/openhuman-core/src/hosting/tools_tests.rs@@ -0,0 +1,27 @@+use super::*;++#[test]+fn rollback_refuses_everything_except_a_ready_deployment() {+ for status in ["queued", "building", "failed", "canceled", "unknown"] {+ let deployment = json!({"status": status});+ assert!(!rollback_target_is_ready(&deployment), "{status}");+ assert_ne!(rollback_status(&deployment), "Ready");+ }+ let ready = json!({"status": "ready"});+ assert!(rollback_target_is_ready(&ready));+ assert_eq!(rollback_status(&ready), "Ready");+}++#[test]+fn launch_summary_keeps_the_model_facing_status_and_wait_guidance() {+ let launch = json!({+ "site": {"name": "demo"},+ "created_site": true,+ "deployment": {"id": "dpl_1", "status": "building", "url": "https://demo.example"},+ "database": null,+ "domains": []+ });+ let summary = launch_summary(&launch);+ assert!(summary.contains("Site **demo** (created), deployment `dpl_1` is Building."));+ assert!(summary.contains("poll `hosting_deployment_status`"));+}diff --git a/crates/openhuman-core/src/modules/registry/records_extra.rs b/crates/openhuman-core/src/modules/registry/records_extra.rsindex ef34242287..69bc7b739a 100644--- a/crates/openhuman-core/src/modules/registry/records_extra.rs+++ b/crates/openhuman-core/src/modules/registry/records_extra.rs@@ -144,63 +144,63 @@ pub(crate) const TINYHOSTS: ModuleRecord = ModuleRecord {description: "Hosting provider operations",bus_name: "ai.tinyhumans.tinyhosts.Hosting",object_path: "/ai/tinyhumans/tinyhosts/Hosting",- version: "0.2.3",- release_url: "https://github.com/tinyhumansai/tinyhosts/releases/tag/v0.2.3",+ version: "0.3.0",+ release_url: "https://github.com/tinyhumansai/tinyhosts/releases/tag/v0.3.0",assets: &[PlatformAsset {host_key: "ubuntu-24.04-x86_64",- archive: "tinyhosts-0.2.3-ubuntu-24.04-x86_64.tar.gz",- sha256: "a0e623c5f541c1d21f2e7aba16ce3074fcee06f014c39c43fd2a7f7a3a77f6dd",+ archive: "tinyhosts-0.3.0-ubuntu-24.04-x86_64.tar.gz",+ sha256: "368f00ee397649481ff8f61d33eeb8b908cc416d6b2f9d4ef3c81263d6b0460e",},PlatformAsset {host_key: "ubuntu-24.04-arm64",- archive: "tinyhosts-0.2.3-ubuntu-24.04-arm64.tar.gz",- sha256: "0e0b0467c08e3f79275fbbd46e84df3dea570f896b746031a581d030eb7eb9c5",+ archive: "tinyhosts-0.3.0-ubuntu-24.04-arm64.tar.gz",+ sha256: "e298942fddec8930fd78651632c02abe78968a17ab3589608875b8dc4f731669",},PlatformAsset {host_key: "ubuntu-22.04-x86_64",- archive: "tinyhosts-0.2.3-ubuntu-22.04-x86_64.tar.gz",- sha256: "6d622d9497ebdea67323125e25dab0d6497e0d3f39c351f3ef13de016076fc8b",+ archive: "tinyhosts-0.3.0-ubuntu-22.04-x86_64.tar.gz",+ sha256: "f7c9484176b62357fb449eb79830e3df0eebfd4e0814c8d8e1c58669d829f482",},PlatformAsset {host_key: "ubuntu-22.04-arm64",- archive: "tinyhosts-0.2.3-ubuntu-22.04-arm64.tar.gz",- sha256: "6648fa3debb518ab5090aef2e49a3eed147ca00eef5c0c7e22576768cb7d1f51",+ archive: "tinyhosts-0.3.0-ubuntu-22.04-arm64.tar.gz",+ sha256: "576ff6204ccaa1e2dc2ef1b27762848efa4555d4d32ef46b4c329daf1e04eac3",},PlatformAsset {host_key: "macos-26-arm64",- archive: "tinyhosts-0.2.3-macos-26-arm64.tar.gz",- sha256: "8c8d62564df5fad2b3d4da30e56e86969584aacb30a22875f96a6209d1e0cfae",+ archive: "tinyhosts-0.3.0-macos-26-arm64.tar.gz",+ sha256: "b0083e70b567659d095a1ff0f9d2c8cb5bafe110d90fb08527c509362ce77a55",},PlatformAsset {host_key: "macos-26-x86_64",- archive: "tinyhosts-0.2.3-macos-26-x86_64.tar.gz",- sha256: "801cec78dfe01006ff6811b445730de3f246087f1cbe9f0d63da8bcf55bf3f5d",+ archive: "tinyhosts-0.3.0-macos-26-x86_64.tar.gz",+ sha256: "44fa7c9efde0c388f154f154809ce2829460bae4931f27d20f8f0d3ee3bf2a8c",},PlatformAsset {host_key: "macos-15-arm64",- archive: "tinyhosts-0.2.3-macos-15-arm64.tar.gz",- sha256: "10b9ac5b6e414064b4d9abb9cc4cb47b7a6e80e0cbfd0c29a8b1afe41637fb0f",+ archive: "tinyhosts-0.3.0-macos-15-arm64.tar.gz",+ sha256: "56ca93b2cab2010ff599c38179eb99f6ad67631e39f671be973256c3d9142381",},PlatformAsset {host_key: "macos-15-x86_64",- archive: "tinyhosts-0.2.3-macos-15-x86_64.tar.gz",- sha256: "3b9b608d4fa3b638c93485fefca3825ebdc4220d0fc4dc2312f94a570dadcb83",+ archive: "tinyhosts-0.3.0-macos-15-x86_64.tar.gz",+ sha256: "0ffb9fc8d1c7fc7d95a7808af7722d8c6537a508c0c3a294ecf8fb8a28430207",},PlatformAsset {host_key: "windows-2025-x86_64",- archive: "tinyhosts-0.2.3-windows-2025-x86_64.zip",- sha256: "b9caaed8b6b2235098c88477d8101f2dcd26e4d5a68109957836272616f25b71",+ archive: "tinyhosts-0.3.0-windows-2025-x86_64.zip",+ sha256: "3d6d5f7fd0806ac6fd6c2ed0c60a9155d6c09a861ebd1ac0c43864e969f88fb9",},PlatformAsset {host_key: "windows-2022-x86_64",- archive: "tinyhosts-0.2.3-windows-2022-x86_64.zip",- sha256: "a1ca38023401efd5fda4db6f8b30701dd9a209563f74d5a961e6572e7c4b6223",+ archive: "tinyhosts-0.3.0-windows-2022-x86_64.zip",+ sha256: "a5003f1254052828d6fa362b993b0bed6b7256c252f969536090e148378c331f",},PlatformAsset {host_key: "windows-11-arm64",- archive: "tinyhosts-0.2.3-windows-11-arm64.zip",- sha256: "3912ad5a10ce87e2de5e91e29f8beb1ffb669e31ca2dcdd7e0e522b63607adf7",+ archive: "tinyhosts-0.3.0-windows-11-arm64.zip",+ sha256: "21f8909a2a81a541e3d0347510b2bf25baec59438a5536edcd57e65fae7f4a4d",},],load: LoadPolicy::Lazy,diff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rsindex f4a6151ef0..8e7c8f227f 100644--- a/crates/openhuman-core/src/tools/ops.rs+++ b/crates/openhuman-core/src/tools/ops.rs@@ -758,10 +758,11 @@ pub fn all_tools_with_runtime(action_dir,));- // Hosting tools — deploy a workspace directory to a real hosting provider,- // with a managed database wired into it. Registered only once a credential+ // Hosting tools — deploy a workspace directory through the compiled+ // TinyHosts module. Registered only once a credential// actually resolves (`[hosting].api_key`, else the provider's environment- // variables): a tool that cannot work is worse than one that is absent,+ // variables). Module loading stays lazy until a tool is invoked.+ // A tool that cannot work is worse than one that is absent,// because a model retries it. A misconfigured section — an unknown provider// slug, a blank key — is logged and skipped rather than failing startup,// since nothing else in the process depends on hosting.diff --git a/docs/module-boundary-inventory.md b/docs/module-boundary-inventory.mdindex 81a57002e4..4b6f2f322e 100644--- a/docs/module-boundary-inventory.md+++ b/docs/module-boundary-inventory.md@@ -17,7 +17,7 @@ copying its implementation into a host, or accepting weaker isolation.| tinyconnectors | tinyconnectors, tinyconnectors-sync | tinyconnectors-bus | core integrations, credentials and triggers | Argument preparation, calendar defaults, task windows, structured provider errors, trigger archives; preserve sign-in/out reconciliation || tinymcp | tinymcp | tinymcp-bus | core MCP registry, supervisor, CLI stdio/HTTP server | Supervisor notifications, server protocol operations and callbacks for approved host tools/resources/prompts || tinychannels | tinychannels, tinychannels-runtime; runtime/crypto code in contract | tinychannels-bus | core channels and podcast email, TinyHumans host, CLI REPL | Move providers, signing and pairing out of contract; relay config, pairing, start/stop/send/status, inbound/status callbacks, bounded delivery/draining |-| tinyhosts | tinyhosts | tinyhosts-bus (missing at pin) | core hosting tools | Extract vocabulary and tool declarations; consume Execute/Providers after host validation/approval |+| tinyhosts | tinyhosts | tinyhosts-bus | core hosting tools | Consume released Execute/Providers contract; keep workspace authorization, credentials, and approval policy in OpenHuman || tinywallet | tinywallet-crypto, tinywallet-web3, tinywallet-x402 via bus and direct imports | tinywallet-bus | core wallet/web3/x402 | Move behavioral re-exports out of bus; validation, transaction construction, quotes, swaps, payments, budgets, ledger; retain host custody/approval and confidential attestation || tinybox | tinybox-core, tinybox-jail, tinybox-docker, tinybox-host, tinybox-ssh | tinybox-bus (missing at pin) | core sandbox and security, desktop gateways | Discovery-only module needs handle-based sandbox/exec/streams/cancel/files/forward/status/close and shell-analysis facts; pre-core gateways use process loader || tinycomputer | tinycomputer-accessibility | tinycomputer-bus | core voice, paste/focus and permission checks | Permission, focus, paste, Globe listener vocabulary/operations; preserve native thread and target rules |diff --git a/scripts/ci/module-boundaries.json b/scripts/ci/module-boundaries.jsonindex 4f2f5eb3a6..572dd8c70a 100644--- a/scripts/ci/module-boundaries.json+++ b/scripts/ci/module-boundaries.json@@ -95,6 +95,11 @@"name": "tinysearch-bus","manifest": "vendor/tinysearch/crates/tinysearch-bus/Cargo.toml","owner": "https://github.com/tinyhumansai/tinysearch"+ },+ {+ "name": "tinyhosts-bus",+ "manifest": "vendor/tinyhosts/crates/tinyhosts-bus/Cargo.toml",+ "owner": "https://github.com/tinyhumansai/tinyhosts"}],"pendingContracts": [@@ -103,12 +108,6 @@"manifest": "vendor/tinybox/crates/tinybox-bus/Cargo.toml","owner": "https://github.com/tinyhumansai/tinybox","reason": "Sandbox execution, shell analysis and pre-core gateways need a bus contract."- },- {- "name": "tinyhosts-bus",- "manifest": "vendor/tinyhosts/crates/tinyhosts-bus/Cargo.toml",- "owner": "https://github.com/tinyhumansai/tinyhosts",- "reason": "Hosting contract crate has not been published."}],"exceptions": [@@ -132,11 +131,6 @@"package": "tinychannels-runtime","reason": "Providers, relay, pairing and delivery lifecycles still call the implementation."},- {- "scope": "hosts",- "package": "tinyhosts",- "reason": "Hosting contract crate has not been published."- },{"scope": "hosts","package": "tinybox-core",diff --git a/vendor/tinyhosts b/vendor/tinyhostsindex 94098349c8..6ad6e8b2c0 160000--- a/vendor/tinyhosts+++ b/vendor/tinyhosts@@ -1 +1 @@-Subproject commit 94098349c8d75269438e8903f9042148b1ab4752+Subproject commit 6ad6e8b2c038b5214cb4f2cd49927f8cc11e9dc7